<commit_before>
#pragma once

#include <math.h>
#include <sys/time.h>
#include <stdint.h>
#include <deque>
#include <vector>
#include <stdexcept>
#include <typeinfo>
#include <QString>
#include "Geometry2d/Point.hpp"
#include "Constants.hpp"
#include "time.hpp"
//#include <iostream>
#include <math.h>
using namespace std;

/**
 * @brief Restricts the given angle to be between pi and -pi
 *
 * @param a An angle in radians
 * @return An equivalent angle in radians restricted to [-pi, pi]
 */
static inline float fixAngleRadians(float a)
{
	a= remainder(a, 2*M_PI);
	//cout<<"angle "<<a<<endl;
	while (a < -M_PI) a += 2.0*M_PI;

	while (a > M_PI) a -= 2.0*M_PI;
	return a;
}

/** Checks whether or not the given ball is in the defense area. */
static inline bool ballIsInGoalieBox(Geometry2d::Point point) {
	if (abs(point.x) < Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f) // Ball is in center (rectangular) portion of defensive bubble
	{
		if (point.y > 0 && point.y < Field_Dimensions::Current_Dimensions.ArcRadius()) {
			return true;
		} else {
			return false;
		}
	} else if (abs(point.x) < (Field_Dimensions::Current_Dimensions.ArcRadius() + Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f)) // Ball is in one of the side (arc) portions of defensive bubble
	{
		double adjusted_x = abs(point.x) - (Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f);
		double max_y = sqrt( (Field_Dimensions::Current_Dimensions.ArcRadius() * Field_Dimensions::Current_Dimensions.ArcRadius()) - (adjusted_x * adjusted_x));
		if (point.y > 0 && point.y <= max_y) {
			return true;
		} else {
			return false;
		}
	}
	return false;
}

static Geometry2d::Point fromOursToTheirs(Geometry2d::Point &pt) {
	Geometry2d::Point c;
	c.y = Field_Dimensions::Current_Dimensions.Length() - pt.y;
	c.x = -pt.x;

	return c;
}

static bool ballIsInTheirGoalieBox(Geometry2d::Point &pt) {
	Geometry2d::Point converted = fromOursToTheirs(pt);
	return ballIsInGoalieBox(converted);
}

/** Handles saturation of a bounded value */
template<class T>
float clamp(T value, T min, T max)
{
	if (value > max)
	{
		return max;
	}
	else if (value < min)
	{
		return min;
	}
	return value;
}

// Removes all entries in a std::map which associate to the given value.
template<class Map_Type, class Data_Type>
void map_remove(Map_Type &map, Data_Type &value)
{
	typename Map_Type::iterator i = map.begin();
	while (i != map.end())
	{
		typename Map_Type::iterator next = i;
		++next;

		if (i->second == value)
		{
			map.erase(i);
		}

		i = next;
	}
}

// If <key> exists in <map>, returns map[key].
// If not, returns 0.
template<typename Map>
typename Map::mapped_type map_lookup(const Map &map, typename Map::key_type key)
{
	typename Map::const_iterator i = map.find(key);
	if (i != map.end())
	{
		return i->second;
	} else {
		return 0;
	}
}

/**
 * A basic FIR filter of variable type with float coeffs
 *
 * Note, coefficients will be normalized so that inputs
 * will always be scaled appropriately
 */
template<typename T>
class FIRFilter {
public:
	typedef std::vector<float> Coeffs;

	FIRFilter(const T& zero, size_t nrTaps) : _zero(zero) {
		if (nrTaps == 0)
			throw std::invalid_argument("FIR Filter: number of taps must be greater than zero");

		// initialize
		_taps.assign(nrTaps, _zero);
		_coeffs.assign(nrTaps, 0.0f);
		_coeffs[0] = 1.0;
	}

	T filter(const T& x) {
		_taps.push_front(x);
		_taps.pop_back();

		T y = _zero;
		for (size_t i = 0; i<_taps.size(); ++i)
			y += _taps.at(i) * _coeffs.at(i);

		return y;
	}

	/** reinitializes the coeffs and taps to new values */
	void setCoeffs(const Coeffs& coeffs) {
		size_t nrTaps = coeffs.size();
		if (nrTaps == 0)
			throw std::invalid_argument("FIR Filter: number of coeffs must be greater than zero");

		_taps.assign(nrTaps, _zero);
		_coeffs.assign(nrTaps, 0.0);

		// find the normalizer
		float normalizer = 0.0;
		for (size_t i = 0; i<coeffs.size(); ++i)
			normalizer += coeffs.at(i);

		// set the normalized coefficients
		for (size_t i=0; i<coeffs.size(); ++i)
			_coeffs[i] = coeffs.at(i) / normalizer;
	}

protected:
	T _zero;
	std::deque<T> _taps;
	Coeffs _coeffs;
};

// An output iterator which throws an exception when it's used.
// This is used for example to determine if the output of set_difference would be non-empty without
// calculating all of it.
template<typename T>
class ExceptionIterator: public std::iterator<std::output_iterator_tag, void, void, void, void>
{
public:
	ExceptionIterator &operator=(const T &value)
	{
		throw std::exception();
	}

	ExceptionIterator &operator*()
	{
		return *this;
	}

	ExceptionIterator &operator++()
	{
		return *this;
	}

	ExceptionIterator &operator++(int)
	{
		return *this;
	}
};

// Sets str to the name of a class.
// Use it like this:
//		Object *obj = new Object();
//		QString name = typeName(typeid(*obj));
// The returned name is in the usual C++ format: "Namespace::Namespace::Class"
QString typeName(const std::type_info &info);

// Like typeName, but only returns the final class name part.
QString className(const std::type_info &info);
<commit_msg>removed `using namespace std;` from headers<commit_after>
#pragma once

#include <math.h>
#include <sys/time.h>
#include <stdint.h>
#include <deque>
#include <vector>
#include <stdexcept>
#include <typeinfo>
#include <QString>
#include "Geometry2d/Point.hpp"
#include "Constants.hpp"
#include "time.hpp"
#include <math.h>

/**
 * @brief Restricts the given angle to be between pi and -pi
 *
 * @param a An angle in radians
 * @return An equivalent angle in radians restricted to [-pi, pi]
 */
static inline float fixAngleRadians(float a)
{
	a= remainder(a, 2*M_PI);
	//cout<<"angle "<<a<<endl;
	while (a < -M_PI) a += 2.0*M_PI;

	while (a > M_PI) a -= 2.0*M_PI;
	return a;
}

/** Checks whether or not the given ball is in the defense area. */
static inline bool ballIsInGoalieBox(Geometry2d::Point point) {
	if (abs(point.x) < Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f) // Ball is in center (rectangular) portion of defensive bubble
	{
		if (point.y > 0 && point.y < Field_Dimensions::Current_Dimensions.ArcRadius()) {
			return true;
		} else {
			return false;
		}
	} else if (abs(point.x) < (Field_Dimensions::Current_Dimensions.ArcRadius() + Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f)) // Ball is in one of the side (arc) portions of defensive bubble
	{
		double adjusted_x = abs(point.x) - (Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f);
		double max_y = sqrt( (Field_Dimensions::Current_Dimensions.ArcRadius() * Field_Dimensions::Current_Dimensions.ArcRadius()) - (adjusted_x * adjusted_x));
		if (point.y > 0 && point.y <= max_y) {
			return true;
		} else {
			return false;
		}
	}
	return false;
}

static Geometry2d::Point fromOursToTheirs(Geometry2d::Point &pt) {
	Geometry2d::Point c;
	c.y = Field_Dimensions::Current_Dimensions.Length() - pt.y;
	c.x = -pt.x;

	return c;
}

static bool ballIsInTheirGoalieBox(Geometry2d::Point &pt) {
	Geometry2d::Point converted = fromOursToTheirs(pt);
	return ballIsInGoalieBox(converted);
}

/** Handles saturation of a bounded value */
template<class T>
float clamp(T value, T min, T max)
{
	if (value > max)
	{
		return max;
	}
	else if (value < min)
	{
		return min;
	}
	return value;
}

// Removes all entries in a std::map which associate to the given value.
template<class Map_Type, class Data_Type>
void map_remove(Map_Type &map, Data_Type &value)
{
	typename Map_Type::iterator i = map.begin();
	while (i != map.end())
	{
		typename Map_Type::iterator next = i;
		++next;

		if (i->second == value)
		{
			map.erase(i);
		}

		i = next;
	}
}

// If <key> exists in <map>, returns map[key].
// If not, returns 0.
template<typename Map>
typename Map::mapped_type map_lookup(const Map &map, typename Map::key_type key)
{
	typename Map::const_iterator i = map.find(key);
	if (i != map.end())
	{
		return i->second;
	} else {
		return 0;
	}
}

/**
 * A basic FIR filter of variable type with float coeffs
 *
 * Note, coefficients will be normalized so that inputs
 * will always be scaled appropriately
 */
template<typename T>
class FIRFilter {
public:
	typedef std::vector<float> Coeffs;

	FIRFilter(const T& zero, size_t nrTaps) : _zero(zero) {
		if (nrTaps == 0)
			throw std::invalid_argument("FIR Filter: number of taps must be greater than zero");

		// initialize
		_taps.assign(nrTaps, _zero);
		_coeffs.assign(nrTaps, 0.0f);
		_coeffs[0] = 1.0;
	}

	T filter(const T& x) {
		_taps.push_front(x);
		_taps.pop_back();

		T y = _zero;
		for (size_t i = 0; i<_taps.size(); ++i)
			y += _taps.at(i) * _coeffs.at(i);

		return y;
	}

	/** reinitializes the coeffs and taps to new values */
	void setCoeffs(const Coeffs& coeffs) {
		size_t nrTaps = coeffs.size();
		if (nrTaps == 0)
			throw std::invalid_argument("FIR Filter: number of coeffs must be greater than zero");

		_taps.assign(nrTaps, _zero);
		_coeffs.assign(nrTaps, 0.0);

		// find the normalizer
		float normalizer = 0.0;
		for (size_t i = 0; i<coeffs.size(); ++i)
			normalizer += coeffs.at(i);

		// set the normalized coefficients
		for (size_t i=0; i<coeffs.size(); ++i)
			_coeffs[i] = coeffs.at(i) / normalizer;
	}

protected:
	T _zero;
	std::deque<T> _taps;
	Coeffs _coeffs;
};

// An output iterator which throws an exception when it's used.
// This is used for example to determine if the output of set_difference would be non-empty without
// calculating all of it.
template<typename T>
class ExceptionIterator: public std::iterator<std::output_iterator_tag, void, void, void, void>
{
public:
	ExceptionIterator &operator=(const T &value)
	{
		throw std::exception();
	}

	ExceptionIterator &operator*()
	{
		return *this;
	}

	ExceptionIterator &operator++()
	{
		return *this;
	}

	ExceptionIterator &operator++(int)
	{
		return *this;
	}
};

// Sets str to the name of a class.
// Use it like this:
//		Object *obj = new Object();
//		QString name = typeName(typeid(*obj));
// The returned name is in the usual C++ format: "Namespace::Namespace::Class"
QString typeName(const std::type_info &info);

// Like typeName, but only returns the final class name part.
QString className(const std::type_info &info);
<|endoftext|>


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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.

/// \file
/// Tests for the PhysicsManagerState class.

#include <gtest/gtest.h>

#include <string>
#include <memory>
#include <unordered_map>
#include <vector>

#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/Physics/Constraint.h"
#include "SurgSim/Physics/ContactConstraintData.h"
#include "SurgSim/Physics/MlcpMapping.h"
#include "SurgSim/Physics/PhysicsManagerState.h"
#include "SurgSim/Physics/RigidCollisionRepresentation.h"
#include "SurgSim/Physics/RigidRepresentation.h"
#include "SurgSim/Physics/RigidRepresentationContact.h"

using SurgSim::Physics::Constraint;
using SurgSim::Physics::ContactConstraintData;
using SurgSim::Physics::Localization;
using SurgSim::Physics::MlcpMapping;
using SurgSim::Physics::PhysicsManagerState;
using SurgSim::Physics::Representation;
using SurgSim::Physics::RigidCollisionRepresentation;
using SurgSim::Physics::RigidRepresentation;
using SurgSim::Physics::RigidRepresentationContact;
using SurgSim::Physics::RigidRepresentationLocalization;

TEST(PhysicsManagerStateTest, SetGetRigidRepresentations)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();
	std::vector<std::shared_ptr<Representation>> expectedRepresentations;
	std::vector<std::shared_ptr<Representation>> actualRepresentations;
	MlcpMapping<Representation> actualRepresentationsIndexMapping;
	std::unordered_map<std::shared_ptr<SurgSim::Collision::Representation>,
		std::shared_ptr<Representation>> actualCollisionsToPhysicsMap;

	// Add a representation.
	auto rigid1 = std::make_shared<RigidRepresentation>("rigid1");
	expectedRepresentations.push_back(rigid1);
	physicsState->setRepresentations(expectedRepresentations);
	actualRepresentations = physicsState->getRepresentations();
	ASSERT_EQ(1, actualRepresentations.size());
	EXPECT_EQ(rigid1, actualRepresentations.back());
	actualRepresentationsIndexMapping = physicsState->getRepresentationsMapping();
	int expectedMapValue = 0;
	std::shared_ptr<Representation> rigid1AsRepresentation = rigid1;
	EXPECT_EQ(expectedMapValue, actualRepresentationsIndexMapping.getValue(rigid1AsRepresentation.get()));
	actualCollisionsToPhysicsMap = physicsState->getCollisionToPhysicsMap();
	EXPECT_EQ(0, actualCollisionsToPhysicsMap.size());

	// Add a second representation.  This one has a collision representation.
	auto rigid2 = std::make_shared<RigidRepresentation>("rigid2");
	auto collisionRepresentation = std::make_shared<SurgSim::Physics::RigidCollisionRepresentation>("rigid2 collision");
	collisionRepresentation->setRigidRepresentation(rigid2);
	expectedRepresentations.push_back(rigid2);
	physicsState->setRepresentations(expectedRepresentations);
	actualRepresentations = physicsState->getRepresentations();
	ASSERT_EQ(2, actualRepresentations.size());
	EXPECT_EQ(rigid2, actualRepresentations.back());

	// check the representationsIndexMapping
	actualRepresentationsIndexMapping = physicsState->getRepresentationsMapping();
	EXPECT_EQ(expectedMapValue, actualRepresentationsIndexMapping.getValue(rigid1AsRepresentation.get()));
	expectedMapValue += 6; // the number of DOF for a rigid representation
	std::shared_ptr<Representation> rigid2AsRepresentation = rigid2;
	EXPECT_EQ(expectedMapValue, actualRepresentationsIndexMapping.getValue(rigid2AsRepresentation.get()));

	// check the collisionsToPhysicsMap
	actualCollisionsToPhysicsMap = physicsState->getCollisionToPhysicsMap();
	ASSERT_EQ(1, actualCollisionsToPhysicsMap.size());
	EXPECT_EQ(rigid2, actualCollisionsToPhysicsMap[collisionRepresentation]);
}

TEST(PhysicsManagerStateTest, SetGetCollisionRepresentations)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();
	std::vector<std::shared_ptr<SurgSim::Collision::Representation>> expectedRepresentations;
	std::vector<std::shared_ptr<SurgSim::Collision::Representation>> actualRepresentations;

	// Add a collision representation.
	std::shared_ptr<SurgSim::Collision::Representation> collision1 =
		std::make_shared<RigidCollisionRepresentation>("collision1");

	std::make_shared<RigidCollisionRepresentation>("Sphere1 Collision");
	expectedRepresentations.push_back(collision1);
	physicsState->setCollisionRepresentations(expectedRepresentations);
	actualRepresentations = physicsState->getCollisionRepresentations();
	ASSERT_EQ(1, actualRepresentations.size());
	EXPECT_EQ(collision1, actualRepresentations.back());

	// Add a second collision representation.
	std::shared_ptr<SurgSim::Collision::Representation> collision2 =
		std::make_shared<RigidCollisionRepresentation>("collision2");
	expectedRepresentations.push_back(collision2);
	physicsState->setCollisionRepresentations(expectedRepresentations);
	actualRepresentations = physicsState->getCollisionRepresentations();
	ASSERT_EQ(2, actualRepresentations.size());
	EXPECT_EQ(collision2, actualRepresentations.back());
}

TEST(PhysicsManagerStateTest, SetGetCollisionPairs)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();
	std::vector<std::shared_ptr<SurgSim::Collision::CollisionPair>> expectedPairs;
	std::vector<std::shared_ptr<SurgSim::Collision::CollisionPair>> actualPairs;

	// Add a collision pair.
	auto pair1 = std::make_shared<SurgSim::Collision::CollisionPair>();
	expectedPairs.push_back(pair1);
	physicsState->setCollisionPairs(expectedPairs);
	actualPairs = physicsState->getCollisionPairs();
	ASSERT_EQ(1, actualPairs.size());
	EXPECT_EQ(pair1, actualPairs.back());

	// Add a second collision representation.
	auto pair2 = std::make_shared<SurgSim::Collision::CollisionPair>();
	expectedPairs.push_back(pair2);
	physicsState->setCollisionPairs(expectedPairs);
	actualPairs = physicsState->getCollisionPairs();
	ASSERT_EQ(2, actualPairs.size());
	EXPECT_EQ(pair2, actualPairs.back());
}

TEST(PhysicsManagerStateTest, SetGetConstraintGroup)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();
	std::vector<std::shared_ptr<Constraint>> expectedConstraints;
	std::vector<std::shared_ptr<Constraint>> actualConstraints;

	// We need a populated constraint to check the constraintsIndexMapping.
	// Create first side of a constraint.
	auto rigid1 = std::make_shared<RigidRepresentation>("rigid1");
	std::shared_ptr<RigidRepresentationLocalization> rigid1LocalizationTyped;
	rigid1LocalizationTyped = std::make_shared<RigidRepresentationLocalization>();
	rigid1LocalizationTyped->setRepresentation(rigid1);
	std::shared_ptr<Localization> rigid1Localization = rigid1LocalizationTyped;
	auto rigid1Contact = std::make_shared<RigidRepresentationContact>();

	// Create second side of a constraint.
	auto rigid2 = std::make_shared<RigidRepresentation>("rigid2");
	std::shared_ptr<RigidRepresentationLocalization> rigid2LocalizationTyped;
	rigid2LocalizationTyped = std::make_shared<RigidRepresentationLocalization>();
	rigid2LocalizationTyped->setRepresentation(rigid2);
	std::shared_ptr<Localization> rigid2Localization = rigid2LocalizationTyped;
	auto rigid2Contact = std::make_shared<RigidRepresentationContact>();

	// Create the constraint specific data.
	std::shared_ptr<ContactConstraintData> data = std::make_shared<ContactConstraintData>();

	// Create the constraint.
	auto constraint1 = std::make_shared<Constraint>(data, rigid1Contact, rigid1Localization,
		rigid2Contact, rigid2Localization);

	// Check the constraintGroup.
	expectedConstraints.push_back(constraint1);
	physicsState->setConstraintGroup(SurgSim::Physics::CONSTRAINT_GROUP_TYPE_CONTACT, expectedConstraints);
	actualConstraints = physicsState->getConstraintGroup(SurgSim::Physics::CONSTRAINT_GROUP_TYPE_CONTACT);
	ASSERT_EQ(1, actualConstraints.size());
	EXPECT_EQ(constraint1, actualConstraints.back());

	// Create a second constraint.
	auto constraint2 = std::make_shared<Constraint>(data, rigid1Contact, rigid1Localization,
		rigid2Contact, rigid2Localization);

	// Check the constraintGroup.
	expectedConstraints.push_back(constraint2);
	physicsState->setConstraintGroup(SurgSim::Physics::CONSTRAINT_GROUP_TYPE_CONTACT, expectedConstraints);
	actualConstraints = physicsState->getConstraintGroup(SurgSim::Physics::CONSTRAINT_GROUP_TYPE_CONTACT);
	ASSERT_EQ(2, actualConstraints.size());
	EXPECT_EQ(constraint2, actualConstraints.back());

	// Check the constraintsIndexMapping.
	MlcpMapping<Constraint> actualConstraintsIndexMapping = physicsState->getConstraintsMapping();
	int expectedMapValue = 0;
	EXPECT_EQ(expectedMapValue, actualConstraintsIndexMapping.getValue(constraint1.get()));
	expectedMapValue += 1; // The number of DOF for a MLCP_UNILATERAL_3D_FRICTIONLESS_CONSTRAINT.
	std::shared_ptr<Representation> rigid2AsRepresentation = rigid2;
	EXPECT_EQ(expectedMapValue, actualConstraintsIndexMapping.getValue(constraint2.get()));
}

TEST(PhysicsManagerStateTest, GetMlcpProblem)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();

	// Check non-const getter.
	EXPECT_NO_THROW(physicsState->getMlcpProblem().A.resize(21, 8));
	EXPECT_EQ(21, physicsState->getMlcpProblem().A.rows());
	EXPECT_EQ(8, physicsState->getMlcpProblem().A.cols());

	// Check const getter.
	std::shared_ptr<const PhysicsManagerState> constPhysicsState = std::make_shared<PhysicsManagerState>();
	EXPECT_NO_THROW(constPhysicsState->getMlcpProblem());
}

TEST(PhysicsManagerStateTest, GetMlcpSolution)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();

	// Check non-const getter.
	EXPECT_NO_THROW(physicsState->getMlcpSolution().x.resize(23));
	EXPECT_EQ(23, physicsState->getMlcpSolution().x.size());

	// Check const getter.
	std::shared_ptr<const PhysicsManagerState> constPhysicsState = std::make_shared<PhysicsManagerState>();
	EXPECT_NO_THROW(constPhysicsState->getMlcpSolution());
}
<commit_msg>Removes unnecessary construction in PhysicsManagerStateTests.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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.

/// \file
/// Tests for the PhysicsManagerState class.

#include <gtest/gtest.h>

#include <string>
#include <memory>
#include <unordered_map>
#include <vector>

#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/Physics/Constraint.h"
#include "SurgSim/Physics/ContactConstraintData.h"
#include "SurgSim/Physics/MlcpMapping.h"
#include "SurgSim/Physics/PhysicsManagerState.h"
#include "SurgSim/Physics/RigidCollisionRepresentation.h"
#include "SurgSim/Physics/RigidRepresentation.h"
#include "SurgSim/Physics/RigidRepresentationContact.h"

using SurgSim::Physics::Constraint;
using SurgSim::Physics::ContactConstraintData;
using SurgSim::Physics::Localization;
using SurgSim::Physics::MlcpMapping;
using SurgSim::Physics::PhysicsManagerState;
using SurgSim::Physics::Representation;
using SurgSim::Physics::RigidCollisionRepresentation;
using SurgSim::Physics::RigidRepresentation;
using SurgSim::Physics::RigidRepresentationContact;
using SurgSim::Physics::RigidRepresentationLocalization;

TEST(PhysicsManagerStateTest, SetGetRigidRepresentations)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();
	std::vector<std::shared_ptr<Representation>> expectedRepresentations;
	std::vector<std::shared_ptr<Representation>> actualRepresentations;
	MlcpMapping<Representation> actualRepresentationsIndexMapping;
	std::unordered_map<std::shared_ptr<SurgSim::Collision::Representation>,
		std::shared_ptr<Representation>> actualCollisionsToPhysicsMap;

	// Add a representation.
	auto rigid1 = std::make_shared<RigidRepresentation>("rigid1");
	expectedRepresentations.push_back(rigid1);
	physicsState->setRepresentations(expectedRepresentations);
	actualRepresentations = physicsState->getRepresentations();
	ASSERT_EQ(1, actualRepresentations.size());
	EXPECT_EQ(rigid1, actualRepresentations.back());
	actualRepresentationsIndexMapping = physicsState->getRepresentationsMapping();
	int expectedMapValue = 0;
	std::shared_ptr<Representation> rigid1AsRepresentation = rigid1;
	EXPECT_EQ(expectedMapValue, actualRepresentationsIndexMapping.getValue(rigid1AsRepresentation.get()));
	actualCollisionsToPhysicsMap = physicsState->getCollisionToPhysicsMap();
	EXPECT_EQ(0, actualCollisionsToPhysicsMap.size());

	// Add a second representation.  This one has a collision representation.
	auto rigid2 = std::make_shared<RigidRepresentation>("rigid2");
	auto collisionRepresentation = std::make_shared<SurgSim::Physics::RigidCollisionRepresentation>("rigid2 collision");
	collisionRepresentation->setRigidRepresentation(rigid2);
	expectedRepresentations.push_back(rigid2);
	physicsState->setRepresentations(expectedRepresentations);
	actualRepresentations = physicsState->getRepresentations();
	ASSERT_EQ(2, actualRepresentations.size());
	EXPECT_EQ(rigid2, actualRepresentations.back());

	// check the representationsIndexMapping
	actualRepresentationsIndexMapping = physicsState->getRepresentationsMapping();
	EXPECT_EQ(expectedMapValue, actualRepresentationsIndexMapping.getValue(rigid1AsRepresentation.get()));
	expectedMapValue += 6; // the number of DOF for a rigid representation
	std::shared_ptr<Representation> rigid2AsRepresentation = rigid2;
	EXPECT_EQ(expectedMapValue, actualRepresentationsIndexMapping.getValue(rigid2AsRepresentation.get()));

	// check the collisionsToPhysicsMap
	actualCollisionsToPhysicsMap = physicsState->getCollisionToPhysicsMap();
	ASSERT_EQ(1, actualCollisionsToPhysicsMap.size());
	EXPECT_EQ(rigid2, actualCollisionsToPhysicsMap[collisionRepresentation]);
}

TEST(PhysicsManagerStateTest, SetGetCollisionRepresentations)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();
	std::vector<std::shared_ptr<SurgSim::Collision::Representation>> expectedRepresentations;
	std::vector<std::shared_ptr<SurgSim::Collision::Representation>> actualRepresentations;

	// Add a collision representation.
	std::shared_ptr<SurgSim::Collision::Representation> collision1 =
		std::make_shared<RigidCollisionRepresentation>("collision1");

	expectedRepresentations.push_back(collision1);
	physicsState->setCollisionRepresentations(expectedRepresentations);
	actualRepresentations = physicsState->getCollisionRepresentations();
	ASSERT_EQ(1, actualRepresentations.size());
	EXPECT_EQ(collision1, actualRepresentations.back());

	// Add a second collision representation.
	std::shared_ptr<SurgSim::Collision::Representation> collision2 =
		std::make_shared<RigidCollisionRepresentation>("collision2");
	expectedRepresentations.push_back(collision2);
	physicsState->setCollisionRepresentations(expectedRepresentations);
	actualRepresentations = physicsState->getCollisionRepresentations();
	ASSERT_EQ(2, actualRepresentations.size());
	EXPECT_EQ(collision2, actualRepresentations.back());
}

TEST(PhysicsManagerStateTest, SetGetCollisionPairs)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();
	std::vector<std::shared_ptr<SurgSim::Collision::CollisionPair>> expectedPairs;
	std::vector<std::shared_ptr<SurgSim::Collision::CollisionPair>> actualPairs;

	// Add a collision pair.
	auto pair1 = std::make_shared<SurgSim::Collision::CollisionPair>();
	expectedPairs.push_back(pair1);
	physicsState->setCollisionPairs(expectedPairs);
	actualPairs = physicsState->getCollisionPairs();
	ASSERT_EQ(1, actualPairs.size());
	EXPECT_EQ(pair1, actualPairs.back());

	// Add a second collision representation.
	auto pair2 = std::make_shared<SurgSim::Collision::CollisionPair>();
	expectedPairs.push_back(pair2);
	physicsState->setCollisionPairs(expectedPairs);
	actualPairs = physicsState->getCollisionPairs();
	ASSERT_EQ(2, actualPairs.size());
	EXPECT_EQ(pair2, actualPairs.back());
}

TEST(PhysicsManagerStateTest, SetGetConstraintGroup)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();
	std::vector<std::shared_ptr<Constraint>> expectedConstraints;
	std::vector<std::shared_ptr<Constraint>> actualConstraints;

	// We need a populated constraint to check the constraintsIndexMapping.
	// Create first side of a constraint.
	auto rigid1 = std::make_shared<RigidRepresentation>("rigid1");
	std::shared_ptr<RigidRepresentationLocalization> rigid1LocalizationTyped =
		std::make_shared<RigidRepresentationLocalization>();
	rigid1LocalizationTyped->setRepresentation(rigid1);
	std::shared_ptr<Localization> rigid1Localization = rigid1LocalizationTyped;
	auto rigid1Contact = std::make_shared<RigidRepresentationContact>();

	// Create second side of a constraint.
	auto rigid2 = std::make_shared<RigidRepresentation>("rigid2");
	std::shared_ptr<RigidRepresentationLocalization> rigid2LocalizationTyped =
		std::make_shared<RigidRepresentationLocalization>();
	rigid2LocalizationTyped->setRepresentation(rigid2);
	std::shared_ptr<Localization> rigid2Localization = rigid2LocalizationTyped;
	auto rigid2Contact = std::make_shared<RigidRepresentationContact>();

	// Create the constraint specific data.
	std::shared_ptr<ContactConstraintData> data = std::make_shared<ContactConstraintData>();

	// Create the constraint.
	auto constraint1 = std::make_shared<Constraint>(data, rigid1Contact, rigid1Localization,
		rigid2Contact, rigid2Localization);

	// Check the constraintGroup.
	expectedConstraints.push_back(constraint1);
	physicsState->setConstraintGroup(SurgSim::Physics::CONSTRAINT_GROUP_TYPE_CONTACT, expectedConstraints);
	actualConstraints = physicsState->getConstraintGroup(SurgSim::Physics::CONSTRAINT_GROUP_TYPE_CONTACT);
	ASSERT_EQ(1, actualConstraints.size());
	EXPECT_EQ(constraint1, actualConstraints.back());

	// Create a second constraint.
	auto constraint2 = std::make_shared<Constraint>(data, rigid1Contact, rigid1Localization,
		rigid2Contact, rigid2Localization);

	// Check the constraintGroup.
	expectedConstraints.push_back(constraint2);
	physicsState->setConstraintGroup(SurgSim::Physics::CONSTRAINT_GROUP_TYPE_CONTACT, expectedConstraints);
	actualConstraints = physicsState->getConstraintGroup(SurgSim::Physics::CONSTRAINT_GROUP_TYPE_CONTACT);
	ASSERT_EQ(2, actualConstraints.size());
	EXPECT_EQ(constraint2, actualConstraints.back());

	// Check the constraintsIndexMapping.
	MlcpMapping<Constraint> actualConstraintsIndexMapping = physicsState->getConstraintsMapping();
	int expectedMapValue = 0;
	EXPECT_EQ(expectedMapValue, actualConstraintsIndexMapping.getValue(constraint1.get()));
	expectedMapValue += 1; // The number of DOF for a MLCP_UNILATERAL_3D_FRICTIONLESS_CONSTRAINT.
	std::shared_ptr<Representation> rigid2AsRepresentation = rigid2;
	EXPECT_EQ(expectedMapValue, actualConstraintsIndexMapping.getValue(constraint2.get()));
}

TEST(PhysicsManagerStateTest, GetMlcpProblem)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();

	// Check non-const getter.
	EXPECT_NO_THROW(physicsState->getMlcpProblem().A.resize(21, 8));
	EXPECT_EQ(21, physicsState->getMlcpProblem().A.rows());
	EXPECT_EQ(8, physicsState->getMlcpProblem().A.cols());

	// Check const getter.
	std::shared_ptr<const PhysicsManagerState> constPhysicsState = std::make_shared<PhysicsManagerState>();
	EXPECT_NO_THROW(constPhysicsState->getMlcpProblem());
}

TEST(PhysicsManagerStateTest, GetMlcpSolution)
{
	auto physicsState = std::make_shared<PhysicsManagerState>();

	// Check non-const getter.
	EXPECT_NO_THROW(physicsState->getMlcpSolution().x.resize(23));
	EXPECT_EQ(23, physicsState->getMlcpSolution().x.size());

	// Check const getter.
	std::shared_ptr<const PhysicsManagerState> constPhysicsState = std::make_shared<PhysicsManagerState>();
	EXPECT_NO_THROW(constPhysicsState->getMlcpSolution());
}
<|endoftext|>


<commit_before>/*
 * igridreport - produce json configuration gridreport
*/
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "lsUtil.hpp"
#include "irods_buffer_encryption.hpp"
#include "grid_report.hpp"
#include <string>
#include <iostream>

int
main( int, char** ) {

    rodsEnv myEnv;
    int status = getRodsEnv( &myEnv );
    if ( status < 0 ) {
        rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
        exit( 1 );
    }

    rErrMsg_t errMsg;
    rcComm_t *conn;
    conn = rcConnect(
               myEnv.rodsHost,
               myEnv.rodsPort,
               myEnv.rodsUserName,
               myEnv.rodsZone,
               0, &errMsg );

    if ( conn == NULL ) {
        exit( 2 );
    }

    // =-=-=-=-=-=-=-
    // initialize pluggable api table
    irods::pack_entry_table& pk_tbl = irods::get_pack_table();
    irods::api_entry_table& api_tbl = irods::get_client_api_table();
    init_api_table( api_tbl, pk_tbl );

    if ( strcmp( myEnv.rodsUserName, PUBLIC_USER_NAME ) != 0 ) {
        status = clientLogin( conn );
        if ( status != 0 ) {
            rcDisconnect( conn );
            exit( 7 );
        }
    }

    void *tmp_out = NULL;
    status = procApiRequest( conn, GRID_REPORT_AN, NULL, NULL,
                             &tmp_out, NULL );
    if ( status < 0 ) {
        printf( "\n\nERROR - failed in call to rcGridReport" );
        return 0;
    }
    else {
        bytesBuf_t* bbuf = static_cast< bytesBuf_t* >( tmp_out );

        // may not be propertly null terminated
        std::string s( (char*)bbuf->buf, bbuf->len );
        printf( "\n%s\n", s.c_str() );
    }

    rcDisconnect( conn );
}

<commit_msg>[#858] spelling<commit_after>/*
 * igridreport - produce json configuration gridreport
*/
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "lsUtil.hpp"
#include "irods_buffer_encryption.hpp"
#include "grid_report.hpp"
#include <string>
#include <iostream>

int
main( int, char** ) {

    rodsEnv myEnv;
    int status = getRodsEnv( &myEnv );
    if ( status < 0 ) {
        rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
        exit( 1 );
    }

    rErrMsg_t errMsg;
    rcComm_t *conn;
    conn = rcConnect(
               myEnv.rodsHost,
               myEnv.rodsPort,
               myEnv.rodsUserName,
               myEnv.rodsZone,
               0, &errMsg );

    if ( conn == NULL ) {
        exit( 2 );
    }

    // =-=-=-=-=-=-=-
    // initialize pluggable api table
    irods::pack_entry_table& pk_tbl = irods::get_pack_table();
    irods::api_entry_table& api_tbl = irods::get_client_api_table();
    init_api_table( api_tbl, pk_tbl );

    if ( strcmp( myEnv.rodsUserName, PUBLIC_USER_NAME ) != 0 ) {
        status = clientLogin( conn );
        if ( status != 0 ) {
            rcDisconnect( conn );
            exit( 7 );
        }
    }

    void *tmp_out = NULL;
    status = procApiRequest( conn, GRID_REPORT_AN, NULL, NULL,
                             &tmp_out, NULL );
    if ( status < 0 ) {
        printf( "\n\nERROR - failed in call to rcGridReport" );
        return 0;
    }
    else {
        bytesBuf_t* bbuf = static_cast< bytesBuf_t* >( tmp_out );

        // may not be properly null terminated
        std::string s( (char*)bbuf->buf, bbuf->len );
        printf( "\n%s\n", s.c_str() );
    }

    rcDisconnect( conn );
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007-2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/util/DynamicObjectImpl.h"
#include "db/util/DynamicObject.h"

using namespace std;
using namespace db::util;

DynamicObjectImpl::DynamicObjectImpl()
{
   mType = String;
   mString = NULL;
   mStringValue = NULL;
}

DynamicObjectImpl::~DynamicObjectImpl()
{
   DynamicObjectImpl::freeData();

   // free cached string value
   if(mStringValue != NULL)
   {
      free(mStringValue);
   }
}

void DynamicObjectImpl::freeMapKeys()
{
   // clean up member names
   for(ObjectMap::iterator i = mMap->begin(); i != mMap->end(); i++)
   {
      free((char*)i->first);
   }
}

void DynamicObjectImpl::freeData()
{
   // clean up data based on type
   switch(mType)
   {
      case String:
         {
            if(mString != NULL)
            {
               free(mString);
            }
            mString = NULL;
         }
         break;
      case Map:
         if(mMap != NULL)
         {
            freeMapKeys();
            delete mMap;
            mMap = NULL;
         }
         break;
      case Array:
         if(mArray != NULL)
         {
            delete mArray;
            mArray = NULL;
         }
         break;
      default:
         // nothing to cleanup
         break;
   }
}

void DynamicObjectImpl::setString(const char* value)
{
   freeData();
   mType = String;
   mString = strdup(value);
}

void DynamicObjectImpl::operator=(const char* value)
{
   setString(value);
}

void DynamicObjectImpl::operator=(bool value)
{
   freeData();
   mType = Boolean;
   mBoolean = value;
}

void DynamicObjectImpl::operator=(int value)
{
   freeData();
   mType = Int32;
   mInt32 = value;
}

void DynamicObjectImpl::operator=(unsigned int value)
{
   freeData();
   mType = UInt32;
   mUInt32 = value;
}

void DynamicObjectImpl::operator=(long long value)
{
   freeData();
   mType = Int64;
   mInt64 = value;
}

void DynamicObjectImpl::operator=(unsigned long long value)
{
   freeData();
   mType = UInt64;
   mUInt64 = value;
}

void DynamicObjectImpl::operator=(double value)
{
   freeData();
   mType = Double;
   mDouble = value;
}

DynamicObject& DynamicObjectImpl::operator[](const char* name)
{
   DynamicObject* rval = NULL;

   // change to map type if necessary
   setType(Map);

   ObjectMap::iterator i = mMap->find(name);
   if(i == mMap->end())
   {
      // create new map entry
      DynamicObject dyno;
      mMap->insert(std::make_pair(strdup(name), dyno));
      rval = &(*mMap)[name];
   }
   else
   {
      // get existing map entry
      rval = &i->second;
   }

   return *rval;
}

DynamicObject& DynamicObjectImpl::operator[](int index)
{
   // change to array type if necessary
   setType(Array);

   if(index < 0)
   {
      index = mArray->size() + index;
   }

   // fill the object array as necessary
   if(index >= (int)mArray->size())
   {
      int i = index - (int)mArray->size() + 1;
      for(; i > 0; i--)
      {
         DynamicObject dyno;
         mArray->push_back(dyno);
      }
   }

   return (*mArray)[index];
}

DynamicObject& DynamicObjectImpl::append()
{
   return (*this)[length()];
}

void DynamicObjectImpl::setType(DynamicObjectType type)
{
   if(mType != type)
   {
      switch(type)
      {
         case String:
            *this = getString();
            break;
         case Boolean:
            *this = getBoolean();
            break;
         case Int32:
            *this = getInt32();
            break;
         case UInt32:
            *this = getUInt32();
            break;
         case Int64:
            *this = getInt64();
            break;
         case UInt64:
            *this = getUInt64();
            break;
         case Double:
            *this = getDouble();
            break;
         case Map:
            {
               freeData();
               mType = Map;
               mMap = new ObjectMap();
            }
            break;
         case Array:
            {
               freeData();
               mType = Array;
               mArray = new ObjectArray();
            }
            break;
      }
   }
}

DynamicObjectType DynamicObjectImpl::getType()
{
   return mType;
}

const char* DynamicObjectImpl::getString()
{
   const char* rval;

   if(mType == String)
   {
      if(mString != NULL)
      {
         // use existing string
         rval = mString;
      }
      else
      {
         // only duplicate blank string upon request
         rval = mString = strdup("");
      }
   }
   else
   {
      // convert type as appropriate
      switch(mType)
      {
         case Boolean:
            mStringValue = (char*)realloc(mStringValue, 6);
            snprintf(mStringValue, 6, "%s", (mBoolean ? "true" : "false"));
            break;
         case Int32:
            mStringValue = (char*)realloc(mStringValue, 12);
            snprintf(mStringValue, 12, "%i", mInt32);
            break;
         case UInt32:
            mStringValue = (char*)realloc(mStringValue, 11);
            snprintf(mStringValue, 11, "%u", mUInt32);
            break;
         case Int64:
            mStringValue = (char*)realloc(mStringValue, 22);
            snprintf(mStringValue, 22, "%lli", mInt64);
            break;
         case UInt64:
            mStringValue = (char*)realloc(mStringValue, 21);
            snprintf(mStringValue, 21, "%llu", mUInt64);
            break;
         case Double:
            // use default precision of 6
            // X.000000e+00 = 11 places to right of decimal
            mStringValue = (char*)realloc(mStringValue, 50);
            snprintf(mStringValue, 50, "%e", mDouble);
            break;
         default: /* Map, Array, ... */
            {
               if(mStringValue == NULL)
               {
                  // duplicate blank string
                  mStringValue = strdup("");
               }
               else
               {
                  // set null-terminator to first character
                  mStringValue[0] = 0;
               }
            }
            break;
      }

      // return generated value
      rval = mStringValue;
   }

   return rval;
}

bool DynamicObjectImpl::getBoolean()
{
   bool rval;

   switch(mType)
   {
      case Boolean:
         rval = mBoolean;
         break;
      case String:
         rval = (strcmp(mString, "true") == 0);
         break;
      case Int32:
         rval = (mInt32 == 1);
         break;
      case UInt32:
         rval = (mUInt32 == 1);
         break;
      case Int64:
         rval = (mInt64 == 1);
         break;
      case UInt64:
         rval = (mUInt64 == 1);
         break;
      case Double:
         rval = (mDouble == 1);
         break;
      default:
         rval = false;
         break;
   }

   return rval;
}

int DynamicObjectImpl::getInt32()
{
   int rval;

   switch(mType)
   {
      case Int32:
         rval = mInt32;
         break;
      case String:
         rval = strtol(mString, NULL, 10);
         break;
      case Boolean:
         rval = mBoolean ? 1 : 0;
         break;
      case UInt32:
         rval = (int)mUInt32;
         break;
      case Int64:
         rval = (int)mInt64;
         break;
      case UInt64:
         rval = (int)mUInt64;
         break;
      case Double:
         rval = (int)mDouble;
         break;
      default:
         rval = 0;
         break;
   }

   return rval;
}

unsigned int DynamicObjectImpl::getUInt32()
{
   unsigned int rval;

   switch(mType)
   {
      case UInt32:
         rval = mUInt32;
         break;
      case String:
         rval = (unsigned int)strtoul(mString, NULL, 10);
         break;
      case Boolean:
         rval = mBoolean ? 1 : 0;
         break;
      case Int32:
         rval = (mInt32 < 0) ? 0 : mInt32;
         break;
      case Int64:
         rval = (mInt64 < 0) ? 0 : (unsigned int)mInt64;
         break;
      case UInt64:
         rval = (unsigned int)mUInt64;
         break;
      case Double:
         rval = (unsigned int)mDouble;
         break;
      default:
         rval = 0;
         break;
   }

   return rval;
}

long long DynamicObjectImpl::getInt64()
{
   long long rval;

   switch(mType)
   {
      case Int64:
         rval = mInt64;
         break;
      case String:
         rval = strtoll(mString, NULL, 10);
         break;
      case Boolean:
         rval = mBoolean ? 1 : 0;
         break;
      case Int32:
         rval = mInt32;
         break;
      case UInt32:
         rval = mUInt32;
         break;
      case UInt64:
         rval = (long long)mUInt64;
         break;
      case Double:
         rval = (long long)mDouble;
         break;
      default:
         rval = 0;
         break;
   }

   return rval;
}

unsigned long long DynamicObjectImpl::getUInt64()
{
   unsigned long long rval;

   switch(mType)
   {
      case UInt64:
         rval = mUInt64;
         break;
      case String:
         rval = strtoull(mString, NULL, 10);
         break;
      case Boolean:
         rval = mBoolean ? 1 : 0;
         break;
      case Int32:
         rval = (mInt32 < 0) ? 0 : mInt32;
         break;
      case UInt32:
         rval = mUInt32;
         break;
      case Int64:
         rval = (mInt64 < 0) ? 0 : mInt64;
         break;
      case Double:
         rval = mDouble;
         break;
      default:
         rval = 0;
         break;
   }

   return rval;
}

double DynamicObjectImpl::getDouble()
{
   double rval;

   switch(mType)
   {
      case Double:
         rval = mDouble;
         break;
      case String:
         rval = strtod(mString, NULL);
         break;
      case Boolean:
         rval = mBoolean ? 1 : 0;
         break;
      case Int32:
         rval = mInt32;
         break;
      case UInt32:
         rval = mUInt32;
         break;
      case Int64:
         rval = mInt64;
         break;
      case UInt64:
         rval = mUInt64;
         break;
      default:
         rval = 0;
         break;
   }

   return rval;
}

bool DynamicObjectImpl::hasMember(const char* name)
{
   bool rval = false;

   if(mType == Map)
   {
      ObjectMap::iterator i = mMap->find(name);
      rval = (i != mMap->end());
   }

   return rval;
}

DynamicObject DynamicObjectImpl::removeMember(const char* name)
{
   DynamicObject rval(NULL);

   if(mType == Map)
   {
      ObjectMap::iterator i = mMap->find(name);
      if(i != mMap->end())
      {
         // clean up key and remove map entry
         free((char*)i->first);
         rval = i->second;
         mMap->erase(i);
      }
   }

   return rval;
}

void DynamicObjectImpl::clear()
{
   switch(mType)
   {
      case String:
         *this = "";
         break;
      case Boolean:
         *this = false;
         break;
      case Int32:
         *this = (int)0;
         break;
      case UInt32:
         *this = (unsigned int)0;
         break;
      case Int64:
         *this = (long long)0;
         break;
      case UInt64:
         *this = (unsigned long long)0;
         break;
      case Double:
         *this = (double)0.0;
         break;
      case Map:
         freeMapKeys();
         mMap->clear();
         break;
      case Array:
         mArray->clear();
         break;
   }
}

int DynamicObjectImpl::length()
{
   int rval = 0;

   switch(mType)
   {
      case String:
         if(mString != NULL)
         {
            rval = strlen(getString());
         }
         break;
      case Boolean:
         rval = 1;
         break;
      case Int32:
      case UInt32:
         rval = sizeof(unsigned int);
         break;
      case Int64:
      case UInt64:
         rval = sizeof(unsigned long long);
         break;
      case Double:
         rval = sizeof(double);
         break;
      case Map:
         rval = mMap->size();
         break;
      case Array:
         rval = mArray->size();
         break;
   }

   return rval;
}
<commit_msg>Fixed potential null dereference bug in conversion methods.<commit_after>/*
 * Copyright (c) 2007-2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/util/DynamicObjectImpl.h"
#include "db/util/DynamicObject.h"

using namespace std;
using namespace db::util;

DynamicObjectImpl::DynamicObjectImpl()
{
   mType = String;
   mString = NULL;
   mStringValue = NULL;
}

DynamicObjectImpl::~DynamicObjectImpl()
{
   DynamicObjectImpl::freeData();

   // free cached string value
   if(mStringValue != NULL)
   {
      free(mStringValue);
   }
}

void DynamicObjectImpl::freeMapKeys()
{
   // clean up member names
   for(ObjectMap::iterator i = mMap->begin(); i != mMap->end(); i++)
   {
      free((char*)i->first);
   }
}

void DynamicObjectImpl::freeData()
{
   // clean up data based on type
   switch(mType)
   {
      case String:
         {
            if(mString != NULL)
            {
               free(mString);
            }
            mString = NULL;
         }
         break;
      case Map:
         if(mMap != NULL)
         {
            freeMapKeys();
            delete mMap;
            mMap = NULL;
         }
         break;
      case Array:
         if(mArray != NULL)
         {
            delete mArray;
            mArray = NULL;
         }
         break;
      default:
         // nothing to cleanup
         break;
   }
}

void DynamicObjectImpl::setString(const char* value)
{
   freeData();
   mType = String;
   mString = strdup(value);
}

void DynamicObjectImpl::operator=(const char* value)
{
   setString(value);
}

void DynamicObjectImpl::operator=(bool value)
{
   freeData();
   mType = Boolean;
   mBoolean = value;
}

void DynamicObjectImpl::operator=(int value)
{
   freeData();
   mType = Int32;
   mInt32 = value;
}

void DynamicObjectImpl::operator=(unsigned int value)
{
   freeData();
   mType = UInt32;
   mUInt32 = value;
}

void DynamicObjectImpl::operator=(long long value)
{
   freeData();
   mType = Int64;
   mInt64 = value;
}

void DynamicObjectImpl::operator=(unsigned long long value)
{
   freeData();
   mType = UInt64;
   mUInt64 = value;
}

void DynamicObjectImpl::operator=(double value)
{
   freeData();
   mType = Double;
   mDouble = value;
}

DynamicObject& DynamicObjectImpl::operator[](const char* name)
{
   DynamicObject* rval = NULL;

   // change to map type if necessary
   setType(Map);

   ObjectMap::iterator i = mMap->find(name);
   if(i == mMap->end())
   {
      // create new map entry
      DynamicObject dyno;
      mMap->insert(std::make_pair(strdup(name), dyno));
      rval = &(*mMap)[name];
   }
   else
   {
      // get existing map entry
      rval = &i->second;
   }

   return *rval;
}

DynamicObject& DynamicObjectImpl::operator[](int index)
{
   // change to array type if necessary
   setType(Array);

   if(index < 0)
   {
      index = mArray->size() + index;
   }

   // fill the object array as necessary
   if(index >= (int)mArray->size())
   {
      int i = index - (int)mArray->size() + 1;
      for(; i > 0; i--)
      {
         DynamicObject dyno;
         mArray->push_back(dyno);
      }
   }

   return (*mArray)[index];
}

DynamicObject& DynamicObjectImpl::append()
{
   return (*this)[length()];
}

void DynamicObjectImpl::setType(DynamicObjectType type)
{
   if(mType != type)
   {
      switch(type)
      {
         case String:
            *this = getString();
            break;
         case Boolean:
            *this = getBoolean();
            break;
         case Int32:
            *this = getInt32();
            break;
         case UInt32:
            *this = getUInt32();
            break;
         case Int64:
            *this = getInt64();
            break;
         case UInt64:
            *this = getUInt64();
            break;
         case Double:
            *this = getDouble();
            break;
         case Map:
            {
               freeData();
               mType = Map;
               mMap = new ObjectMap();
            }
            break;
         case Array:
            {
               freeData();
               mType = Array;
               mArray = new ObjectArray();
            }
            break;
      }
   }
}

DynamicObjectType DynamicObjectImpl::getType()
{
   return mType;
}

const char* DynamicObjectImpl::getString()
{
   const char* rval;

   if(mType == String)
   {
      if(mString != NULL)
      {
         // use existing string
         rval = mString;
      }
      else
      {
         // only duplicate blank string upon request
         rval = mString = strdup("");
      }
   }
   else
   {
      // convert type as appropriate
      switch(mType)
      {
         case Boolean:
            mStringValue = (char*)realloc(mStringValue, 6);
            snprintf(mStringValue, 6, "%s", (mBoolean ? "true" : "false"));
            break;
         case Int32:
            mStringValue = (char*)realloc(mStringValue, 12);
            snprintf(mStringValue, 12, "%i", mInt32);
            break;
         case UInt32:
            mStringValue = (char*)realloc(mStringValue, 11);
            snprintf(mStringValue, 11, "%u", mUInt32);
            break;
         case Int64:
            mStringValue = (char*)realloc(mStringValue, 22);
            snprintf(mStringValue, 22, "%lli", mInt64);
            break;
         case UInt64:
            mStringValue = (char*)realloc(mStringValue, 21);
            snprintf(mStringValue, 21, "%llu", mUInt64);
            break;
         case Double:
            // use default precision of 6
            // X.000000e+00 = 11 places to right of decimal
            mStringValue = (char*)realloc(mStringValue, 50);
            snprintf(mStringValue, 50, "%e", mDouble);
            break;
         default: /* Map, Array, ... */
            {
               if(mStringValue == NULL)
               {
                  // duplicate blank string
                  mStringValue = strdup("");
               }
               else
               {
                  // set null-terminator to first character
                  mStringValue[0] = 0;
               }
            }
            break;
      }

      // return generated value
      rval = mStringValue;
   }

   return rval;
}

bool DynamicObjectImpl::getBoolean()
{
   bool rval;

   switch(mType)
   {
      case Boolean:
         rval = mBoolean;
         break;
      case String:
         rval = (mString == NULL) ? false : (strcmp(mString, "true") == 0);
         break;
      case Int32:
         rval = (mInt32 == 1);
         break;
      case UInt32:
         rval = (mUInt32 == 1);
         break;
      case Int64:
         rval = (mInt64 == 1);
         break;
      case UInt64:
         rval = (mUInt64 == 1);
         break;
      case Double:
         rval = (mDouble == 1);
         break;
      default:
         rval = false;
         break;
   }

   return rval;
}

int DynamicObjectImpl::getInt32()
{
   int rval;

   switch(mType)
   {
      case Int32:
         rval = mInt32;
         break;
      case String:
         rval = (mString == NULL) ? 0 : strtol(mString, NULL, 10);
         break;
      case Boolean:
         rval = mBoolean ? 1 : 0;
         break;
      case UInt32:
         rval = (int)mUInt32;
         break;
      case Int64:
         rval = (int)mInt64;
         break;
      case UInt64:
         rval = (int)mUInt64;
         break;
      case Double:
         rval = (int)mDouble;
         break;
      default:
         rval = 0;
         break;
   }

   return rval;
}

unsigned int DynamicObjectImpl::getUInt32()
{
   unsigned int rval;

   switch(mType)
   {
      case UInt32:
         rval = mUInt32;
         break;
      case String:
         rval = (mString == NULL) ? 0 : strtoul(mString, NULL, 10);
         break;
      case Boolean:
         rval = mBoolean ? 1 : 0;
         break;
      case Int32:
         rval = (mInt32 < 0) ? 0 : mInt32;
         break;
      case Int64:
         rval = (mInt64 < 0) ? 0 : (unsigned int)mInt64;
         break;
      case UInt64:
         rval = (unsigned int)mUInt64;
         break;
      case Double:
         rval = (unsigned int)mDouble;
         break;
      default:
         rval = 0;
         break;
   }

   return rval;
}

long long DynamicObjectImpl::getInt64()
{
   long long rval;

   switch(mType)
   {
      case Int64:
         rval = mInt64;
         break;
      case String:
         rval = (mString == NULL) ? 0 : strtoll(mString, NULL, 10);
         break;
      case Boolean:
         rval = mBoolean ? 1 : 0;
         break;
      case Int32:
         rval = mInt32;
         break;
      case UInt32:
         rval = mUInt32;
         break;
      case UInt64:
         rval = (long long)mUInt64;
         break;
      case Double:
         rval = (long long)mDouble;
         break;
      default:
         rval = 0;
         break;
   }

   return rval;
}

unsigned long long DynamicObjectImpl::getUInt64()
{
   unsigned long long rval;

   switch(mType)
   {
      case UInt64:
         rval = mUInt64;
         break;
      case String:
         rval = (mString == NULL) ? 0 : strtoull(mString, NULL, 10);
         break;
      case Boolean:
         rval = mBoolean ? 1 : 0;
         break;
      case Int32:
         rval = (mInt32 < 0) ? 0 : mInt32;
         break;
      case UInt32:
         rval = mUInt32;
         break;
      case Int64:
         rval = (mInt64 < 0) ? 0 : mInt64;
         break;
      case Double:
         rval = mDouble;
         break;
      default:
         rval = 0;
         break;
   }

   return rval;
}

double DynamicObjectImpl::getDouble()
{
   double rval;

   switch(mType)
   {
      case Double:
         rval = mDouble;
         break;
      case String:
         rval = (mString == NULL) ? 0 : strtod(mString, NULL);
         break;
      case Boolean:
         rval = mBoolean ? 1 : 0;
         break;
      case Int32:
         rval = mInt32;
         break;
      case UInt32:
         rval = mUInt32;
         break;
      case Int64:
         rval = mInt64;
         break;
      case UInt64:
         rval = mUInt64;
         break;
      default:
         rval = 0;
         break;
   }

   return rval;
}

bool DynamicObjectImpl::hasMember(const char* name)
{
   bool rval = false;

   if(mType == Map)
   {
      ObjectMap::iterator i = mMap->find(name);
      rval = (i != mMap->end());
   }

   return rval;
}

DynamicObject DynamicObjectImpl::removeMember(const char* name)
{
   DynamicObject rval(NULL);

   if(mType == Map)
   {
      ObjectMap::iterator i = mMap->find(name);
      if(i != mMap->end())
      {
         // clean up key and remove map entry
         free((char*)i->first);
         rval = i->second;
         mMap->erase(i);
      }
   }

   return rval;
}

void DynamicObjectImpl::clear()
{
   switch(mType)
   {
      case String:
         *this = "";
         break;
      case Boolean:
         *this = false;
         break;
      case Int32:
         *this = (int)0;
         break;
      case UInt32:
         *this = (unsigned int)0;
         break;
      case Int64:
         *this = (long long)0;
         break;
      case UInt64:
         *this = (unsigned long long)0;
         break;
      case Double:
         *this = (double)0.0;
         break;
      case Map:
         freeMapKeys();
         mMap->clear();
         break;
      case Array:
         mArray->clear();
         break;
   }
}

int DynamicObjectImpl::length()
{
   int rval = 0;

   switch(mType)
   {
      case String:
         if(mString != NULL)
         {
            rval = strlen(getString());
         }
         break;
      case Boolean:
         rval = 1;
         break;
      case Int32:
      case UInt32:
         rval = sizeof(unsigned int);
         break;
      case Int64:
      case UInt64:
         rval = sizeof(unsigned long long);
         break;
      case Double:
         rval = sizeof(double);
         break;
      case Map:
         rval = mMap->size();
         break;
      case Array:
         rval = mArray->size();
         break;
   }

   return rval;
}
<|endoftext|>


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

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

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

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

#include <iostream>

#include "itkCenteredAffineTransform.h"
#include "itkImage.h"
#include "vnl/vnl_vector_fixed.h"

typedef  itk::Matrix<double,2,2>   MatrixType;
typedef  itk::Vector<double,2>     VectorType;

namespace
{

void PrintVector( const VectorType & v )
{
  for( unsigned int i=0; i<VectorType::Dimension; i++)
  {
    std::cout << v[i] << ", ";
  }
  std::cout << std::endl;
}
}

int itkCenteredAffineTransformTest(int, char *[])
{

    int any = 0;       // Any errors detected in testing?

    MatrixType                   matrix2;
    MatrixType                   inverse2;
    VectorType                   vector2;

    int i, j;

    /* FIXME: This code exercises most of the methods but doesn't
       actually check that the results are correct. */

    /* Create a 2D identity transformation and show its parameters */
    typedef itk::Point<double,6> ParametersType;
    typedef itk::Matrix<double,2,6> JacobianType;

    typedef itk::CenteredAffineTransform<double,2> Affine2DType;
    Affine2DType::Pointer id2 = Affine2DType::New();
    matrix2 = id2->GetMatrix();
    vector2 = id2->GetOffset();
    std::cout << "Matrix from instantiating an identity transform:"
              << std::endl << matrix2;
    std::cout << "Vector from instantiating an identity transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Create and show a simple 2D transform from given parameters */
    matrix2[0][0] = 1;
    matrix2[0][1] = 2;
    matrix2[1][0] = 3;
    matrix2[1][1] = 4;
    vector2[0] = 5;
    vector2[1] = 6;

    Affine2DType::Pointer aff2 = Affine2DType::New();
    aff2->SetMatrix( matrix2 );
    aff2->SetOffset( vector2 );
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++)
            matrix2[i][j] = 0.0;
        vector2[i]    = 0.0;
    }
    std::cout << "Instantiation of a given 2D transform:" << std::endl;
    aff2->Print( std::cout );

    inverse2 = aff2->GetInverseMatrix();
    std::cout << "Inverse matrix for the given transform:"
              << std::endl << inverse2;

    /* Set parameters of a 2D transform */
    matrix2[0][0] = 6;
    matrix2[0][1] = 5;
    matrix2[1][0] = 4;
    matrix2[1][1] = 3;
    vector2[0] = 2;
    vector2[1] = 1;
    aff2->SetMatrix(matrix2);
    aff2->SetOffset(vector2);
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++)
            matrix2[i][j] = 0.0;
        vector2[i]    = 0.0;
    }
    matrix2 = aff2->GetMatrix();
    vector2 = aff2->GetOffset();
    std::cout << "Setting the matrix in an existing transform:"
              << std::endl << matrix2;
    std::cout << "Setting the offset in an existing  transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Try composition of two transformations */
    aff2->Compose( aff2 );
    std::cout << "Result of a composition:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a translation */
    VectorType trans;
    trans[0] = 1;
    trans[1] = 2;
    aff2->Translate(trans);
    std::cout << "Result of a translation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with an isotropic scaling */
    aff2->Scale(.3, 1);
    std::cout << "Result of isotropic scaling:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with an anisotropic scaling */
    VectorType scale;
    scale[0] = .3;
    scale[1] = .2;
    aff2->Scale(scale);
    std::cout << "Result of anisotropic scaling:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a general N-D rotation */
    aff2->Rotate(0, 1, 0.57, 1);
    std::cout << "Result of general rotation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a 2-D rotation */
    aff2->Rotate(0, 1, -0.57, 1);
    std::cout << "Result of 2-D rotation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a shear */
    aff2->Shear(1, 0, .2);
    std::cout << "Result of shear:" << std::endl;
    aff2->Print( std::cout );

    /* Transform a point */
    itk::Point<double, 2> u2, v2;
    u2[0] = 3;
    u2[1] = 5;
    v2 = aff2->TransformPoint(u2);
    std::cout << "Transform a point:" << std::endl
              << v2[0] << " , " << v2[1] << std::endl;

    /* Back transform a point */
    v2 = aff2->BackTransform(u2);
    std::cout << "Back transform a point:" << std::endl
              << v2[0] << " , " << v2[1] << std::endl;

    /* Transform a vnl_vector */
    vnl_vector_fixed<double, 2> x2, y2;
    x2[0] = 1;
    x2[1] = 2;
    y2 = aff2->TransformVector(x2);
    std::cout << "Transform a vnl_vector:" << std::endl
              << y2[0] << " , " << y2[1] << std::endl;

    /* Back transform a vector */
    y2 = aff2->BackTransform(x2);
    std::cout << "Back transform a vnl_vector:" << std::endl
              << y2[0] << " , " << y2[1] << std::endl;

    /* Transform a vector */
    itk::Vector<double, 2> u3, v3;
    u3[0] = 3;
    u3[1] = 5;
    v3 = aff2->TransformVector(u3);
    std::cout << "Transform a vector:" << std::endl
              << v3[0] << " , " << v3[1] << std::endl;

    /* Back transform a vector */
    v3 = aff2->BackTransform(u3);
    std::cout << "Back transform a vector :" << std::endl
              << v3[0] << " , " << v3[1] << std::endl;

    /* Transform a Covariant vector */
    itk::Vector<double, 2> u4, v4;
    u4[0] = 3;
    u4[1] = 5;
    v4 = aff2->TransformVector(u4);
    std::cout << "Transform a Covariant vector:" << std::endl
              << v4[0] << " , " << v4[1] << std::endl;

    /* Back transform a vector */
    v4 = aff2->BackTransform(u4);
    std::cout << "Back transform a vector :" << std::endl
              << v4[0] << " , " << v4[1] << std::endl;

    /* Create a 3D transform and rotate in 3D */
    typedef itk::CenteredAffineTransform<double,3> Affine3DType;
    Affine3DType::Pointer aff3 = Affine3DType::New();
    itk::Vector<double,3> axis;
    axis[0] = .707;
    axis[1] = .707;
    axis[2] = .707;
    aff3->Rotate3D(axis, 1.0, 1);
    std::cout << "Create and rotate a 3D transform:" << std::endl;
    aff3->Print( std::cout );

    /* Generate inverse transform */
    Affine3DType::Pointer inv3 = Affine3DType::New();
    if(!aff3->GetInverse(inv3))
      {
      std::cout << "Cannot create inverse transformation" << std::endl;
      }
    std::cout << "Create an inverse transformation:" << std::endl;
    inv3->Print( std::cout );

    /* Create an image for testing index<->physical transforms */
    std::cout << "Creating image for testing index<->physical transforms"
              << std::endl;
    double spacing[3] = {1.0, 2.0, 3.0};
    double origin [3] = {4.0, 5.0, 6.0};
    itk::Image<unsigned char, 3>::Pointer
        image =itk::Image<unsigned char, 3>::New();
    image->SetOrigin (origin);
    image->SetSpacing(spacing);

    /* Test output of GetJacobian */
    Affine3DType::Pointer jaff = Affine3DType::New();
    Affine3DType::MatrixType jaffMatrix = jaff->GetMatrix();
    Affine3DType::OffsetType jaffVector = jaff->GetOffset();

    Affine3DType::InputPointType jpoint;
    jpoint[0] = 5.0;
    jpoint[1] = 10.0;
    jpoint[2] = 15.0;
    Affine3DType::JacobianType jaffJacobian = jaff->GetJacobian( jpoint );

    std::cout << "GetJacobian: " << std::endl;
    std::cout << jaffJacobian << std::endl;

    return any;
}
<commit_msg>BUG: Removed tests for deprecated member function<commit_after>/*=========================================================================

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

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

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

#include <iostream>

#include "itkCenteredAffineTransform.h"
#include "itkImage.h"
#include "vnl/vnl_vector_fixed.h"

typedef  itk::Matrix<double,2,2>   MatrixType;
typedef  itk::Vector<double,2>     VectorType;

namespace
{

void PrintVector( const VectorType & v )
{
  for( unsigned int i=0; i<VectorType::Dimension; i++)
  {
    std::cout << v[i] << ", ";
  }
  std::cout << std::endl;
}
}

int itkCenteredAffineTransformTest(int, char *[])
{

    int any = 0;       // Any errors detected in testing?

    MatrixType                   matrix2;
    MatrixType                   inverse2;
    VectorType                   vector2;

    int i, j;

    /* FIXME: This code exercises most of the methods but doesn't
       actually check that the results are correct. */

    /* Create a 2D identity transformation and show its parameters */
    typedef itk::Point<double,6> ParametersType;
    typedef itk::Matrix<double,2,6> JacobianType;

    typedef itk::CenteredAffineTransform<double,2> Affine2DType;
    Affine2DType::Pointer id2 = Affine2DType::New();
    matrix2 = id2->GetMatrix();
    vector2 = id2->GetOffset();
    std::cout << "Matrix from instantiating an identity transform:"
              << std::endl << matrix2;
    std::cout << "Vector from instantiating an identity transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Create and show a simple 2D transform from given parameters */
    matrix2[0][0] = 1;
    matrix2[0][1] = 2;
    matrix2[1][0] = 3;
    matrix2[1][1] = 4;
    vector2[0] = 5;
    vector2[1] = 6;

    Affine2DType::Pointer aff2 = Affine2DType::New();
    aff2->SetMatrix( matrix2 );
    aff2->SetOffset( vector2 );
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++)
            matrix2[i][j] = 0.0;
        vector2[i]    = 0.0;
    }
    std::cout << "Instantiation of a given 2D transform:" << std::endl;
    aff2->Print( std::cout );

    inverse2 = aff2->GetInverseMatrix();
    std::cout << "Inverse matrix for the given transform:"
              << std::endl << inverse2;

    /* Set parameters of a 2D transform */
    matrix2[0][0] = 6;
    matrix2[0][1] = 5;
    matrix2[1][0] = 4;
    matrix2[1][1] = 3;
    vector2[0] = 2;
    vector2[1] = 1;
    aff2->SetMatrix(matrix2);
    aff2->SetOffset(vector2);
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++)
            matrix2[i][j] = 0.0;
        vector2[i]    = 0.0;
    }
    matrix2 = aff2->GetMatrix();
    vector2 = aff2->GetOffset();
    std::cout << "Setting the matrix in an existing transform:"
              << std::endl << matrix2;
    std::cout << "Setting the offset in an existing  transform:"
              << std::endl;
    PrintVector( vector2 );

    /* Try composition of two transformations */
    aff2->Compose( aff2 );
    std::cout << "Result of a composition:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a translation */
    VectorType trans;
    trans[0] = 1;
    trans[1] = 2;
    aff2->Translate(trans);
    std::cout << "Result of a translation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with an isotropic scaling */
    aff2->Scale(.3, 1);
    std::cout << "Result of isotropic scaling:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with an anisotropic scaling */
    VectorType scale;
    scale[0] = .3;
    scale[1] = .2;
    aff2->Scale(scale);
    std::cout << "Result of anisotropic scaling:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a general N-D rotation */
    aff2->Rotate(0, 1, 0.57, 1);
    std::cout << "Result of general rotation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a 2-D rotation */
    aff2->Rotate(0, 1, -0.57, 1);
    std::cout << "Result of 2-D rotation:" << std::endl;
    aff2->Print( std::cout );

    /* Compose with a shear */
    aff2->Shear(1, 0, .2);
    std::cout << "Result of shear:" << std::endl;
    aff2->Print( std::cout );

    /* Transform a point */
    itk::Point<double, 2> u2, v2;
    u2[0] = 3;
    u2[1] = 5;
    v2 = aff2->TransformPoint(u2);
    std::cout << "Transform a point:" << std::endl
              << v2[0] << " , " << v2[1] << std::endl;

    ///* Back transform a point */
    //v2 = aff2->BackTransform(u2);
    //std::cout << "Back transform a point:" << std::endl
              //<< v2[0] << " , " << v2[1] << std::endl;

    /* Transform a vnl_vector */
    vnl_vector_fixed<double, 2> x2, y2;
    x2[0] = 1;
    x2[1] = 2;
    y2 = aff2->TransformVector(x2);
    std::cout << "Transform a vnl_vector:" << std::endl
              << y2[0] << " , " << y2[1] << std::endl;

    ///* Back transform a vector */
    //y2 = aff2->BackTransform(x2);
    //std::cout << "Back transform a vnl_vector:" << std::endl
              //<< y2[0] << " , " << y2[1] << std::endl;

    /* Transform a vector */
    itk::Vector<double, 2> u3, v3;
    u3[0] = 3;
    u3[1] = 5;
    v3 = aff2->TransformVector(u3);
    std::cout << "Transform a vector:" << std::endl
              << v3[0] << " , " << v3[1] << std::endl;

    ///* Back transform a vector */
    //v3 = aff2->BackTransform(u3);
    //std::cout << "Back transform a vector :" << std::endl
              //<< v3[0] << " , " << v3[1] << std::endl;

    /* Transform a Covariant vector */
    itk::Vector<double, 2> u4, v4;
    u4[0] = 3;
    u4[1] = 5;
    v4 = aff2->TransformVector(u4);
    std::cout << "Transform a Covariant vector:" << std::endl
              << v4[0] << " , " << v4[1] << std::endl;

    ///* Back transform a vector */
    //v4 = aff2->BackTransform(u4);
    //std::cout << "Back transform a vector :" << std::endl
              //<< v4[0] << " , " << v4[1] << std::endl;

    /* Create a 3D transform and rotate in 3D */
    typedef itk::CenteredAffineTransform<double,3> Affine3DType;
    Affine3DType::Pointer aff3 = Affine3DType::New();
    itk::Vector<double,3> axis;
    axis[0] = .707;
    axis[1] = .707;
    axis[2] = .707;
    aff3->Rotate3D(axis, 1.0, 1);
    std::cout << "Create and rotate a 3D transform:" << std::endl;
    aff3->Print( std::cout );

    /* Generate inverse transform */
    Affine3DType::Pointer inv3 = Affine3DType::New();
    if(!aff3->GetInverse(inv3))
      {
      std::cout << "Cannot create inverse transformation" << std::endl;
      }
    std::cout << "Create an inverse transformation:" << std::endl;
    inv3->Print( std::cout );

    /* Create an image for testing index<->physical transforms */
    std::cout << "Creating image for testing index<->physical transforms"
              << std::endl;
    double spacing[3] = {1.0, 2.0, 3.0};
    double origin [3] = {4.0, 5.0, 6.0};
    itk::Image<unsigned char, 3>::Pointer
        image =itk::Image<unsigned char, 3>::New();
    image->SetOrigin (origin);
    image->SetSpacing(spacing);

    /* Test output of GetJacobian */
    Affine3DType::Pointer jaff = Affine3DType::New();
    Affine3DType::MatrixType jaffMatrix = jaff->GetMatrix();
    Affine3DType::OffsetType jaffVector = jaff->GetOffset();

    Affine3DType::InputPointType jpoint;
    jpoint[0] = 5.0;
    jpoint[1] = 10.0;
    jpoint[2] = 15.0;
    Affine3DType::JacobianType jaffJacobian = jaff->GetJacobian( jpoint );

    std::cout << "GetJacobian: " << std::endl;
    std::cout << jaffJacobian << std::endl;

    return any;
}
<|endoftext|>


<commit_before>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif

#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"

namespace model
{
    class World
    {
        public:
            // constructor.
            World();

            // destructor.
            ~World();

            // this method renders the entire world, one shader at a time.
            void render();

            // this method sets a shader pointer.
            void set_pointer(GLuint shaderID, void* shader_pointer);

            // this method gets a shader pointer.
            void* get_pointer(GLuint shaderID);

            // this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
            GLuint get_shaderID();

        private:
            std::vector<void*> shader_pointer_vector;
            std::queue<GLuint> free_shaderID_queue;
    };

    class Shader
    {
        public:
            // constructor.
            Shader(ShaderStruct shader_struct);

            // destructor.
            ~Shader();

            // this method renders all species using this shader.
            void render();

            // this method sets a species pointer.
            void set_pointer(GLuint speciesID, void* species_pointer);

            // this method gets a species pointer.
            void* get_pointer(GLuint speciesID);

            // this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
            GLuint get_speciesID();

            // this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
            void switch_to_new_world(model::World *new_world_pointer);

            model::World *world_pointer;          // pointer to the world.

            GLuint shaderID;                      // shader ID, returned by `model::World->get_shaderID()`.

            std::string vertex_shader;            // filename of vertex shader.
            std::string fragment_shader;          // filename of fragment shader.

            GLuint programID;                     // shaders' programID, returned by `LoadShaders`.

        private:
            std::vector<void*> species_pointer_vector;
            std::queue<GLuint> free_speciesID_queue;

            const char *char_vertex_shader;
            const char *char_fragment_shader;
    };

    class Graph
    {
        public:
            // constructor.
            Graph();

            // destructor.
            ~Graph();

            // this method sets a node pointer.
            void set_pointer(GLuint nodeID, void* node_pointer);

            // this method gets a node pointer.
            void* get_pointer(GLuint nodeID);

            // this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
            GLuint get_nodeID();

        private:
            std::vector<void*> node_pointer_vector;
            std::queue<GLuint> free_nodeID_queue;
    };

    // `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
    // Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
    // The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
    class Node
    {
        public:
            // constructor.
            Node(NodeStruct node_struct);

            // destructor.
            ~Node();

            // this method creates a bidirectional link.
            // creating of bidirectional links is not possible before all nodes are created.
            void create_bidirectional_link(GLuint nodeID);

            // this method deletes a bidirectional link.
            // deleting of links is not possible before all nodes are created.
            void delete_bidirectional_link(GLuint nodeID);

            // this method transfers this node to a new graph.
            // links will not be changed.
            // all nodes that are to be transferred must be transferred separately.
            // before transfering any node to a new graph,
            // all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
            void transfer_to_new_graph(model::Graph *new_graph_pointer);

            GLuint nodeID;
            model::Graph *graph_pointer;

            // nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
            std::vector<GLuint> neighbor_nodeIDs;

        private:
            // this method creates an unidirectional link.
            // in the constructor only unidirectional links can be created.
            void create_unidirectional_link(GLuint nodeID);

            // this method deletes an unidirectional link.
            void delete_unidirectional_link(GLuint nodeID);

            glm::vec3 coordinate_vector;
    };

    class Species
    {
        public:
            // constructor.
            Species(SpeciesStruct species_struct);

            // destructor.
            ~Species();

            // this method renders all objects of this species.
            void render();

            // this method sets a object pointer.
            void set_pointer(GLuint objectID, void* object_pointer);

            // this method gets a object pointer.
            void* get_pointer(GLuint objectID);

            // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
            GLuint get_objectID();

            // this method sets pointer to this species to NULL, sets `shader_pointer` according to the input, and requests a new `speciesID` from the new shader.
            void switch_to_new_shader(model::Shader *new_shader_pointer);

            std::string texture_file_format;         // type of the model file, eg. `"bmp"`.
            std::string texture_filename;            // filename of the model file.
            std::string color_channel;               // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
            std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
            glm::vec3 lightPos;                      // light position.

            void *vertex_UV_pointer;                 // pointer to the vertex & UV species (not yet in use!).
            void *texture_pointer;                   // pointer to the texture species (not yet in use!).

            // The rest fields are created in the constructor.
            GLuint MatrixID;
            GLuint ViewMatrixID;
            GLuint ModelMatrixID;
            GLuint vertexPosition_modelspaceID;
            GLuint vertexUVID;
            GLuint vertexNormal_modelspaceID;

            std::vector<glm::vec3> vertices;       // vertices of the object.
            std::vector<glm::vec2> UVs;            // UVs of the object.
            std::vector<glm::vec3> normals;        // normals of the object.

            std::vector<GLuint> indices;           // the deleted vertices will be reused (though it is not required, if there's enough memory).
            std::vector<glm::vec3> indexed_vertices;
            std::vector<glm::vec2> indexed_UVs;
            std::vector<glm::vec3> indexed_normals;

            GLuint vertexbuffer;
            GLuint uvbuffer;
            GLuint normalbuffer;
            GLuint elementbuffer;

            glm::mat4 ProjectionMatrix;
            glm::mat4 ViewMatrix;
        private:
            model::Shader *shader_pointer;         // pointer to the shader.

            std::string model_file_format;         // type of the model file, eg. `"bmp"`.
            std::string model_filename;            // filename of the model file.
            GLuint speciesID;                      // species ID, returned by `model::World->get_speciesID()`.
            GLuint lightID;                        // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
            GLuint texture;                        // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
            GLuint textureID;                      // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
            const char *char_model_file_format;
            const char *char_model_filename;
            const char *char_texture_file_format;
            const char *char_texture_filename;
            const char *char_color_channel;

            std::vector<void*> object_pointer_vector;
            std::queue<GLuint> free_objectID_queue;
    };

    class Object
    {
        public:
            // constructor.
            Object(ObjectStruct object_struct);

            // destructor.
            ~Object();

            // this method renders this object.
            void render();

            // this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
            void switch_to_new_species(model::Species *new_species_pointer);

            model::Species *species_pointer;       // pointer to the species.

            GLuint objectID;                      // object ID, returned by `model::Species->get_objectID()`.

            bool has_entered;
            glm::vec3 coordinate_vector;           // rotate vector.
            GLfloat rotate_angle;                  // rotate angle.
            glm::vec3 rotate_vector;               // rotate vector.
            glm::vec3 translate_vector;            // translate vector.

            // The rest fields are created in the constructor.
            glm::mat4 model_matrix;                // model matrix.
            std::vector<glm::vec3> vertices;       // vertices of the object.
            std::vector<glm::vec2> UVs;            // UVs of the object.
            std::vector<glm::vec3> normals;        // normals of the object. not used at the moment.

            glm::mat4 MVP_matrix;                  // model view projection matrix.
    };
}

#endif
<commit_msg>`std::string texture_file_format` on `private`-muuttuja.<commit_after>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif

#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"

namespace model
{
    class World
    {
        public:
            // constructor.
            World();

            // destructor.
            ~World();

            // this method renders the entire world, one shader at a time.
            void render();

            // this method sets a shader pointer.
            void set_pointer(GLuint shaderID, void* shader_pointer);

            // this method gets a shader pointer.
            void* get_pointer(GLuint shaderID);

            // this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
            GLuint get_shaderID();

        private:
            std::vector<void*> shader_pointer_vector;
            std::queue<GLuint> free_shaderID_queue;
    };

    class Shader
    {
        public:
            // constructor.
            Shader(ShaderStruct shader_struct);

            // destructor.
            ~Shader();

            // this method renders all species using this shader.
            void render();

            // this method sets a species pointer.
            void set_pointer(GLuint speciesID, void* species_pointer);

            // this method gets a species pointer.
            void* get_pointer(GLuint speciesID);

            // this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
            GLuint get_speciesID();

            // this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
            void switch_to_new_world(model::World *new_world_pointer);

            model::World *world_pointer;          // pointer to the world.

            GLuint shaderID;                      // shader ID, returned by `model::World->get_shaderID()`.

            std::string vertex_shader;            // filename of vertex shader.
            std::string fragment_shader;          // filename of fragment shader.

            GLuint programID;                     // shaders' programID, returned by `LoadShaders`.

        private:
            std::vector<void*> species_pointer_vector;
            std::queue<GLuint> free_speciesID_queue;

            const char *char_vertex_shader;
            const char *char_fragment_shader;
    };

    class Graph
    {
        public:
            // constructor.
            Graph();

            // destructor.
            ~Graph();

            // this method sets a node pointer.
            void set_pointer(GLuint nodeID, void* node_pointer);

            // this method gets a node pointer.
            void* get_pointer(GLuint nodeID);

            // this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
            GLuint get_nodeID();

        private:
            std::vector<void*> node_pointer_vector;
            std::queue<GLuint> free_nodeID_queue;
    };

    // `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
    // Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
    // The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
    class Node
    {
        public:
            // constructor.
            Node(NodeStruct node_struct);

            // destructor.
            ~Node();

            // this method creates a bidirectional link.
            // creating of bidirectional links is not possible before all nodes are created.
            void create_bidirectional_link(GLuint nodeID);

            // this method deletes a bidirectional link.
            // deleting of links is not possible before all nodes are created.
            void delete_bidirectional_link(GLuint nodeID);

            // this method transfers this node to a new graph.
            // links will not be changed.
            // all nodes that are to be transferred must be transferred separately.
            // before transfering any node to a new graph,
            // all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
            void transfer_to_new_graph(model::Graph *new_graph_pointer);

            GLuint nodeID;
            model::Graph *graph_pointer;

            // nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
            std::vector<GLuint> neighbor_nodeIDs;

        private:
            // this method creates an unidirectional link.
            // in the constructor only unidirectional links can be created.
            void create_unidirectional_link(GLuint nodeID);

            // this method deletes an unidirectional link.
            void delete_unidirectional_link(GLuint nodeID);

            glm::vec3 coordinate_vector;
    };

    class Species
    {
        public:
            // constructor.
            Species(SpeciesStruct species_struct);

            // destructor.
            ~Species();

            // this method renders all objects of this species.
            void render();

            // this method sets a object pointer.
            void set_pointer(GLuint objectID, void* object_pointer);

            // this method gets a object pointer.
            void* get_pointer(GLuint objectID);

            // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
            GLuint get_objectID();

            // this method sets pointer to this species to NULL, sets `shader_pointer` according to the input, and requests a new `speciesID` from the new shader.
            void switch_to_new_shader(model::Shader *new_shader_pointer);

            std::string texture_filename;            // filename of the model file.
            std::string color_channel;               // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
            std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
            glm::vec3 lightPos;                      // light position.

            void *vertex_UV_pointer;                 // pointer to the vertex & UV species (not yet in use!).
            void *texture_pointer;                   // pointer to the texture species (not yet in use!).

            // The rest fields are created in the constructor.
            GLuint MatrixID;
            GLuint ViewMatrixID;
            GLuint ModelMatrixID;
            GLuint vertexPosition_modelspaceID;
            GLuint vertexUVID;
            GLuint vertexNormal_modelspaceID;

            std::vector<glm::vec3> vertices;       // vertices of the object.
            std::vector<glm::vec2> UVs;            // UVs of the object.
            std::vector<glm::vec3> normals;        // normals of the object.

            std::vector<GLuint> indices;           // the deleted vertices will be reused (though it is not required, if there's enough memory).
            std::vector<glm::vec3> indexed_vertices;
            std::vector<glm::vec2> indexed_UVs;
            std::vector<glm::vec3> indexed_normals;

            GLuint vertexbuffer;
            GLuint uvbuffer;
            GLuint normalbuffer;
            GLuint elementbuffer;

            glm::mat4 ProjectionMatrix;
            glm::mat4 ViewMatrix;
        private:
            model::Shader *shader_pointer;         // pointer to the shader.

            std::string model_file_format;         // type of the model file, eg. `"bmp"`.
            std::string model_filename;            // filename of the model file.
            std::string texture_file_format;       // type of the model file, eg. `"bmp"`.
            GLuint speciesID;                      // species ID, returned by `model::World->get_speciesID()`.
            GLuint lightID;                        // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
            GLuint texture;                        // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
            GLuint textureID;                      // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
            const char *char_model_file_format;
            const char *char_model_filename;
            const char *char_texture_file_format;
            const char *char_texture_filename;
            const char *char_color_channel;

            std::vector<void*> object_pointer_vector;
            std::queue<GLuint> free_objectID_queue;
    };

    class Object
    {
        public:
            // constructor.
            Object(ObjectStruct object_struct);

            // destructor.
            ~Object();

            // this method renders this object.
            void render();

            // this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
            void switch_to_new_species(model::Species *new_species_pointer);

            model::Species *species_pointer;       // pointer to the species.

            GLuint objectID;                      // object ID, returned by `model::Species->get_objectID()`.

            bool has_entered;
            glm::vec3 coordinate_vector;           // rotate vector.
            GLfloat rotate_angle;                  // rotate angle.
            glm::vec3 rotate_vector;               // rotate vector.
            glm::vec3 translate_vector;            // translate vector.

            // The rest fields are created in the constructor.
            glm::mat4 model_matrix;                // model matrix.
            std::vector<glm::vec3> vertices;       // vertices of the object.
            std::vector<glm::vec2> UVs;            // UVs of the object.
            std::vector<glm::vec3> normals;        // normals of the object. not used at the moment.

            glm::mat4 MVP_matrix;                  // model view projection matrix.
    };
}

#endif
<|endoftext|>