text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "QmitkSimpleExampleFunctionality.h"
#include "QmitkSimpleExampleControls.h"
#include <qaction.h>
#include "slicer.xpm"
// for slice-navigation
#include <mitkEventMapper.h>
#include <mitkGlobalInteraction.h>
#include <mitkBaseRenderer.h>
#include "QmitkRenderWindow.h"
#include "QmitkSelectableGLWidget.h"
#include "QmitkStdMultiWidget.h"
#include <QmitkStepperAdapter.h>
// for stereo setting
#include <mitkOpenGLRenderer.h>
#include <mitkVtkRenderWindow.h>
#include <vtkRenderWindow.h>
#include <mitkVesselGraphInteractor.h>
// for zoom/pan
#include <mitkDisplayCoordinateOperation.h>
#include <mitkDisplayVectorInteractor.h>
#include <mitkInteractionConst.h>
QmitkSimpleExampleFunctionality::QmitkSimpleExampleFunctionality(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIterator * it) : QmitkFunctionality(parent, name, it) ,
controls(NULL), multiWidget(mitkStdMultiWidget)
{
setAvailability(true);
mitk::GlobalInteraction* globalInteraction = dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine());
if(globalInteraction!=NULL)
{
globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor("move", this));//sends DisplayCoordinateOperation
globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor("zoom", this));//sends DisplayCoordinateOperation
globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor("picking", new mitk::VesselGraphInteractor( it ) ) ); //allows picking of vessels
}
m_DataTreeIterator->getTree()->addTreeChangeListener(this);
}
QmitkSimpleExampleFunctionality::~QmitkSimpleExampleFunctionality()
{
}
QString QmitkSimpleExampleFunctionality::getFunctionalityName()
{
return "simple example";
}
QWidget * QmitkSimpleExampleFunctionality::createMainWidget(QWidget *parent)
{
if (multiWidget == NULL)
{
return multiWidget = new QmitkStdMultiWidget(parent);
}
else
return NULL;
}
QWidget * QmitkSimpleExampleFunctionality::createControlWidget(QWidget *parent)
{
if (controls == NULL)
{
controls = new QmitkSimpleExampleControls(parent);
multiplexUpdateController = new mitk::MultiplexUpdateController("navigation");
multiplexUpdateController->AddRenderWindow(multiWidget->mitkWidget1->GetRenderer()->GetRenderWindow());
multiplexUpdateController->AddRenderWindow(multiWidget->mitkWidget2->GetRenderer()->GetRenderWindow());
multiplexUpdateController->AddRenderWindow(multiWidget->mitkWidget3->GetRenderer()->GetRenderWindow());
multiplexUpdateController->AddRenderWindow(multiWidget->mitkWidget4->GetRenderer()->GetRenderWindow());
sliceNavigatorTransversal = new mitk::SliceNavigationController("navigation");
sliceNavigatorTransversal->SetViewDirection(mitk::SliceNavigationController::Transversal);
sliceNavigatorTransversal->ConnectGeometrySliceEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer());
sliceNavigatorTransversal->ConnectRepaintRequest(multiplexUpdateController.GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorTransversal(), sliceNavigatorTransversal->GetSlice(), "sliceNavigatorTransversalFromSimpleExample");
sliceNavigatorSagittal = new mitk::SliceNavigationController("navigation");
sliceNavigatorSagittal->SetViewDirection(mitk::SliceNavigationController::Sagittal);
sliceNavigatorSagittal->ConnectGeometrySliceEvent(multiWidget->mitkWidget2->GetRenderer().GetPointer());
sliceNavigatorSagittal->ConnectRepaintRequest(multiplexUpdateController.GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorSagittal(), sliceNavigatorSagittal->GetSlice(), "sliceNavigatorSagittalFromSimpleExample");
sliceNavigatorFrontal = new mitk::SliceNavigationController("navigation");
sliceNavigatorFrontal->SetViewDirection(mitk::SliceNavigationController::Frontal);
sliceNavigatorFrontal->ConnectGeometrySliceEvent(multiWidget->mitkWidget3->GetRenderer().GetPointer());
sliceNavigatorFrontal->ConnectRepaintRequest(multiplexUpdateController.GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorFrontal(), sliceNavigatorFrontal->GetSlice(), "sliceNavigatorFrontalFromSimpleExample");
sliceNavigatorTime = new mitk::SliceNavigationController(NULL);
sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer(), false);
sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget2->GetRenderer().GetPointer(), false);
sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget3->GetRenderer().GetPointer(), false);
sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget4->GetRenderer().GetPointer(), false);
sliceNavigatorTime->ConnectRepaintRequest(multiplexUpdateController.GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorTime(), sliceNavigatorTime->GetTime(), "sliceNavigatorTimeFromSimpleExample");
mitk::GlobalInteraction* globalInteraction = dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine());
if(globalInteraction!=NULL)
{
globalInteraction->AddStateMachine(multiplexUpdateController);
}
}
return controls;
}
void QmitkSimpleExampleFunctionality::createConnections()
{
connect(controls->getStereoSelect(), SIGNAL(activated(int)), this, SLOT(stereoSelectionChanged(int)) );
}
QAction * QmitkSimpleExampleFunctionality::createAction(QActionGroup *parent)
{
QAction* action;
action = new QAction( tr( "Left" ), QPixmap((const char**)slicer_xpm), tr( "&Left" ), CTRL + Key_L, parent, "simple example" );
// action = new QAction( tr( "Left" ), QPixmap(textleft_xpm), tr( "&Left" ), CTRL + Key_L, parent, "simple example" );
return action;
}
void QmitkSimpleExampleFunctionality::initNavigators()
{
const mitk::BoundingBox::Pointer boundingbox = mitk::DataTree::ComputeVisibleBoundingBox(m_DataTreeIterator, NULL, "includeInBoundingBox");
if(boundingbox->GetPoints()->Size()>0)
{
// const mitk::BoundingBox::Pointer bb=boundingbox;
//const mitk::BoundingBox::BoundsArrayType bounds = bb->GetBounds();
// float boundingbox[6]={-2*bounds[1],2*bounds[1],-2*bounds[3],2*bounds[3],-2*bounds[5],2*bounds[5]};
mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New();
geometry->Initialize();
geometry->SetBoundingBox(boundingbox);
//lets see if we have data with a limited live-span ...
mitk::TimeBounds timebounds = mitk::DataTree::ComputeTimeBoundsInMS(m_DataTreeIterator, NULL, "includeInBoundingBox");
if(timebounds[1]<mitk::ScalarTypeNumericTraits::max())
{
mitk::TimeSlicedGeometry::Pointer timegeometry = mitk::TimeSlicedGeometry::New();
timegeometry->Initialize(10);
timegeometry->SetTimeBoundsInMS(timebounds); //@bug really required?
timegeometry->SetEvenlyTimed();
mitk::ScalarType duration = timebounds[1]-timebounds[0];
timebounds[1] = timebounds[0]+duration/10.0;
timegeometry->SetGeometry3D(geometry, 0);
geometry->SetTimeBoundsInMS(timebounds);
geometry=timegeometry;
}
multiplexUpdateController->SetBlockUpdate(true);
sliceNavigatorTransversal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorTransversal->Update();
sliceNavigatorSagittal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorSagittal->Update();
sliceNavigatorFrontal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorFrontal->Update();
sliceNavigatorTime->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorTime->Update();
multiplexUpdateController->SetBlockUpdate(false);
multiplexUpdateController->UpdateRequest();
}
}
void QmitkSimpleExampleFunctionality::treeChanged(mitk::DataTreeIterator& itpos)
{
initNavigators();
}
void QmitkSimpleExampleFunctionality::activated()
{
QmitkFunctionality::activated();
assert( multiWidget != NULL );
// init widget 4 as a 3D widget
multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
multiplexUpdateController->SetBlockUpdate(true);
sliceNavigatorTransversal->Update();
sliceNavigatorSagittal->Update();
sliceNavigatorFrontal->Update();
sliceNavigatorTime->Update();
multiplexUpdateController->SetBlockUpdate(false);
multiplexUpdateController->UpdateRequest();
}
//void QmitkSimpleExampleFunctionality::deactivated()
//{
//
//}
void QmitkSimpleExampleFunctionality::stereoSelectionChanged( int id )
{
vtkRenderWindow * vtkrenderwindow =
((mitk::OpenGLRenderer*)(multiWidget->mitkWidget4->GetRenderer().GetPointer()))->GetVtkRenderWindow();
switch(id)
{
case 0:
vtkrenderwindow->StereoRenderOff();
break;
case 1:
vtkrenderwindow->SetStereoTypeToDresden();
vtkrenderwindow->StereoRenderOn();
break;
}
multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
multiWidget->mitkWidget4->GetRenderer()->GetRenderWindow()->Repaint();
}
void QmitkSimpleExampleFunctionality::ExecuteOperation(mitk::Operation* operation)
{
bool ok;//as return
mitk::DisplayCoordinateOperation* dcOperation=dynamic_cast<mitk::DisplayCoordinateOperation*>(operation);
if( dcOperation != NULL )
{
/****ZOOM & MOVE of the whole volume****/
mitk::BaseRenderer* renderer = dcOperation->GetRenderer();
if( renderer == NULL )
return;
switch (operation->GetOperationType())
{
case mitk::OpMOVE :
{
renderer->GetDisplayGeometry()->MoveBy(dcOperation->GetLastToCurrentDisplayVector()*(-1.0));
renderer->GetRenderWindow()->Repaint();
ok = true;
}
break;
case mitk::OpZOOM :
{
float distance = dcOperation->GetLastToCurrentDisplayVector().y;
distance = (distance > 0 ? 1 : (distance < 0 ? -1 : 0));
float factor= 1.0 + distance * 0.05;
renderer->GetDisplayGeometry()->Zoom(factor, dcOperation->GetStartDisplayCoordinate());
renderer->GetRenderWindow()->Repaint();
ok = true;
}
break;
default:
;
}
}
}
<commit_msg>removed vesselgraphinteractor<commit_after>#include "QmitkSimpleExampleFunctionality.h"
#include "QmitkSimpleExampleControls.h"
#include <qaction.h>
#include "slicer.xpm"
// for slice-navigation
#include <mitkEventMapper.h>
#include <mitkGlobalInteraction.h>
#include <mitkBaseRenderer.h>
#include "QmitkRenderWindow.h"
#include "QmitkSelectableGLWidget.h"
#include "QmitkStdMultiWidget.h"
#include <QmitkStepperAdapter.h>
// for stereo setting
#include <mitkOpenGLRenderer.h>
#include <mitkVtkRenderWindow.h>
#include <vtkRenderWindow.h>
#include <mitkVesselGraphInteractor.h>
// for zoom/pan
#include <mitkDisplayCoordinateOperation.h>
#include <mitkDisplayVectorInteractor.h>
#include <mitkInteractionConst.h>
QmitkSimpleExampleFunctionality::QmitkSimpleExampleFunctionality(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIterator * it) : QmitkFunctionality(parent, name, it) ,
controls(NULL), multiWidget(mitkStdMultiWidget)
{
setAvailability(true);
mitk::GlobalInteraction* globalInteraction = dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine());
if(globalInteraction!=NULL)
{
globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor("move", this));//sends DisplayCoordinateOperation
globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor("zoom", this));//sends DisplayCoordinateOperation
}
m_DataTreeIterator->getTree()->addTreeChangeListener(this);
}
QmitkSimpleExampleFunctionality::~QmitkSimpleExampleFunctionality()
{
}
QString QmitkSimpleExampleFunctionality::getFunctionalityName()
{
return "simple example";
}
QWidget * QmitkSimpleExampleFunctionality::createMainWidget(QWidget *parent)
{
if (multiWidget == NULL)
{
return multiWidget = new QmitkStdMultiWidget(parent);
}
else
return NULL;
}
QWidget * QmitkSimpleExampleFunctionality::createControlWidget(QWidget *parent)
{
if (controls == NULL)
{
controls = new QmitkSimpleExampleControls(parent);
multiplexUpdateController = new mitk::MultiplexUpdateController("navigation");
multiplexUpdateController->AddRenderWindow(multiWidget->mitkWidget1->GetRenderer()->GetRenderWindow());
multiplexUpdateController->AddRenderWindow(multiWidget->mitkWidget2->GetRenderer()->GetRenderWindow());
multiplexUpdateController->AddRenderWindow(multiWidget->mitkWidget3->GetRenderer()->GetRenderWindow());
multiplexUpdateController->AddRenderWindow(multiWidget->mitkWidget4->GetRenderer()->GetRenderWindow());
sliceNavigatorTransversal = new mitk::SliceNavigationController("navigation");
sliceNavigatorTransversal->SetViewDirection(mitk::SliceNavigationController::Transversal);
sliceNavigatorTransversal->ConnectGeometrySliceEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer());
sliceNavigatorTransversal->ConnectRepaintRequest(multiplexUpdateController.GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorTransversal(), sliceNavigatorTransversal->GetSlice(), "sliceNavigatorTransversalFromSimpleExample");
sliceNavigatorSagittal = new mitk::SliceNavigationController("navigation");
sliceNavigatorSagittal->SetViewDirection(mitk::SliceNavigationController::Sagittal);
sliceNavigatorSagittal->ConnectGeometrySliceEvent(multiWidget->mitkWidget2->GetRenderer().GetPointer());
sliceNavigatorSagittal->ConnectRepaintRequest(multiplexUpdateController.GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorSagittal(), sliceNavigatorSagittal->GetSlice(), "sliceNavigatorSagittalFromSimpleExample");
sliceNavigatorFrontal = new mitk::SliceNavigationController("navigation");
sliceNavigatorFrontal->SetViewDirection(mitk::SliceNavigationController::Frontal);
sliceNavigatorFrontal->ConnectGeometrySliceEvent(multiWidget->mitkWidget3->GetRenderer().GetPointer());
sliceNavigatorFrontal->ConnectRepaintRequest(multiplexUpdateController.GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorFrontal(), sliceNavigatorFrontal->GetSlice(), "sliceNavigatorFrontalFromSimpleExample");
sliceNavigatorTime = new mitk::SliceNavigationController(NULL);
sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer(), false);
sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget2->GetRenderer().GetPointer(), false);
sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget3->GetRenderer().GetPointer(), false);
sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget4->GetRenderer().GetPointer(), false);
sliceNavigatorTime->ConnectRepaintRequest(multiplexUpdateController.GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorTime(), sliceNavigatorTime->GetTime(), "sliceNavigatorTimeFromSimpleExample");
mitk::GlobalInteraction* globalInteraction = dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine());
if(globalInteraction!=NULL)
{
globalInteraction->AddStateMachine(multiplexUpdateController);
}
}
return controls;
}
void QmitkSimpleExampleFunctionality::createConnections()
{
connect(controls->getStereoSelect(), SIGNAL(activated(int)), this, SLOT(stereoSelectionChanged(int)) );
}
QAction * QmitkSimpleExampleFunctionality::createAction(QActionGroup *parent)
{
QAction* action;
action = new QAction( tr( "Left" ), QPixmap((const char**)slicer_xpm), tr( "&Left" ), CTRL + Key_L, parent, "simple example" );
// action = new QAction( tr( "Left" ), QPixmap(textleft_xpm), tr( "&Left" ), CTRL + Key_L, parent, "simple example" );
return action;
}
void QmitkSimpleExampleFunctionality::initNavigators()
{
const mitk::BoundingBox::Pointer boundingbox = mitk::DataTree::ComputeVisibleBoundingBox(m_DataTreeIterator, NULL, "includeInBoundingBox");
if(boundingbox->GetPoints()->Size()>0)
{
// const mitk::BoundingBox::Pointer bb=boundingbox;
//const mitk::BoundingBox::BoundsArrayType bounds = bb->GetBounds();
// float boundingbox[6]={-2*bounds[1],2*bounds[1],-2*bounds[3],2*bounds[3],-2*bounds[5],2*bounds[5]};
mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New();
geometry->Initialize();
geometry->SetBoundingBox(boundingbox);
//lets see if we have data with a limited live-span ...
mitk::TimeBounds timebounds = mitk::DataTree::ComputeTimeBoundsInMS(m_DataTreeIterator, NULL, "includeInBoundingBox");
if(timebounds[1]<mitk::ScalarTypeNumericTraits::max())
{
mitk::TimeSlicedGeometry::Pointer timegeometry = mitk::TimeSlicedGeometry::New();
timegeometry->Initialize(10);
timegeometry->SetTimeBoundsInMS(timebounds); //@bug really required?
timegeometry->SetEvenlyTimed();
mitk::ScalarType duration = timebounds[1]-timebounds[0];
timebounds[1] = timebounds[0]+duration/10.0;
timegeometry->SetGeometry3D(geometry, 0);
geometry->SetTimeBoundsInMS(timebounds);
geometry=timegeometry;
}
multiplexUpdateController->SetBlockUpdate(true);
sliceNavigatorTransversal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorTransversal->Update();
sliceNavigatorSagittal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorSagittal->Update();
sliceNavigatorFrontal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorFrontal->Update();
sliceNavigatorTime->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorTime->Update();
multiplexUpdateController->SetBlockUpdate(false);
multiplexUpdateController->UpdateRequest();
}
}
void QmitkSimpleExampleFunctionality::treeChanged(mitk::DataTreeIterator& itpos)
{
initNavigators();
}
void QmitkSimpleExampleFunctionality::activated()
{
QmitkFunctionality::activated();
assert( multiWidget != NULL );
// init widget 4 as a 3D widget
multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
multiplexUpdateController->SetBlockUpdate(true);
sliceNavigatorTransversal->Update();
sliceNavigatorSagittal->Update();
sliceNavigatorFrontal->Update();
sliceNavigatorTime->Update();
multiplexUpdateController->SetBlockUpdate(false);
multiplexUpdateController->UpdateRequest();
}
//void QmitkSimpleExampleFunctionality::deactivated()
//{
//
//}
void QmitkSimpleExampleFunctionality::stereoSelectionChanged( int id )
{
vtkRenderWindow * vtkrenderwindow =
((mitk::OpenGLRenderer*)(multiWidget->mitkWidget4->GetRenderer().GetPointer()))->GetVtkRenderWindow();
switch(id)
{
case 0:
vtkrenderwindow->StereoRenderOff();
break;
case 1:
vtkrenderwindow->SetStereoTypeToDresden();
vtkrenderwindow->StereoRenderOn();
break;
}
multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
multiWidget->mitkWidget4->GetRenderer()->GetRenderWindow()->Repaint();
}
void QmitkSimpleExampleFunctionality::ExecuteOperation(mitk::Operation* operation)
{
bool ok;//as return
mitk::DisplayCoordinateOperation* dcOperation=dynamic_cast<mitk::DisplayCoordinateOperation*>(operation);
if( dcOperation != NULL )
{
/****ZOOM & MOVE of the whole volume****/
mitk::BaseRenderer* renderer = dcOperation->GetRenderer();
if( renderer == NULL )
return;
switch (operation->GetOperationType())
{
case mitk::OpMOVE :
{
renderer->GetDisplayGeometry()->MoveBy(dcOperation->GetLastToCurrentDisplayVector()*(-1.0));
renderer->GetRenderWindow()->Repaint();
ok = true;
}
break;
case mitk::OpZOOM :
{
float distance = dcOperation->GetLastToCurrentDisplayVector().y;
distance = (distance > 0 ? 1 : (distance < 0 ? -1 : 0));
float factor= 1.0 + distance * 0.05;
renderer->GetDisplayGeometry()->Zoom(factor, dcOperation->GetStartDisplayCoordinate());
renderer->GetRenderWindow()->Repaint();
ok = true;
}
break;
default:
;
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "RuntimeSchedulerBinding.h"
#include "SchedulerPriority.h"
#include "primitives.h"
#include <react/debug/react_native_assert.h>
#include <chrono>
#include <memory>
#include <utility>
namespace facebook {
namespace react {
std::shared_ptr<RuntimeSchedulerBinding>
RuntimeSchedulerBinding::createAndInstallIfNeeded(
jsi::Runtime &runtime,
std::shared_ptr<RuntimeScheduler> const &runtimeScheduler) {
auto runtimeSchedulerModuleName = "nativeRuntimeScheduler";
auto runtimeSchedulerValue =
runtime.global().getProperty(runtime, runtimeSchedulerModuleName);
if (runtimeSchedulerValue.isUndefined()) {
// The global namespace does not have an instance of the binding;
// we need to create, install and return it.
auto runtimeSchedulerBinding =
std::make_shared<RuntimeSchedulerBinding>(runtimeScheduler);
auto object =
jsi::Object::createFromHostObject(runtime, runtimeSchedulerBinding);
runtime.global().setProperty(
runtime, runtimeSchedulerModuleName, std::move(object));
return runtimeSchedulerBinding;
}
// The global namespace already has an instance of the binding;
// we need to return that.
auto runtimeSchedulerObject = runtimeSchedulerValue.asObject(runtime);
return runtimeSchedulerObject.getHostObject<RuntimeSchedulerBinding>(runtime);
}
std::shared_ptr<RuntimeSchedulerBinding> RuntimeSchedulerBinding::getBinding(
jsi::Runtime &runtime) {
auto runtimeSchedulerModuleName = "nativeRuntimeScheduler";
auto runtimeSchedulerValue =
runtime.global().getProperty(runtime, runtimeSchedulerModuleName);
if (runtimeSchedulerValue.isUndefined()) {
return nullptr;
}
auto runtimeSchedulerObject = runtimeSchedulerValue.asObject(runtime);
return runtimeSchedulerObject.getHostObject<RuntimeSchedulerBinding>(runtime);
}
RuntimeSchedulerBinding::RuntimeSchedulerBinding(
std::shared_ptr<RuntimeScheduler> runtimeScheduler)
: runtimeScheduler_(std::move(runtimeScheduler)) {}
bool RuntimeSchedulerBinding::getIsSynchronous() const {
return runtimeScheduler_->getIsSynchronous();
}
jsi::Value RuntimeSchedulerBinding::get(
jsi::Runtime &runtime,
jsi::PropNameID const &name) {
auto propertyName = name.utf8(runtime);
if (propertyName == "unstable_scheduleCallback") {
return jsi::Function::createFromHostFunction(
runtime,
name,
3,
[this](
jsi::Runtime &runtime,
jsi::Value const &,
jsi::Value const *arguments,
size_t) noexcept -> jsi::Value {
SchedulerPriority priority = fromRawValue(arguments[0].getNumber());
auto callback = arguments[1].getObject(runtime).getFunction(runtime);
auto task =
runtimeScheduler_->scheduleTask(priority, std::move(callback));
return valueFromTask(runtime, task);
});
}
if (propertyName == "unstable_cancelCallback") {
return jsi::Function::createFromHostFunction(
runtime,
name,
1,
[this](
jsi::Runtime &runtime,
jsi::Value const &,
jsi::Value const *arguments,
size_t) noexcept -> jsi::Value {
runtimeScheduler_->cancelTask(*taskFromValue(runtime, arguments[0]));
return jsi::Value::undefined();
});
}
if (propertyName == "unstable_shouldYield") {
return jsi::Function::createFromHostFunction(
runtime,
name,
0,
[this](
jsi::Runtime &,
jsi::Value const &,
jsi::Value const *,
size_t) noexcept -> jsi::Value {
auto shouldYield = runtimeScheduler_->getShouldYield();
return jsi::Value(shouldYield);
});
}
if (propertyName == "unstable_requestPaint") {
return jsi::Function::createFromHostFunction(
runtime,
name,
0,
[](jsi::Runtime &,
jsi::Value const &,
jsi::Value const *,
size_t) noexcept -> jsi::Value {
// RequestPaint is left empty by design.
return jsi::Value::undefined();
});
}
if (propertyName == "unstable_now") {
return jsi::Function::createFromHostFunction(
runtime,
name,
0,
[this](
jsi::Runtime &,
jsi::Value const &,
jsi::Value const *,
size_t) noexcept -> jsi::Value {
auto now = runtimeScheduler_->now();
auto asDouble =
std::chrono::duration<double, std::milli>(now.time_since_epoch())
.count();
return jsi::Value(asDouble);
});
}
if (propertyName == "unstable_getCurrentPriorityLevel") {
auto currentPriorityLevel = runtimeScheduler_->getCurrentPriorityLevel();
return jsi::Value(runtime, serialize(currentPriorityLevel));
}
if (propertyName == "unstable_ImmediatePriority") {
return jsi::Value(runtime, serialize(SchedulerPriority::ImmediatePriority));
}
if (propertyName == "unstable_UserBlockingPriority") {
return jsi::Value(
runtime, serialize(SchedulerPriority::UserBlockingPriority));
}
if (propertyName == "unstable_NormalPriority") {
return jsi::Value(runtime, serialize(SchedulerPriority::NormalPriority));
}
if (propertyName == "unstable_LowPriority") {
return jsi::Value(runtime, serialize(SchedulerPriority::LowPriority));
}
if (propertyName == "unstable_IdlePriority") {
return jsi::Value(runtime, serialize(SchedulerPriority::IdlePriority));
}
if (propertyName == "$$typeof") {
return jsi::Value::undefined();
}
react_native_assert(false && "undefined property");
return jsi::Value::undefined();
}
} // namespace react
} // namespace facebook
<commit_msg>Throw error when accessing undefined property on runtimeScheduler<commit_after>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "RuntimeSchedulerBinding.h"
#include "SchedulerPriority.h"
#include "primitives.h"
#include <react/debug/react_native_assert.h>
#include <chrono>
#include <memory>
#include <utility>
namespace facebook {
namespace react {
std::shared_ptr<RuntimeSchedulerBinding>
RuntimeSchedulerBinding::createAndInstallIfNeeded(
jsi::Runtime &runtime,
std::shared_ptr<RuntimeScheduler> const &runtimeScheduler) {
auto runtimeSchedulerModuleName = "nativeRuntimeScheduler";
auto runtimeSchedulerValue =
runtime.global().getProperty(runtime, runtimeSchedulerModuleName);
if (runtimeSchedulerValue.isUndefined()) {
// The global namespace does not have an instance of the binding;
// we need to create, install and return it.
auto runtimeSchedulerBinding =
std::make_shared<RuntimeSchedulerBinding>(runtimeScheduler);
auto object =
jsi::Object::createFromHostObject(runtime, runtimeSchedulerBinding);
runtime.global().setProperty(
runtime, runtimeSchedulerModuleName, std::move(object));
return runtimeSchedulerBinding;
}
// The global namespace already has an instance of the binding;
// we need to return that.
auto runtimeSchedulerObject = runtimeSchedulerValue.asObject(runtime);
return runtimeSchedulerObject.getHostObject<RuntimeSchedulerBinding>(runtime);
}
std::shared_ptr<RuntimeSchedulerBinding> RuntimeSchedulerBinding::getBinding(
jsi::Runtime &runtime) {
auto runtimeSchedulerModuleName = "nativeRuntimeScheduler";
auto runtimeSchedulerValue =
runtime.global().getProperty(runtime, runtimeSchedulerModuleName);
if (runtimeSchedulerValue.isUndefined()) {
return nullptr;
}
auto runtimeSchedulerObject = runtimeSchedulerValue.asObject(runtime);
return runtimeSchedulerObject.getHostObject<RuntimeSchedulerBinding>(runtime);
}
RuntimeSchedulerBinding::RuntimeSchedulerBinding(
std::shared_ptr<RuntimeScheduler> runtimeScheduler)
: runtimeScheduler_(std::move(runtimeScheduler)) {}
bool RuntimeSchedulerBinding::getIsSynchronous() const {
return runtimeScheduler_->getIsSynchronous();
}
jsi::Value RuntimeSchedulerBinding::get(
jsi::Runtime &runtime,
jsi::PropNameID const &name) {
auto propertyName = name.utf8(runtime);
if (propertyName == "unstable_scheduleCallback") {
return jsi::Function::createFromHostFunction(
runtime,
name,
3,
[this](
jsi::Runtime &runtime,
jsi::Value const &,
jsi::Value const *arguments,
size_t) noexcept -> jsi::Value {
SchedulerPriority priority = fromRawValue(arguments[0].getNumber());
auto callback = arguments[1].getObject(runtime).getFunction(runtime);
auto task =
runtimeScheduler_->scheduleTask(priority, std::move(callback));
return valueFromTask(runtime, task);
});
}
if (propertyName == "unstable_cancelCallback") {
return jsi::Function::createFromHostFunction(
runtime,
name,
1,
[this](
jsi::Runtime &runtime,
jsi::Value const &,
jsi::Value const *arguments,
size_t) noexcept -> jsi::Value {
runtimeScheduler_->cancelTask(*taskFromValue(runtime, arguments[0]));
return jsi::Value::undefined();
});
}
if (propertyName == "unstable_shouldYield") {
return jsi::Function::createFromHostFunction(
runtime,
name,
0,
[this](
jsi::Runtime &,
jsi::Value const &,
jsi::Value const *,
size_t) noexcept -> jsi::Value {
auto shouldYield = runtimeScheduler_->getShouldYield();
return jsi::Value(shouldYield);
});
}
if (propertyName == "unstable_requestPaint") {
return jsi::Function::createFromHostFunction(
runtime,
name,
0,
[](jsi::Runtime &,
jsi::Value const &,
jsi::Value const *,
size_t) noexcept -> jsi::Value {
// RequestPaint is left empty by design.
return jsi::Value::undefined();
});
}
if (propertyName == "unstable_now") {
return jsi::Function::createFromHostFunction(
runtime,
name,
0,
[this](
jsi::Runtime &,
jsi::Value const &,
jsi::Value const *,
size_t) noexcept -> jsi::Value {
auto now = runtimeScheduler_->now();
auto asDouble =
std::chrono::duration<double, std::milli>(now.time_since_epoch())
.count();
return jsi::Value(asDouble);
});
}
if (propertyName == "unstable_getCurrentPriorityLevel") {
auto currentPriorityLevel = runtimeScheduler_->getCurrentPriorityLevel();
return jsi::Value(runtime, serialize(currentPriorityLevel));
}
if (propertyName == "unstable_ImmediatePriority") {
return jsi::Value(runtime, serialize(SchedulerPriority::ImmediatePriority));
}
if (propertyName == "unstable_UserBlockingPriority") {
return jsi::Value(
runtime, serialize(SchedulerPriority::UserBlockingPriority));
}
if (propertyName == "unstable_NormalPriority") {
return jsi::Value(runtime, serialize(SchedulerPriority::NormalPriority));
}
if (propertyName == "unstable_LowPriority") {
return jsi::Value(runtime, serialize(SchedulerPriority::LowPriority));
}
if (propertyName == "unstable_IdlePriority") {
return jsi::Value(runtime, serialize(SchedulerPriority::IdlePriority));
}
if (propertyName == "$$typeof") {
return jsi::Value::undefined();
}
#ifdef REACT_NATIVE_DEBUG
throw std::runtime_error("undefined property");
#else
return jsi::Value::undefined();
#endif
}
} // namespace react
} // namespace facebook
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>
#include <string>
#include <math.h>
#include "dmath/geometry.h"
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
base_link_("base_link"),
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("/camera/depth/points", 10, &ArtificialPotentialField::obstacleCallback, this))
{
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double force = 0.025;
while(ros::ok()){
dmath::Vector3D Fs;
Fs += get_potential_force(obs_, 0, 3, 1, 2.0);
dmath::Vector3D g;
Fs += get_potential_force(g, 2, 0, 1.5, 1);
dmath::Vector3D vel = Fs * force;
//cmd.linear.x = Fs[1] * force;
//cmd.linear.y = Fs[1] * force;
ROS_INFO("obs = (%f, %f)", obs_.x, obs_.y);
ROS_INFO_STREAM("cmd = " << cmd);
cmd_pub_.publish(cmd);
r.sleep();
ros::spinOnce();
}
}
private:
dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
Vector3D u = dest_lc;
u = normalize(u);
const double d = magnitude(dest_lc);
double U = 0;
if(fabs(d) > dmath::tol){
U = -A/pow(d, n) + B/pow(d, m);
}
return U * u;
}
void obstacleCallback(const sensor_msgs::PointCloud2Ptr &obs_msg){
sensor_msgs::PointCloud obs_lsr, obs_base;
sensor_msgs::convertPointCloud2ToPointCloud(*obs_msg, obs_lsr);
tf_listener_.transformPointCloud(obs_lsr.header.frame_id, obs_lsr.header.stamp, obs_lsr, base_link_, obs_base);
if(obs_base.points.size() == 0){
obs_.x = 0;
obs_.y = 0;
obs_.z = 0;
return;
}
dmath::Vector3D min_obs;
min_obs.x = obs_base.points[0].x;
min_obs.y = obs_base.points[0].y;
min_obs.z = obs_base.points[0].z;
float min_dist = magnitude(min_obs);
for(int i=1; i < obs_base.points.size(); i++){
dmath::Vector3D obs;
obs.x = obs_base.points[i].x;
obs.y = obs_base.points[i].y;
obs.z = obs_base.points[i].z;
//ROS_INFO("(%f, %f)", obs[0], obs[1]);
double dist = magnitude(obs);
if(dist < min_dist){
min_obs.x = obs.x;
min_obs.y = obs.y;
min_obs.z = obs.z;
min_dist = dist;
}
}
obs_.x = min_obs.x;
obs_.y = min_obs.y;
obs_.z = min_obs.z;
}
dmath::Vector3D obs_;
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_;
tf::TransformListener tf_listener_;
std::string base_link_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "apf_planner");
ros::NodeHandle node;
ArtificialPotentialField apf(node);
apf.spin();
return 0;
}
<commit_msg>Fix refecenre error of Vector3D<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>
#include <string>
#include <math.h>
#include "dmath/geometry.h"
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
base_link_("base_link"),
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("/camera/depth/points", 10, &ArtificialPotentialField::obstacleCallback, this))
{
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double force = 0.025;
while(ros::ok()){
dmath::Vector3D Fs;
Fs += get_potential_force(obs_, 0, 3, 1, 2.0);
dmath::Vector3D g;
Fs += get_potential_force(g, 2, 0, 1.5, 1);
dmath::Vector3D vel = Fs * force;
//cmd.linear.x = Fs[1] * force;
//cmd.linear.y = Fs[1] * force;
ROS_INFO("obs = (%f, %f)", obs_.x, obs_.y);
ROS_INFO_STREAM("cmd = " << cmd);
cmd_pub_.publish(cmd);
r.sleep();
ros::spinOnce();
}
}
private:
dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
dmath::Vector3D u = dest_lc;
u = normalize(u);
const double d = magnitude(dest_lc);
double U = 0;
if(fabs(d) > dmath::tol){
U = -A/pow(d, n) + B/pow(d, m);
}
return U * u;
}
void obstacleCallback(const sensor_msgs::PointCloud2Ptr &obs_msg){
sensor_msgs::PointCloud obs_lsr, obs_base;
sensor_msgs::convertPointCloud2ToPointCloud(*obs_msg, obs_lsr);
tf_listener_.transformPointCloud(obs_lsr.header.frame_id, obs_lsr.header.stamp, obs_lsr, base_link_, obs_base);
if(obs_base.points.size() == 0){
obs_.x = 0;
obs_.y = 0;
obs_.z = 0;
return;
}
dmath::Vector3D min_obs;
min_obs.x = obs_base.points[0].x;
min_obs.y = obs_base.points[0].y;
min_obs.z = obs_base.points[0].z;
float min_dist = magnitude(min_obs);
for(int i=1; i < obs_base.points.size(); i++){
dmath::Vector3D obs;
obs.x = obs_base.points[i].x;
obs.y = obs_base.points[i].y;
obs.z = obs_base.points[i].z;
//ROS_INFO("(%f, %f)", obs[0], obs[1]);
double dist = magnitude(obs);
if(dist < min_dist){
min_obs.x = obs.x;
min_obs.y = obs.y;
min_obs.z = obs.z;
min_dist = dist;
}
}
obs_.x = min_obs.x;
obs_.y = min_obs.y;
obs_.z = min_obs.z;
}
dmath::Vector3D obs_;
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_;
tf::TransformListener tf_listener_;
std::string base_link_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "apf_planner");
ros::NodeHandle node;
ArtificialPotentialField apf(node);
apf.spin();
return 0;
}
<|endoftext|>
|
<commit_before>#include <string>
#include <gtest/gtest.h>
extern "C" {
#include "shoveler/resources.h"
}
static void requestResources(ShovelerResources *resources, const char *typeId, const char *resourceId, void *testPointer);
void *loadResource(ShovelerResourcesTypeLoader *typeLoader, const unsigned char *buffer, size_t bytes);
void freeResourceData(ShovelerResourcesTypeLoader *typeLoader, void *resourceData);
void freeTypeLoader(ShovelerResourcesTypeLoader *typeLoader);
class ShovelerResourcesTest : public ::testing::Test {
public:
virtual void SetUp()
{
resources = shovelerResourcesCreate(requestResources, this);
testTypeId = "test type id";
testDefaultResourceData = "test default resource";
testTypeLoader.typeId = testTypeId;
testTypeLoader.defaultResourceData = (void *) testDefaultResourceData;
testTypeLoader.data = this;
testTypeLoader.load = loadResource;
testTypeLoader.freeResourceData = freeResourceData;
testTypeLoader.free = freeTypeLoader;
bool typeLoaderRegistered = shovelerResourcesRegisterTypeLoader(resources, testTypeLoader);
ASSERT_TRUE(typeLoaderRegistered) << "test type loader should register correctly";
lastRequestResources = NULL;
lastRequestTypeId = NULL;
lastRequestResourceId = NULL;
lastLoadBuffer = NULL;
lastLoadBytes = 0;
nextLoadResourceData = NULL;
freeResourceDataArguments.clear();
freeTypeLoaderCalled = false;
}
virtual void TearDown()
{
shovelerResourcesFree(resources);
ASSERT_EQ(*freeResourceDataArguments.rbegin(), testTypeLoader.defaultResourceData) << "type loader's default resource data should be freed after resources was freed";
ASSERT_TRUE(freeTypeLoaderCalled) << "type loader should be freed after resources was freed";
}
ShovelerResources *resources;
const char *testTypeId;
const char *testDefaultResourceData;
ShovelerResourcesTypeLoader testTypeLoader;
ShovelerResources *lastRequestResources;
const char *lastRequestTypeId;
const char *lastRequestResourceId;
const unsigned char *lastLoadBuffer;
size_t lastLoadBytes;
void *nextLoadResourceData;
std::vector<void *> freeResourceDataArguments;
bool freeTypeLoaderCalled;
};
TEST_F(ShovelerResourcesTest, requestUnloaded)
{
const char *testResourceId = "test resource id";
ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
ASSERT_EQ(lastRequestResources, resources) << "request should be called with correct resources";
ASSERT_EQ(lastRequestTypeId, testTypeId) << "request should be called with correct type id";
ASSERT_EQ(lastRequestResourceId, testResourceId) << "request should be called with correct resource id";
ASSERT_EQ(resource->resources, resources) << "returned resource should have correct resources";
ASSERT_STREQ(resource->id, testResourceId) << "returned resource should have correct resource id";
ASSERT_STREQ(resource->typeId, testTypeId) << "returned resource should have correct type id";
ASSERT_EQ(resource->data, testDefaultResourceData) << "returned resource should have correct default data";
}
TEST_F(ShovelerResourcesTest, requestInvalidType)
{
const char *testInvalidTypeId = "foo/bar";
const char *testResourceId = "test resource id";
ShovelerResource *resource = shovelerResourcesGet(resources, testInvalidTypeId, testResourceId);
ASSERT_TRUE(resource == NULL) << "request should have failed";
}
TEST_F(ShovelerResourcesTest, requestNull)
{
const char *testResourceId = "test resource id";
ShovelerResources *resources = shovelerResourcesCreate(NULL, NULL);
bool typeLoaderRegistered = shovelerResourcesRegisterTypeLoader(resources, testTypeLoader);
ASSERT_TRUE(typeLoaderRegistered) << "test type loader should register correctly";
ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
ASSERT_TRUE(resource != NULL) << "returned resource must not be NULL";
shovelerResourcesFree(resources);
}
TEST_F(ShovelerResourcesTest, loadUnrequested)
{
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
const char *testResourceData = "test resource data";
nextLoadResourceData = (void *) testResourceData;
bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
ASSERT_TRUE(loaded) << "load should have succeeded";
ASSERT_EQ(lastLoadBuffer, &testResourceBuffer) << "load should be called with correct buffer";
ASSERT_EQ(lastLoadBytes, testResourceBytes) << "load should be called with correct bytes";
}
TEST_F(ShovelerResourcesTest, loadInvalidType)
{
const char *testInvalidTypeId = "foo/bar";
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
bool loaded = shovelerResourcesSet(resources, testInvalidTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
ASSERT_FALSE(loaded) << "load should have failed";
}
TEST_F(ShovelerResourcesTest, freeLoaded)
{
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
const char *testResourceData = "test resource data";
nextLoadResourceData = (void *) testResourceData;
shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
shovelerResourcesFree(resources);
ASSERT_EQ(*freeResourceDataArguments.begin(), testResourceData) << "free resource data should be called with correct resource data";
resources = NULL;
}
TEST_F(ShovelerResourcesTest, requestAndLoad)
{
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
const char *testResourceData = "test resource data";
ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
nextLoadResourceData = (void *) testResourceData;
bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
ASSERT_TRUE(loaded) << "load should have succeeded";
ASSERT_EQ(resource->data, testResourceData) << "resource data should have changed after loading";
}
TEST_F(ShovelerResourcesTest, requestAndFailToLoad)
{
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
nextLoadResourceData = NULL;
bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
ASSERT_FALSE(loaded) << "load should have failed";
ASSERT_EQ(resource->data, testDefaultResourceData) << "resource data should be unchanged after failing to load";
}
TEST_F(ShovelerResourcesTest, loadAndRequest)
{
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
const char *testResourceData = "test resource data";
nextLoadResourceData = (void *) testResourceData;
shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
ASSERT_EQ(resource->data, testResourceData) << "resource data should be set to correct loaded data";
}
static void requestResources(ShovelerResources *resources, const char *typeId, const char *resourceId, void *testPointer)
{
ShovelerResourcesTest *test = (ShovelerResourcesTest *) testPointer;
test->lastRequestResources = resources;
test->lastRequestTypeId = typeId;
test->lastRequestResourceId = resourceId;
}
void *loadResource(ShovelerResourcesTypeLoader *typeLoader, const unsigned char *buffer, size_t bytes)
{
ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
test->lastLoadBuffer = buffer;
test->lastLoadBytes = bytes;
return test->nextLoadResourceData;
}
void freeResourceData(ShovelerResourcesTypeLoader *typeLoader, void *resourceData)
{
ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
test->freeResourceDataArguments.push_back(resourceData);
}
void freeTypeLoader(ShovelerResourcesTypeLoader *typeLoader)
{
ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
test->freeTypeLoaderCalled = true;
}
<commit_msg>make helper methods static in resources test<commit_after>#include <string>
#include <gtest/gtest.h>
extern "C" {
#include "shoveler/resources.h"
}
static void requestResources(ShovelerResources *resources, const char *typeId, const char *resourceId, void *testPointer);
static void *loadResource(ShovelerResourcesTypeLoader *typeLoader, const unsigned char *buffer, size_t bytes);
static void freeResourceData(ShovelerResourcesTypeLoader *typeLoader, void *resourceData);
static void freeTypeLoader(ShovelerResourcesTypeLoader *typeLoader);
class ShovelerResourcesTest : public ::testing::Test {
public:
virtual void SetUp()
{
resources = shovelerResourcesCreate(requestResources, this);
testTypeId = "test type id";
testDefaultResourceData = "test default resource";
testTypeLoader.typeId = testTypeId;
testTypeLoader.defaultResourceData = (void *) testDefaultResourceData;
testTypeLoader.data = this;
testTypeLoader.load = loadResource;
testTypeLoader.freeResourceData = freeResourceData;
testTypeLoader.free = freeTypeLoader;
bool typeLoaderRegistered = shovelerResourcesRegisterTypeLoader(resources, testTypeLoader);
ASSERT_TRUE(typeLoaderRegistered) << "test type loader should register correctly";
lastRequestResources = NULL;
lastRequestTypeId = NULL;
lastRequestResourceId = NULL;
lastLoadBuffer = NULL;
lastLoadBytes = 0;
nextLoadResourceData = NULL;
freeResourceDataArguments.clear();
freeTypeLoaderCalled = false;
}
virtual void TearDown()
{
shovelerResourcesFree(resources);
ASSERT_EQ(*freeResourceDataArguments.rbegin(), testTypeLoader.defaultResourceData) << "type loader's default resource data should be freed after resources was freed";
ASSERT_TRUE(freeTypeLoaderCalled) << "type loader should be freed after resources was freed";
}
ShovelerResources *resources;
const char *testTypeId;
const char *testDefaultResourceData;
ShovelerResourcesTypeLoader testTypeLoader;
ShovelerResources *lastRequestResources;
const char *lastRequestTypeId;
const char *lastRequestResourceId;
const unsigned char *lastLoadBuffer;
size_t lastLoadBytes;
void *nextLoadResourceData;
std::vector<void *> freeResourceDataArguments;
bool freeTypeLoaderCalled;
};
TEST_F(ShovelerResourcesTest, requestUnloaded)
{
const char *testResourceId = "test resource id";
ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
ASSERT_EQ(lastRequestResources, resources) << "request should be called with correct resources";
ASSERT_EQ(lastRequestTypeId, testTypeId) << "request should be called with correct type id";
ASSERT_EQ(lastRequestResourceId, testResourceId) << "request should be called with correct resource id";
ASSERT_EQ(resource->resources, resources) << "returned resource should have correct resources";
ASSERT_STREQ(resource->id, testResourceId) << "returned resource should have correct resource id";
ASSERT_STREQ(resource->typeId, testTypeId) << "returned resource should have correct type id";
ASSERT_EQ(resource->data, testDefaultResourceData) << "returned resource should have correct default data";
}
TEST_F(ShovelerResourcesTest, requestInvalidType)
{
const char *testInvalidTypeId = "foo/bar";
const char *testResourceId = "test resource id";
ShovelerResource *resource = shovelerResourcesGet(resources, testInvalidTypeId, testResourceId);
ASSERT_TRUE(resource == NULL) << "request should have failed";
}
TEST_F(ShovelerResourcesTest, requestNull)
{
const char *testResourceId = "test resource id";
ShovelerResources *resources = shovelerResourcesCreate(NULL, NULL);
bool typeLoaderRegistered = shovelerResourcesRegisterTypeLoader(resources, testTypeLoader);
ASSERT_TRUE(typeLoaderRegistered) << "test type loader should register correctly";
ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
ASSERT_TRUE(resource != NULL) << "returned resource must not be NULL";
shovelerResourcesFree(resources);
}
TEST_F(ShovelerResourcesTest, loadUnrequested)
{
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
const char *testResourceData = "test resource data";
nextLoadResourceData = (void *) testResourceData;
bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
ASSERT_TRUE(loaded) << "load should have succeeded";
ASSERT_EQ(lastLoadBuffer, &testResourceBuffer) << "load should be called with correct buffer";
ASSERT_EQ(lastLoadBytes, testResourceBytes) << "load should be called with correct bytes";
}
TEST_F(ShovelerResourcesTest, loadInvalidType)
{
const char *testInvalidTypeId = "foo/bar";
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
bool loaded = shovelerResourcesSet(resources, testInvalidTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
ASSERT_FALSE(loaded) << "load should have failed";
}
TEST_F(ShovelerResourcesTest, freeLoaded)
{
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
const char *testResourceData = "test resource data";
nextLoadResourceData = (void *) testResourceData;
shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
shovelerResourcesFree(resources);
ASSERT_EQ(*freeResourceDataArguments.begin(), testResourceData) << "free resource data should be called with correct resource data";
resources = NULL;
}
TEST_F(ShovelerResourcesTest, requestAndLoad)
{
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
const char *testResourceData = "test resource data";
ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
nextLoadResourceData = (void *) testResourceData;
bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
ASSERT_TRUE(loaded) << "load should have succeeded";
ASSERT_EQ(resource->data, testResourceData) << "resource data should have changed after loading";
}
TEST_F(ShovelerResourcesTest, requestAndFailToLoad)
{
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
nextLoadResourceData = NULL;
bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
ASSERT_FALSE(loaded) << "load should have failed";
ASSERT_EQ(resource->data, testDefaultResourceData) << "resource data should be unchanged after failing to load";
}
TEST_F(ShovelerResourcesTest, loadAndRequest)
{
const char *testResourceId = "test resource id";
unsigned char testResourceBuffer = 42;
size_t testResourceBytes = 1337;
const char *testResourceData = "test resource data";
nextLoadResourceData = (void *) testResourceData;
shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
ASSERT_EQ(resource->data, testResourceData) << "resource data should be set to correct loaded data";
}
static void requestResources(ShovelerResources *resources, const char *typeId, const char *resourceId, void *testPointer)
{
ShovelerResourcesTest *test = (ShovelerResourcesTest *) testPointer;
test->lastRequestResources = resources;
test->lastRequestTypeId = typeId;
test->lastRequestResourceId = resourceId;
}
static void *loadResource(ShovelerResourcesTypeLoader *typeLoader, const unsigned char *buffer, size_t bytes)
{
ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
test->lastLoadBuffer = buffer;
test->lastLoadBytes = bytes;
return test->nextLoadResourceData;
}
static void freeResourceData(ShovelerResourcesTypeLoader *typeLoader, void *resourceData)
{
ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
test->freeResourceDataArguments.push_back(resourceData);
}
static void freeTypeLoader(ShovelerResourcesTypeLoader *typeLoader)
{
ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
test->freeTypeLoaderCalled = true;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
/*
This tests the classes ImageRandomNonRepeatingIteratorWithIndex and
ImageRandomNonRepeatingConstIteratorWithIndex. This was contributed
by Rupert Brooks, McGill Centre for Intelligent
Machines, Montreal, Canada. It is heavily based on the
ImageRandomIterator test program.
*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include <algorithm>
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRandomNonRepeatingIteratorWithIndex.h"
#include "itkImageRandomNonRepeatingConstIteratorWithIndex.h"
int itkImageRandomNonRepeatingIteratorWithIndexTest(int, char* [] )
{
const unsigned int ImageDimension = 3;
typedef itk::Index< ImageDimension > PixelType;
typedef itk::Image< PixelType, ImageDimension > ImageType;
typedef itk::SizeValueType PriorityPixelType;
typedef itk::Image< PriorityPixelType, ImageDimension > PriorityImageType;
typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;
typedef itk::ImageRegionIteratorWithIndex< PriorityImageType > PriorityIteratorType;
typedef itk::ImageRandomNonRepeatingIteratorWithIndex< ImageType > RandomIteratorType;
typedef itk::ImageRandomNonRepeatingConstIteratorWithIndex< ImageType > RandomConstIteratorType;
std::cout << "Creating images" << std::endl;
ImageType::Pointer myImage = ImageType::New();
ImageType::ConstPointer myConstImage = myImage.GetPointer();
ImageType::SizeType size0;
size0[0] = 50;
size0[1] = 50;
size0[2] = 50;
unsigned long numberOfSamples = 10;
ImageType::IndexType start0;
start0.Fill(0);
ImageType::RegionType region0;
region0.SetIndex( start0 );
region0.SetSize( size0 );
myImage->SetLargestPossibleRegion( region0 );
myImage->SetBufferedRegion( region0 );
myImage->SetRequestedRegion( region0 );
myImage->Allocate();
// Make the priority image
PriorityImageType::Pointer priorityImage = PriorityImageType::New();
PriorityImageType::SizeType prioritySize;
prioritySize[0] = 50;
prioritySize[1] = 50;
prioritySize[2] = 50;
PriorityImageType::IndexType priorityStart;
priorityStart.Fill(0);
PriorityImageType::RegionType priorityRegion;
priorityRegion.SetIndex( priorityStart );
priorityRegion.SetSize( prioritySize );
priorityImage->SetLargestPossibleRegion( priorityRegion );
priorityImage->SetBufferedRegion( priorityRegion );
priorityImage->SetRequestedRegion( priorityRegion );
priorityImage->Allocate();
// we will make most of this image ones, with a small region of
// zeros. Then pixels from the zero region should be selected
// preferentially.
std::cout << "Building Priority image" << std::endl;
PriorityIteratorType pit( priorityImage, priorityRegion );
pit.GoToBegin();
while( !pit.IsAtEnd() )
{
pit.Set( 1 );
++pit;
}
PriorityImageType::IndexType substart;
substart[0] = 15;
substart[1] = 16;
substart[2] = 17;
PriorityImageType::SizeType subsize;
subsize[0] = 3;
subsize[1] = 4;
subsize[2] = 5;
PriorityImageType::RegionType subregion;
subregion.SetIndex( substart );
subregion.SetSize( subsize );
PriorityIteratorType subit( priorityImage, subregion );
subit.GoToBegin();
while( !subit.IsAtEnd() )
{
subit.Set( 0 );
++subit;
}
//********
std::cout << "Filling image with indices" << std::endl;
RandomIteratorType it( myImage, region0 );
it.SetNumberOfSamples(size0[0]*size0[1]*size0[2]);
it.GoToBegin();
ImageType::IndexType index0;
// Because the random iterator does not repeat, this should
// fill the image with indices
while( !it.IsAtEnd() )
{
index0 = it.GetIndex();
it.Set( index0 );
++it;
}
// Sample the image
IteratorType ot( myImage, region0 );
ot.GoToBegin();
// if it repeated its going to have missed a few.
std::cout << "Verifying iterators... ";
while( !ot.IsAtEnd() )
{
index0 = ot.GetIndex();
if( ot.Get() != index0 )
{
std::cerr << "Values don't correspond to what was stored "
<< std::endl;
std::cerr << "Test failed at index ";
std::cerr << index0 << std::endl;
return EXIT_FAILURE;
}
//std::cout <<".";
//std::cout << index0 << std::endl;
++ot;
}
std::cout << std::endl<<" Done ! " << std::endl;
// Verification
RandomConstIteratorType cot( myConstImage, region0 );
cot.SetNumberOfSamples( numberOfSamples );
cot.GoToBegin();
std::cout << "Verifying const iterator... ";
std::cout << "Random walk of the Iterator over the image " << std::endl;
while( !cot.IsAtEnd() )
{
index0 = cot.GetIndex();
if( cot.Get() != index0 )
{
std::cerr << "Values don't correspond to what was stored "
<< std::endl;
std::cerr << "Test failed at index ";
std::cerr << index0 << " value is " << cot.Get() << std::endl;
return EXIT_FAILURE;
}
std::cout << index0 << std::endl;
++cot;
}
std::cout << " Done ! " << std::endl;
// Verification
std::cout << "Verifying iterator in reverse direction... " << std::endl;
std::cout << "Should be a random walk too (a different one)" << std::endl;
RandomIteratorType ior( myImage, region0 );
ior.SetNumberOfSamples( numberOfSamples );
ior.GoToEnd();
--ior;
while( !ior.IsAtBegin() )
{
index0 = ior.GetIndex();
if( ior.Get() != index0 )
{
std::cerr << "Values don't correspond to what was stored "
<< std::endl;
std::cerr << "Test failed at index ";
std::cerr << index0 << " value is " << ior.Get() << std::endl;
return EXIT_FAILURE;
}
std::cout << index0 << std::endl;
--ior;
}
std::cout << index0 << std::endl; // print the value at the beginning index
std::cout << " Done ! " << std::endl;
// Verification
std::cout << "Verifying const iterator in reverse direction... ";
RandomConstIteratorType cor( myImage, region0 );
cor.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
cor.GoToEnd();
--cor; // start at the end position
while( !cor.IsAtBegin() )
{
index0 = cor.GetIndex();
if( cor.Get() != index0 )
{
std::cerr << "Values don't correspond to what was stored "
<< std::endl;
std::cerr << "Test failed at index ";
std::cerr << index0 << " value is " << cor.Get() << std::endl;
return EXIT_FAILURE;
}
std::cout << index0 << std::endl;
--cor;
}
std::cout << index0 << std::endl; // print the value at the beginning index
std::cout << " Done ! " << std::endl;
// Verification
std::cout << "Verifying const iterator in both directions... ";
RandomConstIteratorType dor( myImage, region0 );
dor.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
dor.GoToEnd();
--dor; // start at the last valid pixel position
for (unsigned int counter = 0; ! dor.IsAtEnd(); ++counter)
{
index0 = dor.GetIndex();
if( dor.Get() != index0 )
{
std::cerr << "Values don't correspond to what was stored "
<< std::endl;
std::cerr << "Test failed at index ";
std::cerr << index0 << " value is " << dor.Get() << std::endl;
return EXIT_FAILURE;
}
std::cout << index0 << std::endl;
if (counter < 6) { --dor; }
else { ++dor; }
}
std::cout << index0 << std::endl; // print the value at the beginning index
std::cout << " Done ! " << std::endl;
// Verification of the Iterator in a subregion of the image
{
std::cout << "Verifying Iterator in a Region smaller than the whole image... "
<< std::endl;
ImageType::IndexType start;
start[0] = 10;
start[1] = 12;
start[2] = 14;
ImageType::SizeType size;
size[0] = 11;
size[1] = 12;
size[2] = 13;
ImageType::RegionType region;
region.SetIndex( start );
region.SetSize( size );
RandomIteratorType cbot( myImage, region );
cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
cbot.GoToBegin();
while( !cbot.IsAtEnd() )
{
ImageType::IndexType index = cbot.GetIndex();
ImageType::PixelType pixel = cbot.Get();
if( index != pixel )
{
std::cerr << "Iterator in region test failed" << std::endl;
std::cerr << pixel << " should be" << index << std::endl;
return EXIT_FAILURE;
}
if( !region.IsInside( index ) )
{
std::cerr << "Iterator in region test failed" << std::endl;
std::cerr << index << " is outside the region " << region << std::endl;
return EXIT_FAILURE;
}
std::cout << index << std::endl;
++cbot;
}
std::cout << " Done ! " << std::endl;
}
// Verification of the Const Iterator in a subregion of the image
{
std::cout << "Verifying Const Iterator in a Region smaller than the whole image... "
<< std::endl;
ImageType::IndexType start;
start[0] = 10;
start[1] = 12;
start[2] = 14;
ImageType::SizeType size;
size[0] = 11;
size[1] = 12;
size[2] = 13;
ImageType::RegionType region;
region.SetIndex( start );
region.SetSize( size );
RandomConstIteratorType cbot( myImage, region );
cbot.SetNumberOfSamples( numberOfSamples );
cbot.GoToBegin();
while( !cbot.IsAtEnd() )
{
ImageType::IndexType index = cbot.GetIndex();
ImageType::PixelType pixel = cbot.Get();
if( index != pixel )
{
std::cerr << "Iterator in region test failed" << std::endl;
std::cerr << pixel << " should be" << index << std::endl;
return EXIT_FAILURE;
}
if( !region.IsInside( index ) )
{
std::cerr << "Iterator in region test failed" << std::endl;
std::cerr << index << " is outside the region " << region << std::endl;
return EXIT_FAILURE;
}
std::cout << index << std::endl;
++cbot;
}
std::cout << " Done ! " << std::endl;
}
// Verifying iterator works with the priority image
{
std::cout << "Verifying Iterator with respect to priority image... "
<< std::endl;
RandomIteratorType cbot( myImage, region0 );
cbot.SetPriorityImage(priorityImage);
cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
cbot.GoToBegin();
unsigned int count=0;
while( !cbot.IsAtEnd() && count<(subsize[0]*subsize[1]*subsize[2]))
{
ImageType::IndexType index = cbot.GetIndex();
if( !subregion.IsInside( index ) )
{
std::cerr << "Iterator in priority region test failed" << std::endl;
std::cerr << index << " is outside the region " << region0 << std::endl;
return EXIT_FAILURE;
}
std::cout << index << std::endl;
++cbot;
++count;
}
// Now we have walked through all the pixels of low priority, next
// one should be outside the region.
if( subregion.IsInside( index0 ) )
{
std::cerr << "Iterator in priority region test failed" << std::endl;
std::cerr << index0 << " is outside the region (should be in)" << region0 << std::endl;
return EXIT_FAILURE;
}
std::cout << " Done ! " << std::endl;
}
{
std::cout << "Verifying const Iterator with respect to priority image... "
<< std::endl;
RandomConstIteratorType cbot( myImage, region0 );
cbot.SetPriorityImage(priorityImage);
cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
cbot.GoToBegin();
unsigned int count=0;
while( !cbot.IsAtEnd() && count<(subsize[0]*subsize[1]*subsize[2]))
{
ImageType::IndexType index = cbot.GetIndex();
if( !subregion.IsInside( index ) )
{
std::cerr << "Iterator in priority region test failed" << std::endl;
std::cerr << index << " is outside the region " << region0 << std::endl;
return EXIT_FAILURE;
}
std::cout << index << std::endl;
++cbot;
++count;
}
// Now we have walked through all the pixels of low priority, next
// one should be outside the region.
if( subregion.IsInside( index0 ) )
{
std::cerr << "Iterator in priority region test failed" << std::endl;
std::cerr << index0 << " is outside the region (should be in)" << region0 << std::endl;
return EXIT_FAILURE;
}
std::cout << " Done ! " << std::endl;
}
{
// Exercise assignment operator
std::cout << "Exercising assignment operator... " << std::endl;
RandomConstIteratorType it;
it = RandomConstIteratorType( myImage, region0 );
it.SetNumberOfSamples(myImage->GetLargestPossibleRegion().GetNumberOfPixels());
it.GoToBegin();
std::cout << "Finished exercising assignment operator... " << std::endl;
}
std::cout << "Test passed" << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>BUG: Fixed warning<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
/*
This tests the classes ImageRandomNonRepeatingIteratorWithIndex and
ImageRandomNonRepeatingConstIteratorWithIndex. This was contributed
by Rupert Brooks, McGill Centre for Intelligent
Machines, Montreal, Canada. It is heavily based on the
ImageRandomIterator test program.
*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include <algorithm>
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRandomNonRepeatingIteratorWithIndex.h"
#include "itkImageRandomNonRepeatingConstIteratorWithIndex.h"
int itkImageRandomNonRepeatingIteratorWithIndexTest(int, char* [] )
{
const unsigned int ImageDimension = 3;
typedef itk::Index< ImageDimension > PixelType;
typedef itk::Image< PixelType, ImageDimension > ImageType;
typedef itk::SizeValueType PriorityPixelType;
typedef itk::Image< PriorityPixelType, ImageDimension > PriorityImageType;
typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;
typedef itk::ImageRegionIteratorWithIndex< PriorityImageType > PriorityIteratorType;
typedef itk::ImageRandomNonRepeatingIteratorWithIndex< ImageType > RandomIteratorType;
typedef itk::ImageRandomNonRepeatingConstIteratorWithIndex< ImageType > RandomConstIteratorType;
std::cout << "Creating images" << std::endl;
ImageType::Pointer myImage = ImageType::New();
ImageType::ConstPointer myConstImage = myImage.GetPointer();
ImageType::SizeType size0;
size0[0] = 50;
size0[1] = 50;
size0[2] = 50;
unsigned long numberOfSamples = 10;
ImageType::IndexType start0;
start0.Fill(0);
ImageType::RegionType region0;
region0.SetIndex( start0 );
region0.SetSize( size0 );
myImage->SetLargestPossibleRegion( region0 );
myImage->SetBufferedRegion( region0 );
myImage->SetRequestedRegion( region0 );
myImage->Allocate();
// Make the priority image
PriorityImageType::Pointer priorityImage = PriorityImageType::New();
PriorityImageType::SizeType prioritySize;
prioritySize[0] = 50;
prioritySize[1] = 50;
prioritySize[2] = 50;
PriorityImageType::IndexType priorityStart;
priorityStart.Fill(0);
PriorityImageType::RegionType priorityRegion;
priorityRegion.SetIndex( priorityStart );
priorityRegion.SetSize( prioritySize );
priorityImage->SetLargestPossibleRegion( priorityRegion );
priorityImage->SetBufferedRegion( priorityRegion );
priorityImage->SetRequestedRegion( priorityRegion );
priorityImage->Allocate();
// we will make most of this image ones, with a small region of
// zeros. Then pixels from the zero region should be selected
// preferentially.
std::cout << "Building Priority image" << std::endl;
PriorityIteratorType pit( priorityImage, priorityRegion );
pit.GoToBegin();
while( !pit.IsAtEnd() )
{
pit.Set( 1 );
++pit;
}
PriorityImageType::IndexType substart;
substart[0] = 15;
substart[1] = 16;
substart[2] = 17;
PriorityImageType::SizeType subsize;
subsize[0] = 3;
subsize[1] = 4;
subsize[2] = 5;
PriorityImageType::RegionType subregion;
subregion.SetIndex( substart );
subregion.SetSize( subsize );
PriorityIteratorType subit( priorityImage, subregion );
subit.GoToBegin();
while( !subit.IsAtEnd() )
{
subit.Set( 0 );
++subit;
}
//********
std::cout << "Filling image with indices" << std::endl;
RandomIteratorType it( myImage, region0 );
it.SetNumberOfSamples(size0[0]*size0[1]*size0[2]);
it.GoToBegin();
ImageType::IndexType index0;
// Because the random iterator does not repeat, this should
// fill the image with indices
while( !it.IsAtEnd() )
{
index0 = it.GetIndex();
it.Set( index0 );
++it;
}
// Sample the image
IteratorType ot( myImage, region0 );
ot.GoToBegin();
// if it repeated its going to have missed a few.
std::cout << "Verifying iterators... ";
while( !ot.IsAtEnd() )
{
index0 = ot.GetIndex();
if( ot.Get() != index0 )
{
std::cerr << "Values don't correspond to what was stored "
<< std::endl;
std::cerr << "Test failed at index ";
std::cerr << index0 << std::endl;
return EXIT_FAILURE;
}
//std::cout <<".";
//std::cout << index0 << std::endl;
++ot;
}
std::cout << std::endl<<" Done ! " << std::endl;
// Verification
RandomConstIteratorType cot( myConstImage, region0 );
cot.SetNumberOfSamples( numberOfSamples );
cot.GoToBegin();
std::cout << "Verifying const iterator... ";
std::cout << "Random walk of the Iterator over the image " << std::endl;
while( !cot.IsAtEnd() )
{
index0 = cot.GetIndex();
if( cot.Get() != index0 )
{
std::cerr << "Values don't correspond to what was stored "
<< std::endl;
std::cerr << "Test failed at index ";
std::cerr << index0 << " value is " << cot.Get() << std::endl;
return EXIT_FAILURE;
}
std::cout << index0 << std::endl;
++cot;
}
std::cout << " Done ! " << std::endl;
// Verification
std::cout << "Verifying iterator in reverse direction... " << std::endl;
std::cout << "Should be a random walk too (a different one)" << std::endl;
RandomIteratorType ior( myImage, region0 );
ior.SetNumberOfSamples( numberOfSamples );
ior.GoToEnd();
--ior;
while( !ior.IsAtBegin() )
{
index0 = ior.GetIndex();
if( ior.Get() != index0 )
{
std::cerr << "Values don't correspond to what was stored "
<< std::endl;
std::cerr << "Test failed at index ";
std::cerr << index0 << " value is " << ior.Get() << std::endl;
return EXIT_FAILURE;
}
std::cout << index0 << std::endl;
--ior;
}
std::cout << index0 << std::endl; // print the value at the beginning index
std::cout << " Done ! " << std::endl;
// Verification
std::cout << "Verifying const iterator in reverse direction... ";
RandomConstIteratorType cor( myImage, region0 );
cor.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
cor.GoToEnd();
--cor; // start at the end position
while( !cor.IsAtBegin() )
{
index0 = cor.GetIndex();
if( cor.Get() != index0 )
{
std::cerr << "Values don't correspond to what was stored "
<< std::endl;
std::cerr << "Test failed at index ";
std::cerr << index0 << " value is " << cor.Get() << std::endl;
return EXIT_FAILURE;
}
std::cout << index0 << std::endl;
--cor;
}
std::cout << index0 << std::endl; // print the value at the beginning index
std::cout << " Done ! " << std::endl;
// Verification
std::cout << "Verifying const iterator in both directions... ";
RandomConstIteratorType dor( myImage, region0 );
dor.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
dor.GoToEnd();
--dor; // start at the last valid pixel position
for (unsigned int counter = 0; ! dor.IsAtEnd(); ++counter)
{
index0 = dor.GetIndex();
if( dor.Get() != index0 )
{
std::cerr << "Values don't correspond to what was stored "
<< std::endl;
std::cerr << "Test failed at index ";
std::cerr << index0 << " value is " << dor.Get() << std::endl;
return EXIT_FAILURE;
}
std::cout << index0 << std::endl;
if (counter < 6) { --dor; }
else { ++dor; }
}
std::cout << index0 << std::endl; // print the value at the beginning index
std::cout << " Done ! " << std::endl;
// Verification of the Iterator in a subregion of the image
{
std::cout << "Verifying Iterator in a Region smaller than the whole image... "
<< std::endl;
ImageType::IndexType start;
start[0] = 10;
start[1] = 12;
start[2] = 14;
ImageType::SizeType size;
size[0] = 11;
size[1] = 12;
size[2] = 13;
ImageType::RegionType region;
region.SetIndex( start );
region.SetSize( size );
RandomIteratorType cbot( myImage, region );
cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
cbot.GoToBegin();
while( !cbot.IsAtEnd() )
{
ImageType::IndexType index = cbot.GetIndex();
ImageType::PixelType pixel = cbot.Get();
if( index != pixel )
{
std::cerr << "Iterator in region test failed" << std::endl;
std::cerr << pixel << " should be" << index << std::endl;
return EXIT_FAILURE;
}
if( !region.IsInside( index ) )
{
std::cerr << "Iterator in region test failed" << std::endl;
std::cerr << index << " is outside the region " << region << std::endl;
return EXIT_FAILURE;
}
std::cout << index << std::endl;
++cbot;
}
std::cout << " Done ! " << std::endl;
}
// Verification of the Const Iterator in a subregion of the image
{
std::cout << "Verifying Const Iterator in a Region smaller than the whole image... "
<< std::endl;
ImageType::IndexType start;
start[0] = 10;
start[1] = 12;
start[2] = 14;
ImageType::SizeType size;
size[0] = 11;
size[1] = 12;
size[2] = 13;
ImageType::RegionType region;
region.SetIndex( start );
region.SetSize( size );
RandomConstIteratorType cbot( myImage, region );
cbot.SetNumberOfSamples( numberOfSamples );
cbot.GoToBegin();
while( !cbot.IsAtEnd() )
{
ImageType::IndexType index = cbot.GetIndex();
ImageType::PixelType pixel = cbot.Get();
if( index != pixel )
{
std::cerr << "Iterator in region test failed" << std::endl;
std::cerr << pixel << " should be" << index << std::endl;
return EXIT_FAILURE;
}
if( !region.IsInside( index ) )
{
std::cerr << "Iterator in region test failed" << std::endl;
std::cerr << index << " is outside the region " << region << std::endl;
return EXIT_FAILURE;
}
std::cout << index << std::endl;
++cbot;
}
std::cout << " Done ! " << std::endl;
}
// Verifying iterator works with the priority image
{
std::cout << "Verifying Iterator with respect to priority image... "
<< std::endl;
RandomIteratorType cbot( myImage, region0 );
cbot.SetPriorityImage(priorityImage);
cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
cbot.GoToBegin();
unsigned int count=0;
while( !cbot.IsAtEnd() && count<(subsize[0]*subsize[1]*subsize[2]))
{
ImageType::IndexType index = cbot.GetIndex();
if( !subregion.IsInside( index ) )
{
std::cerr << "Iterator in priority region test failed" << std::endl;
std::cerr << index << " is outside the region " << region0 << std::endl;
return EXIT_FAILURE;
}
std::cout << index << std::endl;
++cbot;
++count;
}
// Now we have walked through all the pixels of low priority, next
// one should be outside the region.
if( subregion.IsInside( index0 ) )
{
std::cerr << "Iterator in priority region test failed" << std::endl;
std::cerr << index0 << " is outside the region (should be in)" << region0 << std::endl;
return EXIT_FAILURE;
}
std::cout << " Done ! " << std::endl;
}
{
std::cout << "Verifying const Iterator with respect to priority image... "
<< std::endl;
RandomConstIteratorType cbot( myImage, region0 );
cbot.SetPriorityImage(priorityImage);
cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
cbot.GoToBegin();
unsigned int count=0;
while( !cbot.IsAtEnd() && count<(subsize[0]*subsize[1]*subsize[2]))
{
ImageType::IndexType index = cbot.GetIndex();
if( !subregion.IsInside( index ) )
{
std::cerr << "Iterator in priority region test failed" << std::endl;
std::cerr << index << " is outside the region " << region0 << std::endl;
return EXIT_FAILURE;
}
std::cout << index << std::endl;
++cbot;
++count;
}
// Now we have walked through all the pixels of low priority, next
// one should be outside the region.
if( subregion.IsInside( index0 ) )
{
std::cerr << "Iterator in priority region test failed" << std::endl;
std::cerr << index0 << " is outside the region (should be in)" << region0 << std::endl;
return EXIT_FAILURE;
}
std::cout << " Done ! " << std::endl;
}
{
// Exercise assignment operator
std::cout << "Exercising assignment operator... " << std::endl;
RandomConstIteratorType iteratorAssignment;
iteratorAssignment = RandomConstIteratorType( myImage, myImage->GetLargestPossibleRegion() );
iteratorAssignment.SetNumberOfSamples(myImage->GetLargestPossibleRegion().GetNumberOfPixels());
iteratorAssignment.GoToBegin();
std::cout << "Finished exercising assignment operator!" << std::endl;
}
std::cout << "Test passed" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sbxstr.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 21:53:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#include "sbx.hxx"
#include "sbxconv.hxx"
#include "sbxres.hxx"
// AB 29.10.99 Unicode
#ifndef _USE_NO_NAMESPACE
using namespace rtl;
#endif
// Die Konversion eines Items auf String wird ueber die Put-Methoden
// der einzelnen Datentypen abgewickelt, um doppelten Code zu vermeiden.
XubString ImpGetString( const SbxValues* p )
{
SbxValues aTmp;
XubString aRes;
aTmp.eType = SbxSTRING;
aTmp.pString = &aRes;
switch( p->eType )
{
case SbxNULL:
SbxBase::SetError( SbxERR_CONVERSION );
case SbxEMPTY:
break;
case SbxCHAR:
ImpPutChar( &aTmp, p->nChar ); break;
case SbxBYTE:
ImpPutByte( &aTmp, p->nByte ); break;
case SbxINTEGER:
ImpPutInteger( &aTmp, p->nInteger ); break;
case SbxBOOL:
ImpPutBool( &aTmp, p->nUShort ); break;
case SbxUSHORT:
ImpPutUShort( &aTmp, p->nUShort ); break;
case SbxLONG:
ImpPutLong( &aTmp, p->nLong ); break;
case SbxULONG:
ImpPutULong( &aTmp, p->nULong ); break;
case SbxSINGLE:
ImpPutSingle( &aTmp, p->nSingle ); break;
case SbxDOUBLE:
ImpPutDouble( &aTmp, p->nDouble ); break;
case SbxCURRENCY:
ImpPutCurrency( &aTmp, p->nLong64 ); break;
case SbxDECIMAL:
case SbxBYREF | SbxDECIMAL:
ImpPutDecimal( &aTmp, p->pDecimal ); break;
case SbxSALINT64:
ImpPutInt64( &aTmp, p->nInt64 ); break;
case SbxSALUINT64:
ImpPutUInt64( &aTmp, p->uInt64 ); break;
case SbxBYREF | SbxSTRING:
case SbxSTRING:
case SbxLPSTR:
if( p->pString )
aRes = *p->pString;
break;
case SbxOBJECT:
{
SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
if( pVal )
aRes = pVal->GetString();
else
SbxBase::SetError( SbxERR_NO_OBJECT );
break;
}
case SbxERROR:
// Hier wird der String "Error n" erzeugt
aRes = SbxRes( STRING_ERRORMSG );
aRes += p->nUShort; break;
case SbxDATE:
ImpPutDate( &aTmp, p->nDouble ); break;
case SbxBYREF | SbxCHAR:
ImpPutChar( &aTmp, *p->pChar ); break;
case SbxBYREF | SbxBYTE:
ImpPutByte( &aTmp, *p->pByte ); break;
case SbxBYREF | SbxINTEGER:
case SbxBYREF | SbxBOOL:
ImpPutInteger( &aTmp, *p->pInteger ); break;
case SbxBYREF | SbxLONG:
ImpPutLong( &aTmp, *p->pLong ); break;
case SbxBYREF | SbxULONG:
ImpPutULong( &aTmp, *p->pULong ); break;
case SbxBYREF | SbxERROR:
case SbxBYREF | SbxUSHORT:
ImpPutUShort( &aTmp, *p->pUShort ); break;
case SbxBYREF | SbxSINGLE:
ImpPutSingle( &aTmp, *p->pSingle ); break;
case SbxBYREF | SbxDATE:
case SbxBYREF | SbxDOUBLE:
ImpPutDouble( &aTmp, *p->pDouble ); break;
case SbxBYREF | SbxCURRENCY:
ImpPutCurrency( &aTmp, *p->pLong64 ); break;
case SbxBYREF | SbxSALINT64:
ImpPutInt64( &aTmp, *p->pnInt64 ); break;
case SbxBYREF | SbxSALUINT64:
ImpPutUInt64( &aTmp, *p->puInt64 ); break;
default:
SbxBase::SetError( SbxERR_CONVERSION );
}
return aRes;
}
// AB 10.4.97, neue Funktion fuer SbxValue::GetCoreString()
XubString ImpGetCoreString( const SbxValues* p )
{
// Vorerst nur fuer double
if( ( p->eType & (~SbxBYREF) ) == SbxDOUBLE )
{
SbxValues aTmp;
XubString aRes;
aTmp.eType = SbxSTRING;
aTmp.pString = &aRes;
if( p->eType == SbxDOUBLE )
ImpPutDouble( &aTmp, p->nDouble, /*bCoreString=*/TRUE );
else
ImpPutDouble( &aTmp, *p->pDouble, /*bCoreString=*/TRUE );
return aRes;
}
else
return ImpGetString( p );
}
void ImpPutString( SbxValues* p, const XubString* n )
{
SbxValues aTmp;
aTmp.eType = SbxSTRING;
XubString* pTmp = NULL;
// Sicherheitshalber, falls ein NULL-Ptr kommt
if( !n )
n = pTmp = new XubString;
aTmp.pString = (XubString*) n;
switch( p->eType )
{
case SbxCHAR:
p->nChar = ImpGetChar( &aTmp ); break;
case SbxBYTE:
p->nByte = ImpGetByte( &aTmp ); break;
case SbxINTEGER:
case SbxBOOL:
p->nInteger = ImpGetInteger( &aTmp ); break;
case SbxLONG:
p->nLong = ImpGetLong( &aTmp ); break;
case SbxULONG:
p->nULong = ImpGetULong( &aTmp ); break;
case SbxERROR:
case SbxUSHORT:
p->nUShort = ImpGetUShort( &aTmp ); break;
case SbxSINGLE:
p->nSingle = ImpGetSingle( &aTmp ); break;
case SbxDATE:
p->nDouble = ImpGetDate( &aTmp ); break;
case SbxDOUBLE:
p->nDouble = ImpGetDouble( &aTmp ); break;
case SbxULONG64:
p->nLong64 = ImpGetCurrency( &aTmp ); break;
case SbxDECIMAL:
case SbxBYREF | SbxDECIMAL:
releaseDecimalPtr( p->pDecimal );
p->pDecimal = ImpGetDecimal( &aTmp ); break;
case SbxSALINT64:
p->nInt64 = ImpGetInt64( &aTmp ); break;
case SbxSALUINT64:
p->uInt64 = ImpGetUInt64( &aTmp ); break;
case SbxBYREF | SbxSTRING:
case SbxSTRING:
case SbxLPSTR:
if( n->Len() )
{
if( !p->pString )
p->pString = new XubString;
*p->pString = *n;
}
else
delete p->pString, p->pString = NULL;
break;
case SbxOBJECT:
{
SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
if( pVal )
pVal->PutString( *n );
else
SbxBase::SetError( SbxERR_NO_OBJECT );
break;
}
case SbxBYREF | SbxCHAR:
*p->pChar = ImpGetChar( p ); break;
case SbxBYREF | SbxBYTE:
*p->pByte = ImpGetByte( p ); break;
case SbxBYREF | SbxINTEGER:
*p->pInteger = ImpGetInteger( p ); break;
case SbxBYREF | SbxBOOL:
*p->pUShort = ImpGetBool( p ); break;
case SbxBYREF | SbxERROR:
case SbxBYREF | SbxUSHORT:
*p->pUShort = ImpGetUShort( p ); break;
case SbxBYREF | SbxLONG:
*p->pLong = ImpGetLong( p ); break;
case SbxBYREF | SbxULONG:
*p->pULong = ImpGetULong( p ); break;
case SbxBYREF | SbxSINGLE:
*p->pSingle = ImpGetSingle( p ); break;
case SbxBYREF | SbxDATE:
*p->pDouble = ImpGetDate( p ); break;
case SbxBYREF | SbxDOUBLE:
*p->pDouble = ImpGetDouble( p ); break;
case SbxBYREF | SbxCURRENCY:
*p->pLong64 = ImpGetCurrency( p ); break;
default:
SbxBase::SetError( SbxERR_CONVERSION );
}
delete pTmp;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.120); FILE MERGED 2006/09/01 17:17:09 kaib 1.3.120.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sbxstr.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 10:11:56 $
*
* 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_basic.hxx"
#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#include "sbx.hxx"
#include "sbxconv.hxx"
#include "sbxres.hxx"
// AB 29.10.99 Unicode
#ifndef _USE_NO_NAMESPACE
using namespace rtl;
#endif
// Die Konversion eines Items auf String wird ueber die Put-Methoden
// der einzelnen Datentypen abgewickelt, um doppelten Code zu vermeiden.
XubString ImpGetString( const SbxValues* p )
{
SbxValues aTmp;
XubString aRes;
aTmp.eType = SbxSTRING;
aTmp.pString = &aRes;
switch( p->eType )
{
case SbxNULL:
SbxBase::SetError( SbxERR_CONVERSION );
case SbxEMPTY:
break;
case SbxCHAR:
ImpPutChar( &aTmp, p->nChar ); break;
case SbxBYTE:
ImpPutByte( &aTmp, p->nByte ); break;
case SbxINTEGER:
ImpPutInteger( &aTmp, p->nInteger ); break;
case SbxBOOL:
ImpPutBool( &aTmp, p->nUShort ); break;
case SbxUSHORT:
ImpPutUShort( &aTmp, p->nUShort ); break;
case SbxLONG:
ImpPutLong( &aTmp, p->nLong ); break;
case SbxULONG:
ImpPutULong( &aTmp, p->nULong ); break;
case SbxSINGLE:
ImpPutSingle( &aTmp, p->nSingle ); break;
case SbxDOUBLE:
ImpPutDouble( &aTmp, p->nDouble ); break;
case SbxCURRENCY:
ImpPutCurrency( &aTmp, p->nLong64 ); break;
case SbxDECIMAL:
case SbxBYREF | SbxDECIMAL:
ImpPutDecimal( &aTmp, p->pDecimal ); break;
case SbxSALINT64:
ImpPutInt64( &aTmp, p->nInt64 ); break;
case SbxSALUINT64:
ImpPutUInt64( &aTmp, p->uInt64 ); break;
case SbxBYREF | SbxSTRING:
case SbxSTRING:
case SbxLPSTR:
if( p->pString )
aRes = *p->pString;
break;
case SbxOBJECT:
{
SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
if( pVal )
aRes = pVal->GetString();
else
SbxBase::SetError( SbxERR_NO_OBJECT );
break;
}
case SbxERROR:
// Hier wird der String "Error n" erzeugt
aRes = SbxRes( STRING_ERRORMSG );
aRes += p->nUShort; break;
case SbxDATE:
ImpPutDate( &aTmp, p->nDouble ); break;
case SbxBYREF | SbxCHAR:
ImpPutChar( &aTmp, *p->pChar ); break;
case SbxBYREF | SbxBYTE:
ImpPutByte( &aTmp, *p->pByte ); break;
case SbxBYREF | SbxINTEGER:
case SbxBYREF | SbxBOOL:
ImpPutInteger( &aTmp, *p->pInteger ); break;
case SbxBYREF | SbxLONG:
ImpPutLong( &aTmp, *p->pLong ); break;
case SbxBYREF | SbxULONG:
ImpPutULong( &aTmp, *p->pULong ); break;
case SbxBYREF | SbxERROR:
case SbxBYREF | SbxUSHORT:
ImpPutUShort( &aTmp, *p->pUShort ); break;
case SbxBYREF | SbxSINGLE:
ImpPutSingle( &aTmp, *p->pSingle ); break;
case SbxBYREF | SbxDATE:
case SbxBYREF | SbxDOUBLE:
ImpPutDouble( &aTmp, *p->pDouble ); break;
case SbxBYREF | SbxCURRENCY:
ImpPutCurrency( &aTmp, *p->pLong64 ); break;
case SbxBYREF | SbxSALINT64:
ImpPutInt64( &aTmp, *p->pnInt64 ); break;
case SbxBYREF | SbxSALUINT64:
ImpPutUInt64( &aTmp, *p->puInt64 ); break;
default:
SbxBase::SetError( SbxERR_CONVERSION );
}
return aRes;
}
// AB 10.4.97, neue Funktion fuer SbxValue::GetCoreString()
XubString ImpGetCoreString( const SbxValues* p )
{
// Vorerst nur fuer double
if( ( p->eType & (~SbxBYREF) ) == SbxDOUBLE )
{
SbxValues aTmp;
XubString aRes;
aTmp.eType = SbxSTRING;
aTmp.pString = &aRes;
if( p->eType == SbxDOUBLE )
ImpPutDouble( &aTmp, p->nDouble, /*bCoreString=*/TRUE );
else
ImpPutDouble( &aTmp, *p->pDouble, /*bCoreString=*/TRUE );
return aRes;
}
else
return ImpGetString( p );
}
void ImpPutString( SbxValues* p, const XubString* n )
{
SbxValues aTmp;
aTmp.eType = SbxSTRING;
XubString* pTmp = NULL;
// Sicherheitshalber, falls ein NULL-Ptr kommt
if( !n )
n = pTmp = new XubString;
aTmp.pString = (XubString*) n;
switch( p->eType )
{
case SbxCHAR:
p->nChar = ImpGetChar( &aTmp ); break;
case SbxBYTE:
p->nByte = ImpGetByte( &aTmp ); break;
case SbxINTEGER:
case SbxBOOL:
p->nInteger = ImpGetInteger( &aTmp ); break;
case SbxLONG:
p->nLong = ImpGetLong( &aTmp ); break;
case SbxULONG:
p->nULong = ImpGetULong( &aTmp ); break;
case SbxERROR:
case SbxUSHORT:
p->nUShort = ImpGetUShort( &aTmp ); break;
case SbxSINGLE:
p->nSingle = ImpGetSingle( &aTmp ); break;
case SbxDATE:
p->nDouble = ImpGetDate( &aTmp ); break;
case SbxDOUBLE:
p->nDouble = ImpGetDouble( &aTmp ); break;
case SbxULONG64:
p->nLong64 = ImpGetCurrency( &aTmp ); break;
case SbxDECIMAL:
case SbxBYREF | SbxDECIMAL:
releaseDecimalPtr( p->pDecimal );
p->pDecimal = ImpGetDecimal( &aTmp ); break;
case SbxSALINT64:
p->nInt64 = ImpGetInt64( &aTmp ); break;
case SbxSALUINT64:
p->uInt64 = ImpGetUInt64( &aTmp ); break;
case SbxBYREF | SbxSTRING:
case SbxSTRING:
case SbxLPSTR:
if( n->Len() )
{
if( !p->pString )
p->pString = new XubString;
*p->pString = *n;
}
else
delete p->pString, p->pString = NULL;
break;
case SbxOBJECT:
{
SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
if( pVal )
pVal->PutString( *n );
else
SbxBase::SetError( SbxERR_NO_OBJECT );
break;
}
case SbxBYREF | SbxCHAR:
*p->pChar = ImpGetChar( p ); break;
case SbxBYREF | SbxBYTE:
*p->pByte = ImpGetByte( p ); break;
case SbxBYREF | SbxINTEGER:
*p->pInteger = ImpGetInteger( p ); break;
case SbxBYREF | SbxBOOL:
*p->pUShort = ImpGetBool( p ); break;
case SbxBYREF | SbxERROR:
case SbxBYREF | SbxUSHORT:
*p->pUShort = ImpGetUShort( p ); break;
case SbxBYREF | SbxLONG:
*p->pLong = ImpGetLong( p ); break;
case SbxBYREF | SbxULONG:
*p->pULong = ImpGetULong( p ); break;
case SbxBYREF | SbxSINGLE:
*p->pSingle = ImpGetSingle( p ); break;
case SbxBYREF | SbxDATE:
*p->pDouble = ImpGetDate( p ); break;
case SbxBYREF | SbxDOUBLE:
*p->pDouble = ImpGetDouble( p ); break;
case SbxBYREF | SbxCURRENCY:
*p->pLong64 = ImpGetCurrency( p ); break;
default:
SbxBase::SetError( SbxERR_CONVERSION );
}
delete pTmp;
}
<|endoftext|>
|
<commit_before>#pragma once
#include "util/meta_helpers.hpp"
#include <bulk/world.hpp>
#include <memory>
/**
* \file future.hpp
*
* This header defines a future object, which is used to refer to remote values
* that are not yet known.
*/
namespace bulk {
/**
* Represents a value that will become known in the upcoming superstep
*/
template <typename T>
class future {
using value_type = typename bulk::meta::representation<T>::type;
public:
/**
* Initialize the future.
*/
future(bulk::world& world) : world_(world) {
buffer_ = std::make_unique<T>();
}
/**
* Deconstruct the future.
*/
~future() {}
future(const future<T>& other) = delete;
void operator=(const future<T>& other) = delete;
future(future<T>&& other) : world_(other.world_) {
*this = std::move(other);
}
/**
* Move a future.
*/
void operator=(future<T>&& other) { buffer_ = std::move(other.buffer_); }
/**
* Get a reference to the value held by the future.
*
* \returns a reference to the value
*/
value_type& value() { return *buffer_.get(); }
/**
* Get a reference to the world of the future.
*
* \returns a reference to the world of the future
*/
bulk::world& world() { return world_; }
private:
std::unique_ptr<value_type> buffer_;
bulk::world& world_;
};
template <typename T>
class future<T[]> {
public:
/**
* Initialize the future.
*/
future(bulk::world& world, int size) : world_(world) {
buffer_ = std::unique_ptr<T[]>(new T[size]);
}
/**
* Deconstruct the future.
*/
~future() {}
future(const future<T[]>& other) = delete;
void operator=(const future<T[]>& other) = delete;
future(future<T[]>&& other) : world_(other.world_) {
*this = std::move(other);
}
void operator=(future<T[]>&& other) { buffer_ = std::move(other.buffer_); }
/**
* ...
*/
T& operator[](int i) { return buffer_[i]; }
/**
* Get a reference to the world of the future.
*
* \returns a reference to the world of the future
*/
bulk::world& world() { return world_; }
T* buffer() { return buffer_.get(); }
private:
std::unique_ptr<T[]> buffer_;
bulk::world& world_;
};
} // namespace bulk
<commit_msg>Add implicit cast to future<commit_after>#pragma once
#include "util/meta_helpers.hpp"
#include <bulk/world.hpp>
#include <memory>
/**
* \file future.hpp
*
* This header defines a future object, which is used to refer to remote values
* that are not yet known.
*/
namespace bulk {
/**
* Represents a value that will become known in the upcoming superstep
*/
template <typename T>
class future {
using value_type = typename bulk::meta::representation<T>::type;
public:
/**
* Initialize the future.
*/
future(bulk::world& world) : world_(world) {
buffer_ = std::make_unique<T>();
}
/**
* Deconstruct the future.
*/
~future() {}
future(const future<T>& other) = delete;
void operator=(const future<T>& other) = delete;
future(future<T>&& other) : world_(other.world_) {
*this = std::move(other);
}
/**
* Move a future.
*/
void operator=(future<T>&& other) { buffer_ = std::move(other.buffer_); }
/**
* Get a reference to the value held by the future.
*
* \returns a reference to the value
*/
value_type& value() { return *buffer_.get(); }
const value_type& value() const { return *buffer_.get(); }
/**
* Implicitly get the value held by the future
*
* \note This is for code like `myint = myfuture + 5;`.
*/
operator value_type&() { return this->value(); }
operator const value_type&() const { return this->value(); }
/**
* Get a reference to the world of the future.
*
* \returns a reference to the world of the future
*/
bulk::world& world() { return world_; }
private:
std::unique_ptr<value_type> buffer_;
bulk::world& world_;
};
template <typename T>
class future<T[]> {
public:
/**
* Initialize the future.
*/
future(bulk::world& world, int size) : world_(world) {
buffer_ = std::unique_ptr<T[]>(new T[size]);
}
/**
* Deconstruct the future.
*/
~future() {}
future(const future<T[]>& other) = delete;
void operator=(const future<T[]>& other) = delete;
future(future<T[]>&& other) : world_(other.world_) {
*this = std::move(other);
}
void operator=(future<T[]>&& other) { buffer_ = std::move(other.buffer_); }
/**
* ...
*/
T& operator[](int i) { return buffer_[i]; }
/**
* Get a reference to the world of the future.
*
* \returns a reference to the world of the future
*/
bulk::world& world() { return world_; }
T* buffer() { return buffer_.get(); }
private:
std::unique_ptr<T[]> buffer_;
bulk::world& world_;
};
} // namespace bulk
<|endoftext|>
|
<commit_before>/*
* Copyright 2014-2020 CNRS INRIA
*/
#ifndef __eigenpy_fwd_hpp__
#define __eigenpy_fwd_hpp__
#include "eigenpy/config.hpp"
#include <boost/python.hpp>
#include <Eigen/Core>
#define NO_IMPORT_ARRAY
#include "eigenpy/numpy.hpp"
#undef NO_IMPORT_ARRAY
#if EIGEN_VERSION_AT_LEAST(3,2,90)
#define EIGENPY_DEFAULT_ALIGNMENT_VALUE Eigen::Aligned16
#else
#define EIGENPY_DEFAULT_ALIGNMENT_VALUE Eigen::Aligned
#endif
#define EIGENPY_NO_ALIGNMENT_VALUE Eigen::Unaligned
#include "eigenpy/expose.hpp"
namespace eigenpy
{
template<typename MatType> struct EigenToPy;
template<typename MatType> struct EigenFromPy;
}
#endif // ifndef __eigenpy_fwd_hpp__
<commit_msg>core: add EIGENPY_UNUSED_VARIABLE macro<commit_after>/*
* Copyright 2014-2020 CNRS INRIA
*/
#ifndef __eigenpy_fwd_hpp__
#define __eigenpy_fwd_hpp__
#include "eigenpy/config.hpp"
#include <boost/python.hpp>
#include <Eigen/Core>
#define NO_IMPORT_ARRAY
#include "eigenpy/numpy.hpp"
#undef NO_IMPORT_ARRAY
#if EIGEN_VERSION_AT_LEAST(3,2,90)
#define EIGENPY_DEFAULT_ALIGNMENT_VALUE Eigen::Aligned16
#else
#define EIGENPY_DEFAULT_ALIGNMENT_VALUE Eigen::Aligned
#endif
#define EIGENPY_NO_ALIGNMENT_VALUE Eigen::Unaligned
#define EIGENPY_UNUSED_VARIABLE(var) (void)(var)
#include "eigenpy/expose.hpp"
namespace eigenpy
{
template<typename MatType> struct EigenToPy;
template<typename MatType> struct EigenFromPy;
}
#endif // ifndef __eigenpy_fwd_hpp__
<|endoftext|>
|
<commit_before>// Network API based on boost::asio
#ifndef LIBPORT_ASIO_HH
# define LIBPORT_ASIO_HH
# include <iostream>
# include <boost/asio.hpp>
#ifndef LIBPORT_NO_SSL
# include <boost/asio/ssl.hpp>
#endif
# include <boost/function.hpp>
# include <libport/destructible.hh>
# include <libport/finally.hh>
namespace libport
{
class AsioDestructible: public Destructible
{
protected:
virtual void doDestroy();
};
/** BaseSocket class.
*
* This class has a callback-based API: onReadFunc() and onErrorFunc().
*/
class BaseSocket: public AsioDestructible
{
public:
virtual ~BaseSocket(){}
libport::Finally deletor;
/// Write data asynchronously to the socket.
virtual void write(const void* data, unsigned int length) = 0;
/// Alias on write() for API compatibility.
inline void send(void* addr, int len) {write((const void*)addr, len);}
/// Alias on close() for API compatibility.
inline void disconnect() {close();}
/// Return if the socket is connected to a remote host.
virtual bool isConnected() = 0;
/// Disconnect the socket from the remote host.
virtual void close() = 0;
/// Callback function called each time new data is available.
boost::function1<bool, boost::asio::streambuf&> onReadFunc;
/// Callback function called in case of error on the socket.
boost::function1<void, boost::system::error_code> onErrorFunc;
};
/** Socket class with a higher API.
*
*/
class Socket: public AsioDestructible
{
public:
Socket(): base_(0){}
virtual ~Socket();
/** Set underlying BaseSocket object, setup its callbacks to call our virtual functions.
*/
virtual void setBase(BaseSocket*);
/** Called each time new data is received.
* \return the number of bytes used in buffer. The remaining data will
* be passed again to this function as soon as at least an extra byte
* is available.
*/
virtual int onRead(const void*, int length){return length;}
/** Called in case of error on the socket.
*/
virtual void onError(boost::system::error_code){}
/// Ask for the asynchronous destruction of this object.
virtual void destroy();
inline void write(const void* data, unsigned int length)
{ base_->write(data, length);}
/// Alias on write() for API compatibility.
inline void send(void* addr, int len) {write((const void*)addr, len);}
inline void close() {if (base_) base_->close();}
inline bool isConnected() {return base_?base_->isConnected():false;}
boost::system::error_code connect(const std::string& host,
const std::string& port, bool udp=false);
typedef void* Handle;
typedef boost::function0<Socket*> SocketFactory;
static Handle listen(SocketFactory f, const std::string& host,
const std::string& port, boost::system::error_code & erc,
bool udp = false);
#ifndef LIBPORT_NO_SSL
static Handle listenSSL(SocketFactory f, const std::string& host,
const std::string& port,
boost::system::error_code& erc,
boost::asio::ssl::context_base::method ctx
= boost::asio::ssl::context::sslv23_server,
boost::asio::ssl::context::options options
= boost::asio::ssl::context::verify_none,
const std::string& privateKeyFile = "",
const std::string& certChainFile = "",
const std::string& tmpDHFile = "" ,
const std::string& cipherList = "");
#endif
protected:
bool onRead_(boost::asio::streambuf&);
std::string buffer;
BaseSocket* base_;
private:
template<typename Proto, typename BaseFactory> static boost::system::error_code
listenProto(SocketFactory f, const std::string& host,
const std::string&port, BaseFactory bf);
template<typename Proto, typename BaseFactory> boost::system::error_code
connectProto(const std::string& host, const std::string& port, BaseFactory bf);
};
}
# include "libport/asio.hxx"
#endif
<commit_msg>Add a send(std::string) to Socket.<commit_after>// Network API based on boost::asio
#ifndef LIBPORT_ASIO_HH
# define LIBPORT_ASIO_HH
# include <iostream>
# include <boost/asio.hpp>
#ifndef LIBPORT_NO_SSL
# include <boost/asio/ssl.hpp>
#endif
# include <boost/function.hpp>
# include <libport/destructible.hh>
# include <libport/finally.hh>
namespace libport
{
class AsioDestructible: public Destructible
{
protected:
virtual void doDestroy();
};
/** BaseSocket class.
*
* This class has a callback-based API: onReadFunc() and onErrorFunc().
*/
class BaseSocket: public AsioDestructible
{
public:
virtual ~BaseSocket(){}
libport::Finally deletor;
/// Write data asynchronously to the socket.
virtual void write(const void* data, unsigned int length) = 0;
/// Alias on write() for API compatibility.
inline void send(void* addr, int len) {write((const void*)addr, len);}
/// Alias on close() for API compatibility.
inline void disconnect() {close();}
/// Return if the socket is connected to a remote host.
virtual bool isConnected() = 0;
/// Disconnect the socket from the remote host.
virtual void close() = 0;
/// Callback function called each time new data is available.
boost::function1<bool, boost::asio::streambuf&> onReadFunc;
/// Callback function called in case of error on the socket.
boost::function1<void, boost::system::error_code> onErrorFunc;
};
/** Socket class with a higher API.
*
*/
class Socket: public AsioDestructible
{
public:
Socket(): base_(0){}
virtual ~Socket();
/** Set underlying BaseSocket object, setup its callbacks to call our virtual functions.
*/
virtual void setBase(BaseSocket*);
/** Called each time new data is received.
* \return the number of bytes used in buffer. The remaining data will
* be passed again to this function as soon as at least an extra byte
* is available.
*/
virtual int onRead(const void*, int length){return length;}
/** Called in case of error on the socket.
*/
virtual void onError(boost::system::error_code){}
/// Ask for the asynchronous destruction of this object.
virtual void destroy();
inline void write(const void* data, unsigned int length)
{ base_->write(data, length);}
/// Alias on write() for API compatibility.
inline void send(void* addr, int len) {write((const void*)addr, len);}
inline void send(const std::string& s) {write(s.c_str(), s.length());}
inline void close() {if (base_) base_->close();}
inline bool isConnected() {return base_?base_->isConnected():false;}
boost::system::error_code connect(const std::string& host,
const std::string& port, bool udp=false);
typedef void* Handle;
typedef boost::function0<Socket*> SocketFactory;
static Handle listen(SocketFactory f, const std::string& host,
const std::string& port, boost::system::error_code & erc,
bool udp = false);
#ifndef LIBPORT_NO_SSL
static Handle listenSSL(SocketFactory f, const std::string& host,
const std::string& port,
boost::system::error_code& erc,
boost::asio::ssl::context_base::method ctx
= boost::asio::ssl::context::sslv23_server,
boost::asio::ssl::context::options options
= boost::asio::ssl::context::verify_none,
const std::string& privateKeyFile = "",
const std::string& certChainFile = "",
const std::string& tmpDHFile = "" ,
const std::string& cipherList = "");
#endif
protected:
bool onRead_(boost::asio::streambuf&);
std::string buffer;
BaseSocket* base_;
private:
template<typename Proto, typename BaseFactory> static boost::system::error_code
listenProto(SocketFactory f, const std::string& host,
const std::string&port, BaseFactory bf);
template<typename Proto, typename BaseFactory> boost::system::error_code
connectProto(const std::string& host, const std::string& port, BaseFactory bf);
};
}
# include "libport/asio.hxx"
#endif
<|endoftext|>
|
<commit_before>/**
* @file common.tcc
* @author Sean Massung
* @author Chase Geigle
*/
#include <map>
#include <sstream>
#include <sys/stat.h>
#include "util/common.h"
#include "io/mmap_file.h"
namespace meta {
namespace common {
template <class T>
std::string to_string(const T & value)
{
std::stringstream ss;
ss << value;
return ss.str();
}
std::string add_commas(const std::string & number)
{
std::string ret{""};
size_t counter = 0;
for(auto it = number.rbegin(); it != number.rend(); ++it, ++counter)
{
if(counter != 0 && counter != number.size() && counter % 3 == 0)
ret = ',' + ret;
ret = *it + ret;
}
return ret;
}
uint64_t file_size(const std::string & filename)
{
if(!file_exists(filename))
return 0;
struct stat64 st;
stat64(filename.c_str(), &st);
return st.st_size;
}
bool file_exists(const std::string & filename)
{
FILE* f = fopen(filename.c_str(), "r");
if(f != nullptr)
{
fclose(f);
return true;
}
return false;
}
uint64_t num_lines(const std::string & filename)
{
io::mmap_file file{filename};
return std::count(file.start(), file.start() + file.size(), '\n');
}
std::string bytes_to_units(double num_bytes)
{
std::string units = "bytes";
for(auto & u: {"KB", "MB", "GB", "TB"})
{
if(num_bytes >= 1024)
{
num_bytes /= 1024;
units = u;
}
}
num_bytes = static_cast<double>(static_cast<int>(num_bytes * 100)) / 100;
return to_string(num_bytes) + " " + units;
}
template <class Duration, class Functor>
Duration time(Functor && functor)
{
auto start = std::chrono::steady_clock::now();
functor();
auto end = std::chrono::steady_clock::now();
return std::chrono::duration_cast<Duration>(end - start);
}
void show_progress(size_t idx, size_t max, size_t freq, const std::string & prefix)
{
if(idx % freq == 0)
{
std::cerr << prefix << static_cast<double>(idx) / max * 100 << "% \r";
std::flush(std::cerr);
}
}
void end_progress(const std::string & prefix)
{
std::cerr << prefix << "100% " << std::endl;
}
template <class Key,
class Value,
class... Args,
template <class, class, class...> class Map>
Value safe_at(const Map<Key, Value, Args...> & map, const Key & key)
{
auto it = map.find(key);
if(it == map.end())
return Value{};
return it->second;
}
template <class Result, class... Args>
std::function<Result(Args...)> memoize(std::function<Result(Args...)> fun)
{
return [fun](Args... args) {
static std::map<std::tuple<Args...>, Result> map_;
auto it = map_.find(std::make_tuple(args...));
if(it != map_.end())
return it->second;
return map_[std::make_tuple(args...)] = fun(args...);
};
}
template <class Key, class Value>
void save_mapping(const util::invertible_map<Key, Value> & map,
const std::string & filename)
{
std::ofstream outfile{filename};
for(auto & p: map)
outfile << p.first << " " << p.second << "\n";
}
template <class T>
void save_mapping(const std::vector<T> & vec, const std::string & filename)
{
std::ofstream outfile{filename};
for(auto & v: vec)
outfile << v << "\n";
}
template <class Key, class Value>
void load_mapping(util::invertible_map<Key, Value> & map,
const std::string & filename)
{
std::ifstream input{filename};
Key k;
Value v;
while((input >> k) && (input >> v))
map.insert(std::make_pair(k, v));
}
template <class T>
void load_mapping(std::vector<T> & vec, const std::string & filename)
{
std::ifstream input{filename};
uint64_t size = common::num_lines(filename);
vec.reserve(size);
T val;
while(input >> val)
vec.push_back(val);
}
template <class T, class... Args>
std::unique_ptr<T> make_unique(Args &&... args)
{
return std::unique_ptr<T>{new T{std::forward<Args>(args)...}};
}
}
}
<commit_msg>add progress output for line counting<commit_after>/**
* @file common.tcc
* @author Sean Massung
* @author Chase Geigle
*/
#include <map>
#include <sstream>
#include <sys/stat.h>
#include "util/common.h"
#include "io/mmap_file.h"
namespace meta {
namespace common {
template <class T>
std::string to_string(const T & value)
{
std::stringstream ss;
ss << value;
return ss.str();
}
std::string add_commas(const std::string & number)
{
std::string ret{""};
size_t counter = 0;
for(auto it = number.rbegin(); it != number.rend(); ++it, ++counter)
{
if(counter != 0 && counter != number.size() && counter % 3 == 0)
ret = ',' + ret;
ret = *it + ret;
}
return ret;
}
uint64_t file_size(const std::string & filename)
{
if(!file_exists(filename))
return 0;
struct stat64 st;
stat64(filename.c_str(), &st);
return st.st_size;
}
bool file_exists(const std::string & filename)
{
FILE* f = fopen(filename.c_str(), "r");
if(f != nullptr)
{
fclose(f);
return true;
}
return false;
}
uint64_t num_lines(const std::string & filename)
{
io::mmap_file file{filename};
uint64_t num = 0;
std::string progress = " Counting lines in file ";
for(uint64_t idx = 0; idx < file.size(); ++idx)
{
common::show_progress(idx, file.size(), 16 * 1024 * 1024, progress);
if(file.start()[idx] == '\n')
++num;
}
common::end_progress(progress);
return num;
}
std::string bytes_to_units(double num_bytes)
{
std::string units = "bytes";
for(auto & u: {"KB", "MB", "GB", "TB"})
{
if(num_bytes >= 1024)
{
num_bytes /= 1024;
units = u;
}
}
num_bytes = static_cast<double>(static_cast<int>(num_bytes * 100)) / 100;
return to_string(num_bytes) + " " + units;
}
template <class Duration, class Functor>
Duration time(Functor && functor)
{
auto start = std::chrono::steady_clock::now();
functor();
auto end = std::chrono::steady_clock::now();
return std::chrono::duration_cast<Duration>(end - start);
}
void show_progress(size_t idx, size_t max, size_t freq, const std::string & prefix)
{
if(idx % freq == 0)
{
std::cerr << prefix << static_cast<double>(idx) / max * 100 << "% \r";
std::flush(std::cerr);
}
}
void end_progress(const std::string & prefix)
{
std::cerr << prefix << "100% " << std::endl;
}
template <class Key,
class Value,
class... Args,
template <class, class, class...> class Map>
Value safe_at(const Map<Key, Value, Args...> & map, const Key & key)
{
auto it = map.find(key);
if(it == map.end())
return Value{};
return it->second;
}
template <class Result, class... Args>
std::function<Result(Args...)> memoize(std::function<Result(Args...)> fun)
{
return [fun](Args... args) {
static std::map<std::tuple<Args...>, Result> map_;
auto it = map_.find(std::make_tuple(args...));
if(it != map_.end())
return it->second;
return map_[std::make_tuple(args...)] = fun(args...);
};
}
template <class Key, class Value>
void save_mapping(const util::invertible_map<Key, Value> & map,
const std::string & filename)
{
std::ofstream outfile{filename};
for(auto & p: map)
outfile << p.first << " " << p.second << "\n";
}
template <class T>
void save_mapping(const std::vector<T> & vec, const std::string & filename)
{
std::ofstream outfile{filename};
for(auto & v: vec)
outfile << v << "\n";
}
template <class Key, class Value>
void load_mapping(util::invertible_map<Key, Value> & map,
const std::string & filename)
{
std::ifstream input{filename};
Key k;
Value v;
while((input >> k) && (input >> v))
map.insert(std::make_pair(k, v));
}
template <class T>
void load_mapping(std::vector<T> & vec, const std::string & filename)
{
std::ifstream input{filename};
uint64_t size = common::num_lines(filename);
vec.reserve(size);
T val;
while(input >> val)
vec.push_back(val);
}
template <class T, class... Args>
std::unique_ptr<T> make_unique(Args &&... args)
{
return std::unique_ptr<T>{new T{std::forward<Args>(args)...}};
}
}
}
<|endoftext|>
|
<commit_before>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// 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.
// Internal Includes
#include <osvr/ClientKit/Context.h>
#include <osvr/ClientKit/Interface.h>
#include <osvr/Util/ClientReportTypesC.h>
// Library/third-party includes
// Standard includes
#include <iostream>
#include <string>
void skeletonCallback(void * /*userdata*/, const OSVR_TimeValue * /*timestamp*/,
const OSVR_SkeletonReport *report) {
std::cout << "Got skeleton update callback, for sensor #" << report->sensor
<< std::endl;
}
int main() {
osvr::clientkit::ClientContext context(
"com.osvr.exampleclients.SkeletonCallback");
osvr::clientkit::Interface skeleton =
context.getInterface("/com_osvr_example_Skeleton/Skeleton/skeleton/0");
skeleton.registerCallback(&skeletonCallback, NULL);
// Pretend that this is your application's mainloop.
while (1) {
context.update();
}
std::cout << "Library shut down, exiting." << std::endl;
return 0;
}
<commit_msg>remove empty example<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include "initConfig.h"
#include "libconfig.h++"
#include "getopt.h"
using namespace watcher;
using namespace libconfig;
using namespace std;
bool watcher::initConfig(
libconfig::Config &config,
int argc,
char **argv,
std::string &configFilename,
const char configFileChar,
const char *configFileString)
{
int c;
// int digit_optind = 0;
while (true)
{
// int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
{configFileString, required_argument, 0, configFileChar},
{0, 0, 0, 0}
};
opterr=0; // Don't print message just because we see an option we don't understand.
char args[] = { configFileChar, ':', '\n' };
c = getopt_long(argc, argv, args, long_options, &option_index);
if (c == -1)
break;
if (c==configFileChar)
{
try
{
config.readFile(optarg);
configFilename=optarg;
return true;
}
catch (ParseException &e)
{
// Can't use logging here - if we're reading the config file we probably have not
// init'd the logging mechanism.
cerr << "Error reading configuration file " << optarg << ": " << e.what() << endl;
cerr << "Error: \"" << e.getError() << "\" on line: " << e.getLine() << endl;
}
catch (FileIOException &e)
{
cerr << "Unable to read file " << optarg << " given as configuration file on the command line." << endl;
}
}
// else - ignore things we don't understand
}
return false;
}
<commit_msg>initConfig: If not passed on the command line (-c file), then look for configuration file of the name argv[0].cfg (e.g. "watcherd.cfg") when loading the config file.<commit_after>#include <iostream>
#include "initConfig.h"
#include "libconfig.h++"
#include "getopt.h"
using namespace watcher;
using namespace libconfig;
using namespace std;
static bool readConfig(libconfig::Config &config, const string &filename)
{
try
{
config.readFile(filename.c_str());
return true;
}
catch (ParseException &e)
{
// Can't use logging here - if we're reading the config file we probably have not
// init'd the logging mechanism.
cerr << "Error reading configuration file " << optarg << ": " << e.what() << endl;
cerr << "Error: \"" << e.getError() << "\" on line: " << e.getLine() << endl;
}
catch (FileIOException &e)
{
cerr << "Unable to read file " << optarg << " given as configuration file on the command line." << endl;
}
return false;
}
bool watcher::initConfig(
libconfig::Config &config,
int argc,
char **argv,
std::string &configFilename,
const char configFileChar,
const char *configFileString)
{
int c;
// int digit_optind = 0;
bool retVal=false;
while (true)
{
// int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
{configFileString, required_argument, 0, configFileChar},
{0, 0, 0, 0}
};
opterr=0; // Don't print message just because we see an option we don't understand.
char args[] = { configFileChar, ':', '\n' };
c = getopt_long(argc, argv, args, long_options, &option_index);
if (c == -1)
break;
if (c==configFileChar)
if(true==(retVal=readConfig(config, optarg)))
configFilename=optarg;
// else - ignore things we don't understand
}
// Last ditch: look for a file called `echo argv[0]`.cfg.
if(retVal==false)
{
string fname(argv[0]);
fname+=".cfg";
if(true==(retVal=readConfig(config, fname)))
configFilename=fname;
}
return retVal;
}
<|endoftext|>
|
<commit_before>/**
* @file
* @author Mohammad S. Babaei <info@babaei.net>
* @version 0.1.0
*
* @section LICENSE
*
* (The MIT License)
*
* Copyright (c) 2016 Mohammad S. Babaei
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @section DESCRIPTION
*
* The CMS start page.
*/
#ifndef SERVICE_CMS_HPP
#define SERVICE_CMS_HPP
#include "Page.hpp"
namespace Service {
class Cms;
}
class Service::Cms : public Service::Page
{
private:
struct Impl;
std::unique_ptr<Impl> m_pimpl;
public:
explicit Cms();
virtual ~Cms();
private:
Wt::WWidget *Layout() override;
};
#endif /* SERVICE_CMS_HPP */
<commit_msg>add missing header<commit_after>/**
* @file
* @author Mohammad S. Babaei <info@babaei.net>
* @version 0.1.0
*
* @section LICENSE
*
* (The MIT License)
*
* Copyright (c) 2016 Mohammad S. Babaei
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @section DESCRIPTION
*
* The CMS start page.
*/
#ifndef SERVICE_CMS_HPP
#define SERVICE_CMS_HPP
#include <memory>
#include "Page.hpp"
namespace Service {
class Cms;
}
class Service::Cms : public Service::Page
{
private:
struct Impl;
std::unique_ptr<Impl> m_pimpl;
public:
explicit Cms();
virtual ~Cms();
private:
Wt::WWidget *Layout() override;
};
#endif /* SERVICE_CMS_HPP */
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbMultivariateAlterationDetectorImageFilter.h"
namespace otb
{
namespace Wrapper
{
class MultivariateAlterationDetector: public Application
{
public:
/** Standard class typedefs. */
typedef MultivariateAlterationDetector Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(MultivariateAlterationDetector, otb::Wrapper::Application);
private:
MultivariateAlterationDetector()
{
SetName("MultivariateAlterationDetector");
SetDescription("Multivariate Alteration Detector");
// Documentation
SetDocName("Multivariate alteration detector");
SetDocLongDescription("This application detects change between two given images.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
SetDocCLExample("otbApplicationLauncherCommandLine MultivariateAlterationDetector ${OTB-BIN}/bin "
"--in1 ${OTB-Data}/Input/Spot5-Gloucester-before.tif --in2 ${OTB-Data}/Input/Spot5-Gloucester-after.tif "
"--out detectedChangeImage.tif ");
AddDocTag(Tags::FeatureExtraction);
}
virtual ~MultivariateAlterationDetector()
{
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in1", "Input Image 1");
AddParameter(ParameterType_InputImage, "in2", "Input Image 2");
AddParameter(ParameterType_OutputImage, "out", "Change Map");
SetParameterDescription("out","Image of detected changes.");
AddParameter(ParameterType_RAM, "ram", "Available RAM");
SetDefaultParameterInt("ram", 256);
MandatoryOff("ram");
}
void DoUpdateParameters()
{
}
void DoExecute()
{
typedef otb::MultivariateAlterationDetectorImageFilter<
FloatVectorImageType,
FloatVectorImageType> ChangeFilterType;
ChangeFilterType::Pointer changeFilter = ChangeFilterType::New();
changeFilter->SetInput1(GetParameterImage("in1"));
changeFilter->SetInput2(GetParameterImage("in2"));
m_Ref = changeFilter;
SetParameterOutputImage("out", changeFilter->GetOutput());
}
itk::LightObject::Pointer m_Ref;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::MultivariateAlterationDetector)
<commit_msg>ENH: update docexample to the new framework for ChangeDetection appli<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbMultivariateAlterationDetectorImageFilter.h"
namespace otb
{
namespace Wrapper
{
class MultivariateAlterationDetector: public Application
{
public:
/** Standard class typedefs. */
typedef MultivariateAlterationDetector Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(MultivariateAlterationDetector, otb::Wrapper::Application);
private:
MultivariateAlterationDetector()
{
SetName("MultivariateAlterationDetector");
SetDescription("Multivariate Alteration Detector");
// Documentation
SetDocName("Multivariate alteration detector");
SetDocLongDescription("This application detects change between two given images.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::FeatureExtraction);
}
virtual ~MultivariateAlterationDetector()
{
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in1", "Input Image 1");
AddParameter(ParameterType_InputImage, "in2", "Input Image 2");
AddParameter(ParameterType_OutputImage, "out", "Change Map");
SetParameterDescription("out","Image of detected changes.");
AddParameter(ParameterType_RAM, "ram", "Available RAM");
SetDefaultParameterInt("ram", 256);
MandatoryOff("ram");
// Doc example parameter settings
SetDocExampleParameterValue("in1", "Spot5-Gloucester-before.tif");
SetDocExampleParameterValue("in2", "Spot5-Gloucester-after.tif");
SetDocExampleParameterValue("out", "detectedChangeImage.tif");
}
void DoUpdateParameters()
{
}
void DoExecute()
{
typedef otb::MultivariateAlterationDetectorImageFilter<
FloatVectorImageType,
FloatVectorImageType> ChangeFilterType;
ChangeFilterType::Pointer changeFilter = ChangeFilterType::New();
changeFilter->SetInput1(GetParameterImage("in1"));
changeFilter->SetInput2(GetParameterImage("in2"));
m_Ref = changeFilter;
SetParameterOutputImage("out", changeFilter->GetOutput());
}
itk::LightObject::Pointer m_Ref;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::MultivariateAlterationDetector)
<|endoftext|>
|
<commit_before>#include <thread>
#include <condition_variable>
#include <mutex>
#include <sstream>
#include <lcm/lcm-cpp.hpp>
#include <ConciseArgs>
#include <drc_utils/LcmWrapper.hpp>
#include <drc_utils/BotWrapper.hpp>
#include <bot_lcmgl_client/lcmgl.h>
#include <lcmtypes/drc/map_scans_t.hpp>
#include <lcmtypes/drc/affordance_collection_t.hpp>
#include <lcmtypes/drc/block_fit_request_t.hpp>
#include <maps/ScanBundleView.hpp>
#include <maps/LcmTranslator.hpp>
#include <pcl/common/io.h>
#include <pcl/common/transforms.h>
#include "BlockFitter.hpp"
struct State {
drc::BotWrapper::Ptr mBotWrapper;
drc::LcmWrapper::Ptr mLcmWrapper;
bool mRunContinuously;
bool mDoFilter;
bool mRemoveGround;
bool mGrabExactPoses;
bool mDebug;
Eigen::Vector3f mBlockSize;
int mAlgorithm;
bool mDoTrigger;
std::string mNamePrefix;
bool mTriggered;
drc::map_scans_t mData;
int64_t mLastDataTime;
Eigen::Isometry3f mSensorPose;
Eigen::Isometry3f mGroundPose;
std::thread mWorkerThread;
std::condition_variable mCondition;
std::mutex mProcessMutex;
std::mutex mDataMutex;
State() {
mRunContinuously = false;
mDoFilter = true;
mRemoveGround = true;
mGrabExactPoses = false;
mDebug = false;
mAlgorithm = planeseg::BlockFitter::RectangleFitAlgorithm::MinimumArea;
mBlockSize << 15+3/8.0, 15+5/8.0, 5+5/8.0;
mBlockSize *=0.0254;
mDoTrigger = false;
mNamePrefix = "cinderblock";
mTriggered = true;
}
void start() {
mLastDataTime = 0;
mData.utime = 0;
mLcmWrapper->get()->subscribe("MAP_SCANS", &State::onScans, this);
mWorkerThread = std::thread(std::ref(*this));
mLcmWrapper->startHandleThread(true);
}
void stop() {
mLcmWrapper->stopHandleThread();
if (mWorkerThread.joinable()) mWorkerThread.join();
}
void operator()() {
while (true) {
// wait for data
std::unique_lock<std::mutex> lock(mProcessMutex);
mCondition.wait_for(lock, std::chrono::milliseconds(100));
// grab data
drc::map_scans_t data;
Eigen::Isometry3f sensorPose;
Eigen::Isometry3f groundPose;
{
std::unique_lock<std::mutex> dataLock(mDataMutex);
if (mData.utime == mLastDataTime) continue;
data = mData;
sensorPose = mSensorPose;
groundPose = mGroundPose;
mLastDataTime = mData.utime;
}
// convert scans to point cloud
maps::ScanBundleView view;
maps::LcmTranslator::fromLcm(data, view);
maps::PointCloud rawCloud, curCloud;
std::vector<float> allDeltas;
for (const auto& scan : view.getScans()) {
// compute range deltas
int numRanges = scan->getNumRanges();
std::vector<float> deltas;
const auto& ranges = scan->getRanges();
float prevRange = -1;
int curIndex = 0;
for (int i = 0; i < numRanges; ++i, ++curIndex) {
if (ranges[i] <= 0) continue;
prevRange = ranges[i];
deltas.push_back(0);
break;
}
for (int i = curIndex+1; i < numRanges; ++i) {
float range = ranges[i];
if (range <= 0) continue;
deltas.push_back(range-prevRange);
prevRange = range;
}
// add this scan to cloud
scan->get(curCloud, true);
rawCloud += curCloud;
allDeltas.insert(allDeltas.end(), deltas.begin(), deltas.end());
}
pcl::transformPointCloud
(rawCloud, rawCloud,
Eigen::Affine3f(view.getTransform().matrix()).inverse());
planeseg::LabeledCloud::Ptr cloud(new planeseg::LabeledCloud());
pcl::copyPointCloud(rawCloud, *cloud);
/* TODO: change point type
for (int i = 0; i < (int)cloud->size(); ++i) {
cloud->points[i].label = 1000*allDeltas[i];
}
*/
// remove points outside max radius
const float kValidRadius = 5; // meters; TODO: could make this a param
const float kValidRadius2 = kValidRadius*kValidRadius;
planeseg::LabeledCloud::Ptr tempCloud(new planeseg::LabeledCloud());
for (int i = 0; i < (int)cloud->size(); ++i) {
Eigen::Vector3f p = cloud->points[i].getVector3fMap();
float dist2 = (p-sensorPose.translation()).squaredNorm();
if (dist2 > kValidRadius2) continue;
tempCloud->push_back(cloud->points[i]);
}
std::swap(cloud, tempCloud);
// process
planeseg::BlockFitter fitter;
fitter.setSensorPose(sensorPose.translation(),
sensorPose.rotation().col(2));
fitter.setGroundBand(groundPose.translation()[2]-1.0,
groundPose.translation()[2]+0.5);
if (mDoFilter) fitter.setAreaThresholds(0.8, 1.2);
else fitter.setAreaThresholds(0, 1000);
fitter.setBlockDimensions(mBlockSize);
fitter.setRemoveGround(mRemoveGround);
fitter.setRectangleFitAlgorithm
((planeseg::BlockFitter::RectangleFitAlgorithm)mAlgorithm);
fitter.setDebug(mDebug);
fitter.setCloud(cloud);
auto result = fitter.go();
if (!result.mSuccess) {
std::cout << "error: could not detect blocks" << std::endl;
continue;
}
//
// construct json string
//
// header
std::string json;
json += "{\n";
json += " \"command\": \"echo_response\",\n";
json += " \"descriptions\": {\n";
std::string timeString = std::to_string(mBotWrapper->getCurrentTime());
// blocks
for (int i = 0; i < (int)result.mBlocks.size(); ++i) {
const auto& block = result.mBlocks[i];
std::string dimensionsString, positionString, quaternionString;
{
std::ostringstream oss;
Eigen::Vector3f size = block.mSize;
oss << size[0] << ", " << size[1] << ", " << size[2];
dimensionsString = oss.str();
}
{
std::ostringstream oss;
Eigen::Vector3f p = block.mPose.translation();
oss << p[0] << ", " << p[1] << ", " << p[2];
positionString = oss.str();
}
{
std::ostringstream oss;
Eigen::Quaternionf q(block.mPose.rotation());
oss << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z();
quaternionString = oss.str();
}
std::string uuid = timeString + "_" + std::to_string(i+1);
json += " \"" + uuid + "\": {\n";
json += " \"classname\": \"BoxAffordanceItem\",\n";
json += " \"pose\": [[" + positionString + "], [" +
quaternionString + "]],\n";
json += " \"uuid\": \"" + uuid + "\",\n";
json += " \"Dimensions\": [" + dimensionsString + "],\n";
json += " \"Name\": \"" + mNamePrefix + " " +
std::to_string(i) + "\"\n";
json += " },\n";
}
// ground
{
std::string positionString, quaternionString;
Eigen::Vector3f groundNormal = result.mGroundPlane.head<3>();
{
std::ostringstream oss;
Eigen::Vector3f p = groundPose.translation();
p -= (groundNormal.dot(p)+result.mGroundPlane[3])*groundNormal;
oss << p[0] << ", " << p[1] << ", " << p[2];
positionString = oss.str();
}
{
std::ostringstream oss;
Eigen::Matrix3f rot = Eigen::Matrix3f::Identity();
rot.col(2) = groundNormal.normalized();
rot.col(1) = rot.col(2).cross(Eigen::Vector3f::UnitX()).normalized();
rot.col(0) = rot.col(1).cross(rot.col(2)).normalized();
Eigen::Quaternionf q(rot);
oss << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z();
quaternionString = oss.str();
}
json += " \"ground affordance\": {\n";
json += " \"classname\": \"BoxAffordanceItem\",\n";
json += " \"pose\": [[" + positionString + "], [" +
quaternionString + "]],\n";
json += " \"uuid\": \"ground affordance\",\n";
json += " \"Dimensions\": [15, 15, 0.01],\n";
json += " \"Name\": \"ground affordance\",\n";
json += " \"Visible\": 0\n";
json += " }\n";
}
// footer
json += " },\n";
json += " \"commandId\": \"" + timeString + "\",\n";
json += " \"collectionId\": \"block-fitter\"\n";
json += "}\n";
// publish result
drc::affordance_collection_t msg;
msg.utime = data.utime;
msg.name = json;
msg.naffs = 0;
mLcmWrapper->get()->publish("AFFORDANCE_COLLECTION_COMMAND", &msg);
std::cout << "Published affordance collection" << std::endl;
// publish lcmgl
if (mDebug) {
bot_lcmgl_t* lcmgl;
lcmgl = bot_lcmgl_init(mLcmWrapper->get()->getUnderlyingLCM(),
"block-fitter");
for (const auto& block : result.mBlocks) {
bot_lcmgl_color3f(lcmgl, 1, 0, 0);
bot_lcmgl_line_width(lcmgl, 4);
bot_lcmgl_begin(lcmgl, LCMGL_LINE_LOOP);
for (const auto& pt : block.mHull) {
bot_lcmgl_vertex3f(lcmgl, pt[0], pt[1], pt[2]);
}
bot_lcmgl_end(lcmgl);
}
bot_lcmgl_color3f(lcmgl, 0, 1, 0);
bot_lcmgl_begin(lcmgl, LCMGL_LINE_LOOP);
for (const auto& pt : result.mGroundPolygon) {
bot_lcmgl_vertex3f(lcmgl, pt[0], pt[1], pt[2]);
}
bot_lcmgl_end(lcmgl);
bot_lcmgl_switch_buffer(lcmgl);
bot_lcmgl_destroy(lcmgl);
}
if (!mRunContinuously) break;
}
mLcmWrapper->stopHandleThread();
}
void onScans(const lcm::ReceiveBuffer* iBuf,
const std::string& iChannel,
const drc::map_scans_t* iMessage) {
std::unique_lock<std::mutex> lock(mDataMutex);
if (!mTriggered) return;
mData = *iMessage;
int64_t scanTime = iMessage->utime;
int64_t headPoseTime = mBotWrapper->getLatestTime("head", "local");
int64_t groundPoseTime = mBotWrapper->getLatestTime("ground", "local");
if ((groundPoseTime == 0) || (headPoseTime == 0) ||
(mGrabExactPoses && ((std::abs(headPoseTime-scanTime) > 1e6) ||
(std::abs(groundPoseTime-scanTime) > 1e6)))) {
std::cout << "warning: got scans but no valid pose found" << std::endl;
return;
}
mBotWrapper->getTransform("head", "local", mSensorPose, iMessage->utime);
mBotWrapper->getTransform("ground", "local", mGroundPose, iMessage->utime);
mCondition.notify_one();
if (mDoTrigger) mTriggered = false;
}
void onTrigger(const lcm::ReceiveBuffer* iBuf, const std::string& iChannel,
const drc::block_fit_request_t* iMessage) {
mNamePrefix = iMessage->name_prefix;
mBlockSize << iMessage->dimensions[0], iMessage->dimensions[1],
iMessage->dimensions[2];
mAlgorithm = iMessage->algorithm;
mTriggered = true;
std::cout << "received trigger" << std::endl;
}
};
int main(const int iArgc, const char** iArgv) {
std::string sizeString("");
std::string triggerChannel;
State state;
ConciseArgs opt(iArgc, (char**)iArgv);
opt.add(state.mRunContinuously, "c", "continuous", "run continuously");
opt.add(state.mDoFilter, "f", "filter", "filter blocks based on size");
opt.add(sizeString, "s", "blocksize", "prior size for blocks \"x y z\"");
opt.add(state.mRemoveGround, "g", "remove-ground",
"whether to remove ground before processing");
opt.add(state.mAlgorithm, "a", "algorithm",
"0=min_area, 1=closest_size, 2=closest_hull");
opt.add(state.mGrabExactPoses, "p", "exact-poses",
"wait for synchronized poses");
opt.add(triggerChannel, "t", "trigger-channel",
"perform block fit only when trigger is received");
opt.add(state.mDebug, "d", "debug", "debug flag");
opt.parse();
if (sizeString.length() > 0) {
std::istringstream iss(sizeString);
float x, y, z;
if (iss >> x) {
if (iss >> y) {
if (iss >> z) {
state.mBlockSize << x,y,z;
std::cout << "using block size " << state.mBlockSize.transpose() <<
std::endl;
}
}
}
}
state.mBotWrapper.reset(new drc::BotWrapper());
state.mLcmWrapper.reset(new drc::LcmWrapper(state.mBotWrapper->getLcm()));
if (triggerChannel.length() > 0) {
state.mDoTrigger = true;
state.mTriggered = false;
state.mLcmWrapper->get()->subscribe(triggerChannel,
&State::onTrigger, &state);
}
state.start();
state.stop();
return 1;
}
<commit_msg>always do processing upon new trigger<commit_after>#include <thread>
#include <condition_variable>
#include <mutex>
#include <sstream>
#include <lcm/lcm-cpp.hpp>
#include <ConciseArgs>
#include <drc_utils/LcmWrapper.hpp>
#include <drc_utils/BotWrapper.hpp>
#include <bot_lcmgl_client/lcmgl.h>
#include <lcmtypes/drc/map_scans_t.hpp>
#include <lcmtypes/drc/affordance_collection_t.hpp>
#include <lcmtypes/drc/block_fit_request_t.hpp>
#include <maps/ScanBundleView.hpp>
#include <maps/LcmTranslator.hpp>
#include <pcl/common/io.h>
#include <pcl/common/transforms.h>
#include "BlockFitter.hpp"
struct State {
drc::BotWrapper::Ptr mBotWrapper;
drc::LcmWrapper::Ptr mLcmWrapper;
bool mRunContinuously;
bool mDoFilter;
bool mRemoveGround;
bool mGrabExactPoses;
bool mDebug;
Eigen::Vector3f mBlockSize;
int mAlgorithm;
bool mDoTrigger;
std::string mNamePrefix;
bool mTriggered;
drc::map_scans_t mData;
int64_t mLastDataTime;
Eigen::Isometry3f mSensorPose;
Eigen::Isometry3f mGroundPose;
std::thread mWorkerThread;
std::condition_variable mCondition;
std::mutex mProcessMutex;
std::mutex mDataMutex;
State() {
mRunContinuously = false;
mDoFilter = true;
mRemoveGround = true;
mGrabExactPoses = false;
mDebug = false;
mAlgorithm = planeseg::BlockFitter::RectangleFitAlgorithm::MinimumArea;
mBlockSize << 15+3/8.0, 15+5/8.0, 5+5/8.0;
mBlockSize *=0.0254;
mDoTrigger = false;
mNamePrefix = "cinderblock";
mTriggered = true;
}
void start() {
mLastDataTime = 0;
mData.utime = 0;
mLcmWrapper->get()->subscribe("MAP_SCANS", &State::onScans, this);
mWorkerThread = std::thread(std::ref(*this));
mLcmWrapper->startHandleThread(true);
}
void stop() {
mLcmWrapper->stopHandleThread();
if (mWorkerThread.joinable()) mWorkerThread.join();
}
void operator()() {
while (true) {
// wait for data
std::unique_lock<std::mutex> lock(mProcessMutex);
mCondition.wait_for(lock, std::chrono::milliseconds(100));
// grab data
drc::map_scans_t data;
Eigen::Isometry3f sensorPose;
Eigen::Isometry3f groundPose;
{
std::unique_lock<std::mutex> dataLock(mDataMutex);
if (mData.utime == mLastDataTime) continue;
data = mData;
sensorPose = mSensorPose;
groundPose = mGroundPose;
mLastDataTime = mData.utime;
}
// convert scans to point cloud
maps::ScanBundleView view;
maps::LcmTranslator::fromLcm(data, view);
maps::PointCloud rawCloud, curCloud;
std::vector<float> allDeltas;
for (const auto& scan : view.getScans()) {
// compute range deltas
int numRanges = scan->getNumRanges();
std::vector<float> deltas;
const auto& ranges = scan->getRanges();
float prevRange = -1;
int curIndex = 0;
for (int i = 0; i < numRanges; ++i, ++curIndex) {
if (ranges[i] <= 0) continue;
prevRange = ranges[i];
deltas.push_back(0);
break;
}
for (int i = curIndex+1; i < numRanges; ++i) {
float range = ranges[i];
if (range <= 0) continue;
deltas.push_back(range-prevRange);
prevRange = range;
}
// add this scan to cloud
scan->get(curCloud, true);
rawCloud += curCloud;
allDeltas.insert(allDeltas.end(), deltas.begin(), deltas.end());
}
pcl::transformPointCloud
(rawCloud, rawCloud,
Eigen::Affine3f(view.getTransform().matrix()).inverse());
planeseg::LabeledCloud::Ptr cloud(new planeseg::LabeledCloud());
pcl::copyPointCloud(rawCloud, *cloud);
/* TODO: change point type
for (int i = 0; i < (int)cloud->size(); ++i) {
cloud->points[i].label = 1000*allDeltas[i];
}
*/
// remove points outside max radius
const float kValidRadius = 5; // meters; TODO: could make this a param
const float kValidRadius2 = kValidRadius*kValidRadius;
planeseg::LabeledCloud::Ptr tempCloud(new planeseg::LabeledCloud());
for (int i = 0; i < (int)cloud->size(); ++i) {
Eigen::Vector3f p = cloud->points[i].getVector3fMap();
float dist2 = (p-sensorPose.translation()).squaredNorm();
if (dist2 > kValidRadius2) continue;
tempCloud->push_back(cloud->points[i]);
}
std::swap(cloud, tempCloud);
// process
planeseg::BlockFitter fitter;
fitter.setSensorPose(sensorPose.translation(),
sensorPose.rotation().col(2));
fitter.setGroundBand(groundPose.translation()[2]-1.0,
groundPose.translation()[2]+0.5);
if (mDoFilter) fitter.setAreaThresholds(0.8, 1.2);
else fitter.setAreaThresholds(0, 1000);
fitter.setBlockDimensions(mBlockSize);
fitter.setRemoveGround(mRemoveGround);
fitter.setRectangleFitAlgorithm
((planeseg::BlockFitter::RectangleFitAlgorithm)mAlgorithm);
fitter.setDebug(mDebug);
fitter.setCloud(cloud);
auto result = fitter.go();
if (!result.mSuccess) {
std::cout << "error: could not detect blocks" << std::endl;
continue;
}
//
// construct json string
//
// header
std::string json;
json += "{\n";
json += " \"command\": \"echo_response\",\n";
json += " \"descriptions\": {\n";
std::string timeString = std::to_string(mBotWrapper->getCurrentTime());
// blocks
for (int i = 0; i < (int)result.mBlocks.size(); ++i) {
const auto& block = result.mBlocks[i];
std::string dimensionsString, positionString, quaternionString;
{
std::ostringstream oss;
Eigen::Vector3f size = block.mSize;
oss << size[0] << ", " << size[1] << ", " << size[2];
dimensionsString = oss.str();
}
{
std::ostringstream oss;
Eigen::Vector3f p = block.mPose.translation();
oss << p[0] << ", " << p[1] << ", " << p[2];
positionString = oss.str();
}
{
std::ostringstream oss;
Eigen::Quaternionf q(block.mPose.rotation());
oss << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z();
quaternionString = oss.str();
}
std::string uuid = timeString + "_" + std::to_string(i+1);
json += " \"" + uuid + "\": {\n";
json += " \"classname\": \"BoxAffordanceItem\",\n";
json += " \"pose\": [[" + positionString + "], [" +
quaternionString + "]],\n";
json += " \"uuid\": \"" + uuid + "\",\n";
json += " \"Dimensions\": [" + dimensionsString + "],\n";
json += " \"Name\": \"" + mNamePrefix + " " +
std::to_string(i) + "\"\n";
json += " },\n";
}
// ground
{
std::string positionString, quaternionString;
Eigen::Vector3f groundNormal = result.mGroundPlane.head<3>();
{
std::ostringstream oss;
Eigen::Vector3f p = groundPose.translation();
p -= (groundNormal.dot(p)+result.mGroundPlane[3])*groundNormal;
oss << p[0] << ", " << p[1] << ", " << p[2];
positionString = oss.str();
}
{
std::ostringstream oss;
Eigen::Matrix3f rot = Eigen::Matrix3f::Identity();
rot.col(2) = groundNormal.normalized();
rot.col(1) = rot.col(2).cross(Eigen::Vector3f::UnitX()).normalized();
rot.col(0) = rot.col(1).cross(rot.col(2)).normalized();
Eigen::Quaternionf q(rot);
oss << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z();
quaternionString = oss.str();
}
json += " \"ground affordance\": {\n";
json += " \"classname\": \"BoxAffordanceItem\",\n";
json += " \"pose\": [[" + positionString + "], [" +
quaternionString + "]],\n";
json += " \"uuid\": \"ground affordance\",\n";
json += " \"Dimensions\": [15, 15, 0.01],\n";
json += " \"Name\": \"ground affordance\",\n";
json += " \"Visible\": 0\n";
json += " }\n";
}
// footer
json += " },\n";
json += " \"commandId\": \"" + timeString + "\",\n";
json += " \"collectionId\": \"block-fitter\"\n";
json += "}\n";
// publish result
drc::affordance_collection_t msg;
msg.utime = data.utime;
msg.name = json;
msg.naffs = 0;
mLcmWrapper->get()->publish("AFFORDANCE_COLLECTION_COMMAND", &msg);
std::cout << "Published affordance collection" << std::endl;
// publish lcmgl
if (mDebug) {
bot_lcmgl_t* lcmgl;
lcmgl = bot_lcmgl_init(mLcmWrapper->get()->getUnderlyingLCM(),
"block-fitter");
for (const auto& block : result.mBlocks) {
bot_lcmgl_color3f(lcmgl, 1, 0, 0);
bot_lcmgl_line_width(lcmgl, 4);
bot_lcmgl_begin(lcmgl, LCMGL_LINE_LOOP);
for (const auto& pt : block.mHull) {
bot_lcmgl_vertex3f(lcmgl, pt[0], pt[1], pt[2]);
}
bot_lcmgl_end(lcmgl);
}
bot_lcmgl_color3f(lcmgl, 0, 1, 0);
bot_lcmgl_begin(lcmgl, LCMGL_LINE_LOOP);
for (const auto& pt : result.mGroundPolygon) {
bot_lcmgl_vertex3f(lcmgl, pt[0], pt[1], pt[2]);
}
bot_lcmgl_end(lcmgl);
bot_lcmgl_switch_buffer(lcmgl);
bot_lcmgl_destroy(lcmgl);
}
if (!mRunContinuously) break;
}
mLcmWrapper->stopHandleThread();
}
void onScans(const lcm::ReceiveBuffer* iBuf,
const std::string& iChannel,
const drc::map_scans_t* iMessage) {
std::unique_lock<std::mutex> lock(mDataMutex);
if (!mTriggered) return;
mData = *iMessage;
int64_t scanTime = iMessage->utime;
int64_t headPoseTime = mBotWrapper->getLatestTime("head", "local");
int64_t groundPoseTime = mBotWrapper->getLatestTime("ground", "local");
if ((groundPoseTime == 0) || (headPoseTime == 0) ||
(mGrabExactPoses && ((std::abs(headPoseTime-scanTime) > 1e6) ||
(std::abs(groundPoseTime-scanTime) > 1e6)))) {
std::cout << "warning: got scans but no valid pose found" << std::endl;
return;
}
mBotWrapper->getTransform("head", "local", mSensorPose, iMessage->utime);
mBotWrapper->getTransform("ground", "local", mGroundPose, iMessage->utime);
mCondition.notify_one();
if (mDoTrigger) mTriggered = false;
}
void onTrigger(const lcm::ReceiveBuffer* iBuf, const std::string& iChannel,
const drc::block_fit_request_t* iMessage) {
mNamePrefix = iMessage->name_prefix;
mBlockSize << iMessage->dimensions[0], iMessage->dimensions[1],
iMessage->dimensions[2];
mAlgorithm = iMessage->algorithm;
mLastDataTime = 0; // force processing of new data
mTriggered = true;
std::cout << "received trigger" << std::endl;
}
};
int main(const int iArgc, const char** iArgv) {
std::string sizeString("");
std::string triggerChannel;
State state;
ConciseArgs opt(iArgc, (char**)iArgv);
opt.add(state.mRunContinuously, "c", "continuous", "run continuously");
opt.add(state.mDoFilter, "f", "filter", "filter blocks based on size");
opt.add(sizeString, "s", "blocksize", "prior size for blocks \"x y z\"");
opt.add(state.mRemoveGround, "g", "remove-ground",
"whether to remove ground before processing");
opt.add(state.mAlgorithm, "a", "algorithm",
"0=min_area, 1=closest_size, 2=closest_hull");
opt.add(state.mGrabExactPoses, "p", "exact-poses",
"wait for synchronized poses");
opt.add(triggerChannel, "t", "trigger-channel",
"perform block fit only when trigger is received");
opt.add(state.mDebug, "d", "debug", "debug flag");
opt.parse();
if (sizeString.length() > 0) {
std::istringstream iss(sizeString);
float x, y, z;
if (iss >> x) {
if (iss >> y) {
if (iss >> z) {
state.mBlockSize << x,y,z;
std::cout << "using block size " << state.mBlockSize.transpose() <<
std::endl;
}
}
}
}
state.mBotWrapper.reset(new drc::BotWrapper());
state.mLcmWrapper.reset(new drc::LcmWrapper(state.mBotWrapper->getLcm()));
if (triggerChannel.length() > 0) {
state.mDoTrigger = true;
state.mTriggered = false;
state.mLcmWrapper->get()->subscribe(triggerChannel,
&State::onTrigger, &state);
}
state.start();
state.stop();
return 1;
}
<|endoftext|>
|
<commit_before>/*
* GLRenderSystem_Buffers.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "GLRenderSystem.h"
#include "../CheckedCast.h"
#include "../../Core/Helper.h"
#include "GLTypes.h"
#include "Buffer/GLVertexBuffer.h"
#include "Buffer/GLIndexBuffer.h"
#include "Buffer/GLVertexBufferArray.h"
namespace LLGL
{
/* ----- Buffers ------ */
static GLenum GetGLBufferUsage(long flags)
{
return ((flags & BufferFlags::DynamicUsage) != 0 ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
}
Buffer* GLRenderSystem::CreateBuffer(const BufferDescriptor& desc, const void* initialData)
{
/* Create either base of sub-class GLBuffer object */
switch (desc.type)
{
case BufferType::Vertex:
{
/* Create vertex buffer and build vertex array */
auto bufferGL = MakeUnique<GLVertexBuffer>();
{
GLStateManager::active->BindBuffer(*bufferGL);
bufferGL->BufferData(initialData, desc.size, GetGLBufferUsage(desc.flags));
bufferGL->BuildVertexArray(desc.vertexBuffer.format);
}
return TakeOwnership(buffers_, std::move(bufferGL));
}
break;
case BufferType::Index:
{
/* Create index buffer and store index format */
auto bufferGL = MakeUnique<GLIndexBuffer>(desc.indexBuffer.format);
{
GLStateManager::active->BindBuffer(*bufferGL);
bufferGL->BufferData(initialData, desc.size, GetGLBufferUsage(desc.flags));
}
return TakeOwnership(buffers_, std::move(bufferGL));
}
break;
default:
{
/* Create generic buffer */
auto bufferGL = MakeUnique<GLBuffer>(desc.type);
{
GLStateManager::active->BindBuffer(*bufferGL);
bufferGL->BufferData(initialData, desc.size, GetGLBufferUsage(desc.flags));
}
return TakeOwnership(buffers_, std::move(bufferGL));
}
}
}
BufferArray* GLRenderSystem::CreateBufferArray(unsigned int numBuffers, Buffer* const * bufferArray)
{
AssertCreateBufferArray(numBuffers, bufferArray);
auto type = (*bufferArray)->GetType();
if (type == BufferType::Vertex)
{
/* Create vertex buffer array and build VAO */
auto vertexBufferArray = MakeUnique<GLVertexBufferArray>();
vertexBufferArray->BuildVertexArray(numBuffers, bufferArray);
return TakeOwnership(bufferArrays_, std::move(vertexBufferArray));
}
return TakeOwnership(bufferArrays_, MakeUnique<GLBufferArray>(type, numBuffers, bufferArray));
}
void GLRenderSystem::Release(Buffer& buffer)
{
RemoveFromUniqueSet(buffers_, &buffer);
}
void GLRenderSystem::Release(BufferArray& bufferArray)
{
RemoveFromUniqueSet(bufferArrays_, &bufferArray);
}
void GLRenderSystem::WriteBuffer(Buffer& buffer, const void* data, std::size_t dataSize, std::size_t offset)
{
/* Bind and update buffer sub-data */
auto& bufferGL = LLGL_CAST(GLBuffer&, buffer);
GLStateManager::active->BindBuffer(bufferGL);
bufferGL.BufferSubData(data, dataSize, static_cast<GLintptr>(offset));
}
void* GLRenderSystem::MapBuffer(Buffer& buffer, const BufferCPUAccess access)
{
/* Get, bind, and map buffer */
auto& bufferGL = LLGL_CAST(GLBuffer&, buffer);
GLStateManager::active->BindBuffer(bufferGL);
return bufferGL.MapBuffer(GLTypes::Map(access));
}
void GLRenderSystem::UnmapBuffer(Buffer& buffer)
{
/* Get, bind, and unmap buffer */
auto& bufferGL = LLGL_CAST(GLBuffer&, buffer);
GLStateManager::active->BindBuffer(bufferGL);
bufferGL.UnmapBuffer();
}
} // /namespace LLGL
// ================================================================================
<commit_msg>Simplified "Write/Map/UnmapBuffer" functions in GL renderer.<commit_after>/*
* GLRenderSystem_Buffers.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "GLRenderSystem.h"
#include "../CheckedCast.h"
#include "../../Core/Helper.h"
#include "GLTypes.h"
#include "Buffer/GLVertexBuffer.h"
#include "Buffer/GLIndexBuffer.h"
#include "Buffer/GLVertexBufferArray.h"
namespace LLGL
{
/* ----- Buffers ------ */
static GLenum GetGLBufferUsage(long flags)
{
return ((flags & BufferFlags::DynamicUsage) != 0 ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
}
Buffer* GLRenderSystem::CreateBuffer(const BufferDescriptor& desc, const void* initialData)
{
/* Create either base of sub-class GLBuffer object */
switch (desc.type)
{
case BufferType::Vertex:
{
/* Create vertex buffer and build vertex array */
auto bufferGL = MakeUnique<GLVertexBuffer>();
{
GLStateManager::active->BindBuffer(*bufferGL);
bufferGL->BufferData(initialData, desc.size, GetGLBufferUsage(desc.flags));
bufferGL->BuildVertexArray(desc.vertexBuffer.format);
}
return TakeOwnership(buffers_, std::move(bufferGL));
}
break;
case BufferType::Index:
{
/* Create index buffer and store index format */
auto bufferGL = MakeUnique<GLIndexBuffer>(desc.indexBuffer.format);
{
GLStateManager::active->BindBuffer(*bufferGL);
bufferGL->BufferData(initialData, desc.size, GetGLBufferUsage(desc.flags));
}
return TakeOwnership(buffers_, std::move(bufferGL));
}
break;
default:
{
/* Create generic buffer */
auto bufferGL = MakeUnique<GLBuffer>(desc.type);
{
GLStateManager::active->BindBuffer(*bufferGL);
bufferGL->BufferData(initialData, desc.size, GetGLBufferUsage(desc.flags));
}
return TakeOwnership(buffers_, std::move(bufferGL));
}
}
}
BufferArray* GLRenderSystem::CreateBufferArray(unsigned int numBuffers, Buffer* const * bufferArray)
{
AssertCreateBufferArray(numBuffers, bufferArray);
auto type = (*bufferArray)->GetType();
if (type == BufferType::Vertex)
{
/* Create vertex buffer array and build VAO */
auto vertexBufferArray = MakeUnique<GLVertexBufferArray>();
vertexBufferArray->BuildVertexArray(numBuffers, bufferArray);
return TakeOwnership(bufferArrays_, std::move(vertexBufferArray));
}
return TakeOwnership(bufferArrays_, MakeUnique<GLBufferArray>(type, numBuffers, bufferArray));
}
void GLRenderSystem::Release(Buffer& buffer)
{
RemoveFromUniqueSet(buffers_, &buffer);
}
void GLRenderSystem::Release(BufferArray& bufferArray)
{
RemoveFromUniqueSet(bufferArrays_, &bufferArray);
}
static GLBuffer& BindAndGetGLBuffer(Buffer& buffer)
{
auto& bufferGL = LLGL_CAST(GLBuffer&, buffer);
GLStateManager::active->BindBuffer(bufferGL);
return bufferGL;
}
void GLRenderSystem::WriteBuffer(Buffer& buffer, const void* data, std::size_t dataSize, std::size_t offset)
{
/* Bind and update buffer sub-data */
BindAndGetGLBuffer(buffer).BufferSubData(data, dataSize, static_cast<GLintptr>(offset));
}
void* GLRenderSystem::MapBuffer(Buffer& buffer, const BufferCPUAccess access)
{
/* Bind and map buffer */
return BindAndGetGLBuffer(buffer).MapBuffer(GLTypes::Map(access));
}
void GLRenderSystem::UnmapBuffer(Buffer& buffer)
{
/* Bind and unmap buffer */
BindAndGetGLBuffer(buffer).UnmapBuffer();
}
} // /namespace LLGL
// ================================================================================
<|endoftext|>
|
<commit_before>125ee1d0-2e4f-11e5-9284-b827eb9e62be<commit_msg>1263d578-2e4f-11e5-9284-b827eb9e62be<commit_after>1263d578-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d76eb4ac-2e4d-11e5-9284-b827eb9e62be<commit_msg>d773ad18-2e4d-11e5-9284-b827eb9e62be<commit_after>d773ad18-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1e39df52-2e4d-11e5-9284-b827eb9e62be<commit_msg>1e5617e4-2e4d-11e5-9284-b827eb9e62be<commit_after>1e5617e4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>217ce856-2e4f-11e5-9284-b827eb9e62be<commit_msg>2181e4aa-2e4f-11e5-9284-b827eb9e62be<commit_after>2181e4aa-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>a6f1b05e-2e4d-11e5-9284-b827eb9e62be<commit_msg>a6f6a546-2e4d-11e5-9284-b827eb9e62be<commit_after>a6f6a546-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>7b81809c-2e4e-11e5-9284-b827eb9e62be<commit_msg>7b8690e6-2e4e-11e5-9284-b827eb9e62be<commit_after>7b8690e6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>67d6edda-2e4d-11e5-9284-b827eb9e62be<commit_msg>67dc18a0-2e4d-11e5-9284-b827eb9e62be<commit_after>67dc18a0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1a6f2164-2e4f-11e5-9284-b827eb9e62be<commit_msg>1a741b06-2e4f-11e5-9284-b827eb9e62be<commit_after>1a741b06-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>a275efb2-2e4e-11e5-9284-b827eb9e62be<commit_msg>a27b0218-2e4e-11e5-9284-b827eb9e62be<commit_after>a27b0218-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>68f20bd6-2e4e-11e5-9284-b827eb9e62be<commit_msg>68f70708-2e4e-11e5-9284-b827eb9e62be<commit_after>68f70708-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>533fd0ee-2e4d-11e5-9284-b827eb9e62be<commit_msg>5344c82e-2e4d-11e5-9284-b827eb9e62be<commit_after>5344c82e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>31899c1c-2e4f-11e5-9284-b827eb9e62be<commit_msg>318e8966-2e4f-11e5-9284-b827eb9e62be<commit_after>318e8966-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>14a2bd68-2e4f-11e5-9284-b827eb9e62be<commit_msg>14a7cfe2-2e4f-11e5-9284-b827eb9e62be<commit_after>14a7cfe2-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>372270d2-2e4e-11e5-9284-b827eb9e62be<commit_msg>372772a8-2e4e-11e5-9284-b827eb9e62be<commit_after>372772a8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>7858577e-2e4e-11e5-9284-b827eb9e62be<commit_msg>785d5ca6-2e4e-11e5-9284-b827eb9e62be<commit_after>785d5ca6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1c14f03e-2e4f-11e5-9284-b827eb9e62be<commit_msg>1c1a03b2-2e4f-11e5-9284-b827eb9e62be<commit_after>1c1a03b2-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>639efc6c-2e4d-11e5-9284-b827eb9e62be<commit_msg>63a411fc-2e4d-11e5-9284-b827eb9e62be<commit_after>63a411fc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f3fd1220-2e4e-11e5-9284-b827eb9e62be<commit_msg>f40211bc-2e4e-11e5-9284-b827eb9e62be<commit_after>f40211bc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>9549db96-2e4e-11e5-9284-b827eb9e62be<commit_msg>954ed66e-2e4e-11e5-9284-b827eb9e62be<commit_after>954ed66e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>6756cf8c-2e4e-11e5-9284-b827eb9e62be<commit_msg>675bc2d0-2e4e-11e5-9284-b827eb9e62be<commit_after>675bc2d0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>53628ff8-2e4d-11e5-9284-b827eb9e62be<commit_msg>536783e6-2e4d-11e5-9284-b827eb9e62be<commit_after>536783e6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>31dade16-2e4e-11e5-9284-b827eb9e62be<commit_msg>31dfd39e-2e4e-11e5-9284-b827eb9e62be<commit_after>31dfd39e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>dca5c414-2e4e-11e5-9284-b827eb9e62be<commit_msg>dcaaca0e-2e4e-11e5-9284-b827eb9e62be<commit_after>dcaaca0e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d4f9c36e-2e4e-11e5-9284-b827eb9e62be<commit_msg>d4fec22e-2e4e-11e5-9284-b827eb9e62be<commit_after>d4fec22e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b8f131f4-2e4c-11e5-9284-b827eb9e62be<commit_msg>b8f642ca-2e4c-11e5-9284-b827eb9e62be<commit_after>b8f642ca-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>30299f4a-2e4d-11e5-9284-b827eb9e62be<commit_msg>302e9c52-2e4d-11e5-9284-b827eb9e62be<commit_after>302e9c52-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c6b8ef8e-2e4c-11e5-9284-b827eb9e62be<commit_msg>c6bde53e-2e4c-11e5-9284-b827eb9e62be<commit_after>c6bde53e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>def0ae38-2e4d-11e5-9284-b827eb9e62be<commit_msg>def5b770-2e4d-11e5-9284-b827eb9e62be<commit_after>def5b770-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>2c51b074-2e4d-11e5-9284-b827eb9e62be<commit_msg>2c56c578-2e4d-11e5-9284-b827eb9e62be<commit_after>2c56c578-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>408cb8fe-2e4d-11e5-9284-b827eb9e62be<commit_msg>4091c362-2e4d-11e5-9284-b827eb9e62be<commit_after>4091c362-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b7f02674-2e4d-11e5-9284-b827eb9e62be<commit_msg>b7f520d4-2e4d-11e5-9284-b827eb9e62be<commit_after>b7f520d4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>53e39c1e-2e4e-11e5-9284-b827eb9e62be<commit_msg>53e8f380-2e4e-11e5-9284-b827eb9e62be<commit_after>53e8f380-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>00d6627c-2e4e-11e5-9284-b827eb9e62be<commit_msg>00dd3aac-2e4e-11e5-9284-b827eb9e62be<commit_after>00dd3aac-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>8e5c328a-2e4d-11e5-9284-b827eb9e62be<commit_msg>8e614036-2e4d-11e5-9284-b827eb9e62be<commit_after>8e614036-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1fab681e-2e4e-11e5-9284-b827eb9e62be<commit_msg>1fb071ec-2e4e-11e5-9284-b827eb9e62be<commit_after>1fb071ec-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>8ca93fcc-2e4e-11e5-9284-b827eb9e62be<commit_msg>8cae50ac-2e4e-11e5-9284-b827eb9e62be<commit_after>8cae50ac-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b526e94c-2e4c-11e5-9284-b827eb9e62be<commit_msg>b52bfe0a-2e4c-11e5-9284-b827eb9e62be<commit_after>b52bfe0a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f79efeea-2e4c-11e5-9284-b827eb9e62be<commit_msg>f7a56262-2e4c-11e5-9284-b827eb9e62be<commit_after>f7a56262-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>062d63e8-2e4d-11e5-9284-b827eb9e62be<commit_msg>06328134-2e4d-11e5-9284-b827eb9e62be<commit_after>06328134-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>04082d78-2e4d-11e5-9284-b827eb9e62be<commit_msg>040d3dea-2e4d-11e5-9284-b827eb9e62be<commit_after>040d3dea-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b0bee94e-2e4d-11e5-9284-b827eb9e62be<commit_msg>b0c3e30e-2e4d-11e5-9284-b827eb9e62be<commit_after>b0c3e30e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>7804fa1c-2e4d-11e5-9284-b827eb9e62be<commit_msg>7809ebbc-2e4d-11e5-9284-b827eb9e62be<commit_after>7809ebbc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>28e68512-2e4e-11e5-9284-b827eb9e62be<commit_msg>28eb98ea-2e4e-11e5-9284-b827eb9e62be<commit_after>28eb98ea-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e9e05e6a-2e4d-11e5-9284-b827eb9e62be<commit_msg>e9e557ee-2e4d-11e5-9284-b827eb9e62be<commit_after>e9e557ee-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b38e5e88-2e4e-11e5-9284-b827eb9e62be<commit_msg>b3935b04-2e4e-11e5-9284-b827eb9e62be<commit_after>b3935b04-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0e10f4bc-2e4d-11e5-9284-b827eb9e62be<commit_msg>0e15e9c2-2e4d-11e5-9284-b827eb9e62be<commit_after>0e15e9c2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3ef35ad8-2e4e-11e5-9284-b827eb9e62be<commit_msg>3ef87608-2e4e-11e5-9284-b827eb9e62be<commit_after>3ef87608-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>aea40c88-2e4e-11e5-9284-b827eb9e62be<commit_msg>aea9038c-2e4e-11e5-9284-b827eb9e62be<commit_after>aea9038c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>446e29e4-2e4d-11e5-9284-b827eb9e62be<commit_msg>447334f2-2e4d-11e5-9284-b827eb9e62be<commit_after>447334f2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>826616e8-2e4e-11e5-9284-b827eb9e62be<commit_msg>826b1e5e-2e4e-11e5-9284-b827eb9e62be<commit_after>826b1e5e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>ca6c0412-2e4d-11e5-9284-b827eb9e62be<commit_msg>ca70f422-2e4d-11e5-9284-b827eb9e62be<commit_after>ca70f422-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>9993445e-2e4d-11e5-9284-b827eb9e62be<commit_msg>999839f0-2e4d-11e5-9284-b827eb9e62be<commit_after>999839f0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3489b476-2e4d-11e5-9284-b827eb9e62be<commit_msg>348f42c4-2e4d-11e5-9284-b827eb9e62be<commit_after>348f42c4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d38a9990-2e4e-11e5-9284-b827eb9e62be<commit_msg>d38f8fc2-2e4e-11e5-9284-b827eb9e62be<commit_after>d38f8fc2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>6e3f7e5c-2e4e-11e5-9284-b827eb9e62be<commit_msg>6e447b28-2e4e-11e5-9284-b827eb9e62be<commit_after>6e447b28-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f98d054e-2e4c-11e5-9284-b827eb9e62be<commit_msg>f991f8e2-2e4c-11e5-9284-b827eb9e62be<commit_after>f991f8e2-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>8e11393c-2e4e-11e5-9284-b827eb9e62be<commit_msg>8e16570a-2e4e-11e5-9284-b827eb9e62be<commit_after>8e16570a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f8fb5f7a-2e4e-11e5-9284-b827eb9e62be<commit_msg>f9175a40-2e4e-11e5-9284-b827eb9e62be<commit_after>f9175a40-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>2f7c582a-2e4e-11e5-9284-b827eb9e62be<commit_msg>2f817666-2e4e-11e5-9284-b827eb9e62be<commit_after>2f817666-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1d1bfc58-2e4e-11e5-9284-b827eb9e62be<commit_msg>1d21117a-2e4e-11e5-9284-b827eb9e62be<commit_after>1d21117a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3f2b6b4e-2e4e-11e5-9284-b827eb9e62be<commit_msg>3f306e14-2e4e-11e5-9284-b827eb9e62be<commit_after>3f306e14-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>21c7a612-2e4e-11e5-9284-b827eb9e62be<commit_msg>21ccafa4-2e4e-11e5-9284-b827eb9e62be<commit_after>21ccafa4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d45a37fa-2e4d-11e5-9284-b827eb9e62be<commit_msg>d45f2814-2e4d-11e5-9284-b827eb9e62be<commit_after>d45f2814-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>fc6674ee-2e4c-11e5-9284-b827eb9e62be<commit_msg>fc6b7606-2e4c-11e5-9284-b827eb9e62be<commit_after>fc6b7606-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c5c75d4a-2e4c-11e5-9284-b827eb9e62be<commit_msg>c5cc49f4-2e4c-11e5-9284-b827eb9e62be<commit_after>c5cc49f4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>528c598c-2e4e-11e5-9284-b827eb9e62be<commit_msg>52918010-2e4e-11e5-9284-b827eb9e62be<commit_after>52918010-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>032866dc-2e4f-11e5-9284-b827eb9e62be<commit_msg>032d6204-2e4f-11e5-9284-b827eb9e62be<commit_after>032d6204-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>35b0c564-2e4e-11e5-9284-b827eb9e62be<commit_msg>35b5d0c2-2e4e-11e5-9284-b827eb9e62be<commit_after>35b5d0c2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f974295c-2e4c-11e5-9284-b827eb9e62be<commit_msg>f9792240-2e4c-11e5-9284-b827eb9e62be<commit_after>f9792240-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b8d3322e-2e4e-11e5-9284-b827eb9e62be<commit_msg>b8d8450c-2e4e-11e5-9284-b827eb9e62be<commit_after>b8d8450c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>786cf4b8-2e4e-11e5-9284-b827eb9e62be<commit_msg>7871fc92-2e4e-11e5-9284-b827eb9e62be<commit_after>7871fc92-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d6cb5022-2e4e-11e5-9284-b827eb9e62be<commit_msg>d6d04c9e-2e4e-11e5-9284-b827eb9e62be<commit_after>d6d04c9e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>756dd2be-2e4e-11e5-9284-b827eb9e62be<commit_msg>7572dbd8-2e4e-11e5-9284-b827eb9e62be<commit_after>7572dbd8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>2f14984c-2e4f-11e5-9284-b827eb9e62be<commit_msg>2f199978-2e4f-11e5-9284-b827eb9e62be<commit_after>2f199978-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>48d59bc0-2e4d-11e5-9284-b827eb9e62be<commit_msg>48dabd62-2e4d-11e5-9284-b827eb9e62be<commit_after>48dabd62-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d2acfc0e-2e4c-11e5-9284-b827eb9e62be<commit_msg>d2b214f0-2e4c-11e5-9284-b827eb9e62be<commit_after>d2b214f0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b37a3cfa-2e4e-11e5-9284-b827eb9e62be<commit_msg>b37f3aa2-2e4e-11e5-9284-b827eb9e62be<commit_after>b37f3aa2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f7beff42-2e4c-11e5-9284-b827eb9e62be<commit_msg>f7c4085c-2e4c-11e5-9284-b827eb9e62be<commit_after>f7c4085c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>fcd2e654-2e4e-11e5-9284-b827eb9e62be<commit_msg>fcd7dea2-2e4e-11e5-9284-b827eb9e62be<commit_after>fcd7dea2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>36dc5e26-2e4e-11e5-9284-b827eb9e62be<commit_msg>36e154e4-2e4e-11e5-9284-b827eb9e62be<commit_after>36e154e4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f30b3564-2e4d-11e5-9284-b827eb9e62be<commit_msg>f3104752-2e4d-11e5-9284-b827eb9e62be<commit_after>f3104752-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d9952126-2e4d-11e5-9284-b827eb9e62be<commit_msg>d99a192e-2e4d-11e5-9284-b827eb9e62be<commit_after>d99a192e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>528d3cc2-2e4d-11e5-9284-b827eb9e62be<commit_msg>52924fb4-2e4d-11e5-9284-b827eb9e62be<commit_after>52924fb4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>fd56cc6e-2e4c-11e5-9284-b827eb9e62be<commit_msg>fd5bc124-2e4c-11e5-9284-b827eb9e62be<commit_after>fd5bc124-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.