<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#include "caf/downstream_manager.hpp"

#include <functional>
#include <limits>

#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/scheduled_actor.hpp"
#include "caf/logger.hpp"
#include "caf/outbound_path.hpp"

namespace caf {

// -- constructors, destructors, and assignment operators ----------------------

downstream_manager::downstream_manager::path_visitor::~path_visitor() {
  // nop
}

downstream_manager::downstream_manager::path_predicate::~path_predicate() {
  // nop
}

downstream_manager::downstream_manager(stream_manager* parent)
    : parent_(parent) {
  // nop
}

downstream_manager::~downstream_manager() {
  // nop
}

// -- properties ---------------------------------------------------------------

scheduled_actor* downstream_manager::self() const noexcept {
  return parent_->self();
}

stream_manager* downstream_manager::parent() const noexcept {
  return parent_;
}

bool downstream_manager::terminal() const noexcept {
  return true;
}

// -- path management ----------------------------------------------------------

std::vector<stream_slot> downstream_manager::path_slots() {
  std::vector<stream_slot> xs;
  xs.reserve(num_paths());
  for_each_path([&](outbound_path& x) {
    xs.emplace_back(x.slots.sender);
  });
  return xs;
}

size_t downstream_manager::num_paths() const noexcept {
  return 0;
}

downstream_manager::path_ptr
downstream_manager::add_path(stream_slot slot, strong_actor_ptr target) {
  CAF_LOG_TRACE(CAF_ARG(slot) << CAF_ARG(target));
  unique_path_ptr ptr{new outbound_path(slot, std::move(target))};
  auto result = ptr.get();
  return insert_path(std::move(ptr)) ? result : nullptr;
}

bool downstream_manager::remove_path(stream_slot, error, bool) noexcept {
  return false;
}

downstream_manager::const_path_ptr
downstream_manager::path(stream_slot slot) const noexcept {
  // The `const` is restored when returning the pointer.
  return const_cast<downstream_manager&>(*this).path(slot);
}

auto downstream_manager::path(stream_slot) noexcept -> path_ptr {
  return nullptr;
}

bool downstream_manager::clean() const noexcept {
  auto pred = [](const outbound_path& x) {
    return x.clean();
  };
  return buffered() == 0 && all_paths(pred);
}

bool downstream_manager::clean(stream_slot slot) const noexcept {
  auto ptr = path(slot);
  return ptr != nullptr ? buffered(slot) == 0 && ptr->clean() : false;
}

void downstream_manager::close() {
  CAF_LOG_TRACE("");
  if (clean()) {
    for_each_path([&](outbound_path& x) { about_to_erase(&x, false, nullptr); });
    clear_paths();
  } else {
    for_each_path([&](outbound_path& x) { x.closing = true; });
  }
}

void downstream_manager::close(stream_slot slot) {
  CAF_LOG_TRACE(CAF_ARG(slot));
  if (clean(slot))
    remove_path(slot, none, false);
  else {
    auto ptr = path(slot);
    if (ptr != nullptr)
      ptr->closing = true;
  }
}

void downstream_manager::abort(error reason) {
  CAF_LOG_TRACE(CAF_ARG(reason));
  for_each_path([&](outbound_path& x) {
    auto tmp = reason;
    about_to_erase(&x, false, &tmp);
  });
  clear_paths();
}

size_t downstream_manager::min_credit() const {
  if (empty())
    return 0u;
  auto result = std::numeric_limits<size_t>::max();
  const_cast<downstream_manager*>(this)->for_each_path([&](outbound_path& x) {
    result = std::min(result, static_cast<size_t>(x.open_credit));
  });
  return result;
}

size_t downstream_manager::max_credit() const {
  size_t result = 0;
  const_cast<downstream_manager*>(this)->for_each_path([&](outbound_path& x) {
    result = std::max(result, static_cast<size_t>(x.open_credit));
  });
  return result;
}

size_t downstream_manager::total_credit() const {
  size_t result = 0;
  const_cast<downstream_manager*>(this)->for_each_path([&](outbound_path& x) {
    result += static_cast<size_t>(x.open_credit);
  });
  return result;
}

void downstream_manager::emit_batches() {
  // nop
}

void downstream_manager::force_emit_batches() {
  // nop
}

size_t downstream_manager::capacity() const noexcept {
  return std::numeric_limits<size_t>::max();
}

size_t downstream_manager::buffered() const noexcept {
  return 0;
}

size_t downstream_manager::buffered(stream_slot) const noexcept {
  return 0;
}

bool downstream_manager::stalled() const noexcept {
  auto no_credit = [](const outbound_path& x) {
    return x.open_credit == 0;
  };
  return capacity() == 0 && all_paths(no_credit);
}

void downstream_manager::clear_paths() {
  // nop
}

bool downstream_manager::insert_path(unique_path_ptr) {
  return false;
}

void downstream_manager::for_each_path_impl(path_visitor&) {
  // nop
}

bool downstream_manager::check_paths_impl(path_algorithm algo,
                                          path_predicate&) const noexcept {
  // Return the result for empty ranges as specified by the C++ standard.
  switch (algo) {
    default:
      CAF_ASSERT(algo == path_algorithm::all_of);
      return true;
    case path_algorithm::any_of:
      return false;
    case path_algorithm::none_of:
      return true;
  }
}

void downstream_manager::about_to_erase(outbound_path* ptr, bool silent,
                                      error* reason) {
  CAF_LOG_TRACE(CAF_ARG(ptr) << CAF_ARG(silent) << CAF_ARG(reason));
  if (!silent) {
    if (reason == nullptr)
      ptr->emit_regular_shutdown(self());
    else
      ptr->emit_irregular_shutdown(self(), std::move(*reason));
  }
}

} // namespace caf
<commit_msg>Close slots individually in close()<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#include "caf/downstream_manager.hpp"

#include <functional>
#include <limits>

#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/scheduled_actor.hpp"
#include "caf/logger.hpp"
#include "caf/outbound_path.hpp"

namespace caf {

// -- constructors, destructors, and assignment operators ----------------------

downstream_manager::downstream_manager::path_visitor::~path_visitor() {
  // nop
}

downstream_manager::downstream_manager::path_predicate::~path_predicate() {
  // nop
}

downstream_manager::downstream_manager(stream_manager* parent)
    : parent_(parent) {
  // nop
}

downstream_manager::~downstream_manager() {
  // nop
}

// -- properties ---------------------------------------------------------------

scheduled_actor* downstream_manager::self() const noexcept {
  return parent_->self();
}

stream_manager* downstream_manager::parent() const noexcept {
  return parent_;
}

bool downstream_manager::terminal() const noexcept {
  return true;
}

// -- path management ----------------------------------------------------------

std::vector<stream_slot> downstream_manager::path_slots() {
  std::vector<stream_slot> xs;
  xs.reserve(num_paths());
  for_each_path([&](outbound_path& x) {
    xs.emplace_back(x.slots.sender);
  });
  return xs;
}

size_t downstream_manager::num_paths() const noexcept {
  return 0;
}

downstream_manager::path_ptr
downstream_manager::add_path(stream_slot slot, strong_actor_ptr target) {
  CAF_LOG_TRACE(CAF_ARG(slot) << CAF_ARG(target));
  unique_path_ptr ptr{new outbound_path(slot, std::move(target))};
  auto result = ptr.get();
  return insert_path(std::move(ptr)) ? result : nullptr;
}

bool downstream_manager::remove_path(stream_slot, error, bool) noexcept {
  return false;
}

downstream_manager::const_path_ptr
downstream_manager::path(stream_slot slot) const noexcept {
  // The `const` is restored when returning the pointer.
  return const_cast<downstream_manager&>(*this).path(slot);
}

auto downstream_manager::path(stream_slot) noexcept -> path_ptr {
  return nullptr;
}

bool downstream_manager::clean() const noexcept {
  auto pred = [](const outbound_path& x) {
    return x.clean();
  };
  return buffered() == 0 && all_paths(pred);
}

bool downstream_manager::clean(stream_slot slot) const noexcept {
  auto ptr = path(slot);
  return ptr != nullptr ? buffered(slot) == 0 && ptr->clean() : false;
}

void downstream_manager::close() {
  CAF_LOG_TRACE("");
  auto slots = path_slots();
  for (auto slot : slots)
    close(slot);
}

void downstream_manager::close(stream_slot slot) {
  CAF_LOG_TRACE(CAF_ARG(slot));
  if (clean(slot))
    remove_path(slot, none, false);
  else {
    auto ptr = path(slot);
    if (ptr != nullptr)
      ptr->closing = true;
  }
}

void downstream_manager::abort(error reason) {
  CAF_LOG_TRACE(CAF_ARG(reason));
  for_each_path([&](outbound_path& x) {
    auto tmp = reason;
    about_to_erase(&x, false, &tmp);
  });
  clear_paths();
}

size_t downstream_manager::min_credit() const {
  if (empty())
    return 0u;
  auto result = std::numeric_limits<size_t>::max();
  const_cast<downstream_manager*>(this)->for_each_path([&](outbound_path& x) {
    result = std::min(result, static_cast<size_t>(x.open_credit));
  });
  return result;
}

size_t downstream_manager::max_credit() const {
  size_t result = 0;
  const_cast<downstream_manager*>(this)->for_each_path([&](outbound_path& x) {
    result = std::max(result, static_cast<size_t>(x.open_credit));
  });
  return result;
}

size_t downstream_manager::total_credit() const {
  size_t result = 0;
  const_cast<downstream_manager*>(this)->for_each_path([&](outbound_path& x) {
    result += static_cast<size_t>(x.open_credit);
  });
  return result;
}

void downstream_manager::emit_batches() {
  // nop
}

void downstream_manager::force_emit_batches() {
  // nop
}

size_t downstream_manager::capacity() const noexcept {
  return std::numeric_limits<size_t>::max();
}

size_t downstream_manager::buffered() const noexcept {
  return 0;
}

size_t downstream_manager::buffered(stream_slot) const noexcept {
  return 0;
}

bool downstream_manager::stalled() const noexcept {
  auto no_credit = [](const outbound_path& x) {
    return x.open_credit == 0;
  };
  return capacity() == 0 && all_paths(no_credit);
}

void downstream_manager::clear_paths() {
  // nop
}

bool downstream_manager::insert_path(unique_path_ptr) {
  return false;
}

void downstream_manager::for_each_path_impl(path_visitor&) {
  // nop
}

bool downstream_manager::check_paths_impl(path_algorithm algo,
                                          path_predicate&) const noexcept {
  // Return the result for empty ranges as specified by the C++ standard.
  switch (algo) {
    default:
      CAF_ASSERT(algo == path_algorithm::all_of);
      return true;
    case path_algorithm::any_of:
      return false;
    case path_algorithm::none_of:
      return true;
  }
}

void downstream_manager::about_to_erase(outbound_path* ptr, bool silent,
                                      error* reason) {
  CAF_LOG_TRACE(CAF_ARG(ptr) << CAF_ARG(silent) << CAF_ARG(reason));
  if (!silent) {
    if (reason == nullptr)
      ptr->emit_regular_shutdown(self());
    else
      ptr->emit_irregular_shutdown(self(), std::move(*reason));
  }
}

} // namespace caf
<|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.

#include "Examples/ExampleStapling/StaplerBehavior.h"

#include <boost/exception/to_string.hpp>

#include "Examples/ExampleStapling/StapleElement.h"
#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Graphics/SceneryRepresentation.h"
#include "SurgSim/Input/InputComponent.h"
#include "SurgSim/Physics/Constraint.h"
#include "SurgSim/Physics/ConstraintComponent.h"
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
#include "SurgSim/Physics/DeformableRepresentation.h"
#include "SurgSim/Physics/FixedRepresentationBilateral3D.h"
#include "SurgSim/Physics/Fem3DRepresentationBilateral3D.h"
#include "SurgSim/Physics/Localization.h"
#include "SurgSim/Physics/RigidCollisionRepresentation.h"
#include "SurgSim/Physics/RigidRepresentationBilateral3D.h"

using SurgSim::Physics::ConstraintImplementation;
using SurgSim::Physics::FixedRepresentationBilateral3D;
using SurgSim::Physics::RigidRepresentationBilateral3D;
using SurgSim::Physics::Fem3DRepresentationBilateral3D;
using SurgSim::Physics::Localization;

StaplerBehavior::StaplerBehavior(const std::string& name):
	SurgSim::Framework::Behavior(name),
	m_numElements(0),
	m_button1Index(-1),
	m_button1IndexCached(false),
	m_buttonPreviouslyPressed(false)
{
}

void StaplerBehavior::setInputComponent(std::shared_ptr<SurgSim::Input::InputComponent> inputComponent)
{
	m_from = inputComponent;
}

void StaplerBehavior::setRepresentation(
	 std::shared_ptr<SurgSim::Framework::Representation> staplerRepresentation)
{
	m_representation = staplerRepresentation;
}

void StaplerBehavior::setVirtualStaple(
	const std::array<std::shared_ptr<SurgSim::Collision::Representation>, 2>& virtualTeeth)
{
	m_virtualTeeth = virtualTeeth;
}

void StaplerBehavior::enableStaplingForSceneElement(std::string sceneElementName)
{
	m_stapleEnabledSceneElements.push_back(sceneElementName);
}

void StaplerBehavior::filterCollisionMapForStapleEnabledRepresentations(
	SurgSim::Collision::Representation::ContactMapType* collisionsMap)
{
	for (auto it = collisionsMap->begin(); it != collisionsMap->end();)
	{
		if (std::find(m_stapleEnabledSceneElements.begin(),
					  m_stapleEnabledSceneElements.end(),
					  (*it).first->getSceneElement()->getName()) == m_stapleEnabledSceneElements.end())
		{
			// Representation's scene element is not in the m_stapleEnabledSceneElements.
			it = collisionsMap->erase(it);
		}
		else
		{
			++it;
		}
	}
}

std::shared_ptr<SurgSim::Physics::Representation> StaplerBehavior::findCorrespondingPhysicsRepresentation(
	std::shared_ptr<SurgSim::Collision::Representation> collisionRepresentation)
{
	std::shared_ptr<SurgSim::Physics::Representation> physicsRepresentation = nullptr;

	// Check if the collisionRepresenation is for a Rigid body.
	std::shared_ptr<SurgSim::Physics::RigidCollisionRepresentation> rigidCollisionRepresentation =
		std::dynamic_pointer_cast<SurgSim::Physics::RigidCollisionRepresentation>(collisionRepresentation);

	if (rigidCollisionRepresentation != nullptr)
	{
		physicsRepresentation = rigidCollisionRepresentation->getRigidRepresentation();
	}
	else
	{
		// Check if the collisionRepresenation is for a deformable body.
		std::shared_ptr<SurgSim::Physics::DeformableCollisionRepresentation> deformableCollisionRepresentation =
			std::dynamic_pointer_cast<SurgSim::Physics::DeformableCollisionRepresentation>(collisionRepresentation);

		if (deformableCollisionRepresentation != nullptr)
		{
			physicsRepresentation = deformableCollisionRepresentation->getDeformableRepresentation();
		}
	}

	return physicsRepresentation;
}

void StaplerBehavior::filterCollisionMapForSupportedRepresentationTypes(
	SurgSim::Collision::Representation::ContactMapType* collisionsMap)
{
	for (auto it = collisionsMap->begin(); it != collisionsMap->end();)
	{
		if (findCorrespondingPhysicsRepresentation((*it).first) == nullptr)
		{
			// Representation type is not supported to be stapled.
			it = collisionsMap->erase(it);
		}
		else
		{
			++it;
		}
	}
}

std::shared_ptr<SurgSim::Physics::Constraint> StaplerBehavior::createBilateral3DConstraint(
	std::shared_ptr<SurgSim::Physics::Representation> stapleRep,
	std::shared_ptr<SurgSim::Physics::Representation> otherRep,
	SurgSim::Collision::Location contraintLocation)
{
	// Create a bilateral constraint between the physicsRepresentation and staple.
	// First find the points where the constraint is going to be applied.
	std::shared_ptr<Localization> stapleRepLocalization
		= stapleRep->createLocalization(contraintLocation);
	stapleRepLocalization->setRepresentation(stapleRep);

	std::shared_ptr<Localization> otherRepLocatization
		= otherRep->createLocalization(contraintLocation);
	otherRepLocatization->setRepresentation(otherRep);

	std::shared_ptr<SurgSim::Physics::Constraint> constraint = nullptr;

	// Create the Constraint with appropriate constraint implementation.
	switch (otherRep->getType())
	{
	case SurgSim::Physics::REPRESENTATION_TYPE_FIXED:
		constraint = std::make_shared<SurgSim::Physics::Constraint>(
						std::make_shared<SurgSim::Physics::ConstraintData>(),
						std::make_shared<RigidRepresentationBilateral3D>(),
						stapleRepLocalization,
						std::make_shared<FixedRepresentationBilateral3D>(),
						otherRepLocatization);
		break;

	case SurgSim::Physics::REPRESENTATION_TYPE_RIGID:
		constraint = std::make_shared<SurgSim::Physics::Constraint>(
						std::make_shared<SurgSim::Physics::ConstraintData>(),
						std::make_shared<RigidRepresentationBilateral3D>(),
						stapleRepLocalization,
						std::make_shared<RigidRepresentationBilateral3D>(),
						otherRepLocatization);
		break;

	case SurgSim::Physics::REPRESENTATION_TYPE_FEM3D:
		constraint = std::make_shared<SurgSim::Physics::Constraint>(
						std::make_shared<SurgSim::Physics::ConstraintData>(),
						std::make_shared<RigidRepresentationBilateral3D>(),
						stapleRepLocalization,
						std::make_shared<Fem3DRepresentationBilateral3D>(),
						otherRepLocatization);
		break;
	}

	return constraint;
}

void StaplerBehavior::createStaple()
{
	// Create the staple (not added to the scene right now).
	auto staple = std::make_shared<StapleElement>("staple_" + boost::to_string(m_numElements++));
	staple->setPose(m_representation->getPose());

	int toothId = 0;
	bool stapleAdded = false;
	for (auto virtualTooth = m_virtualTeeth.begin(); virtualTooth != m_virtualTeeth.end(); ++virtualTooth)
	{
		// The virtual tooth could be in contact with any number of objects in the scene.
		// Get its collisionMap.
		SurgSim::Collision::Representation::ContactMapType collisionsMap = (*virtualTooth)->getCollisions();

		// If the virtualTooth has no collision, continue to next loop iteration.
		if (collisionsMap.empty())
		{
			continue;
		}

		// Remove representations from the collision map that are not enabled to be stapled.
		filterCollisionMapForStapleEnabledRepresentations(&collisionsMap);

		// If the collision map is emptied after filtering, continue to next loop iteration.
		if (collisionsMap.empty())
		{
			continue;
		}

		// Filter the map based on supported Physics::Represention types.
		filterCollisionMapForSupportedRepresentationTypes(&collisionsMap);

		// If the collision map is emptied after filtering, continue to next loop iteration.
		if (collisionsMap.empty())
		{
			continue;
		}

		// Find the row (representation, list of contacts) in the map that the virtualTooth has most
		// collision pairs with.
		SurgSim::Collision::Representation::ContactMapType::value_type targetRepresentationContacts
			= *std::max_element(collisionsMap.begin(), collisionsMap.end(),
								[](const SurgSim::Collision::Representation::ContactMapType::value_type& lhs,
								   const SurgSim::Collision::Representation::ContactMapType::value_type& rhs)
								{ return lhs.second.size() < rhs.second.size(); });

		// Iterate through the list of collision pairs to find a contact with the deepest penetration.
		std::shared_ptr<SurgSim::Collision::Contact> targetContact
			= *std::max_element(targetRepresentationContacts.second.begin(), targetRepresentationContacts.second.end(),
								[](const std::shared_ptr<SurgSim::Collision::Contact>& lhs,
								   const std::shared_ptr<SurgSim::Collision::Contact>& rhs)
								{ return lhs->depth < rhs->depth; });

		// Create the staple, before creating the constaint with the staple.
		// The staple is created with no collision representation, because it is going to be constrained.
		if (!stapleAdded)
		{
			staple->setHasCollisionRepresentation(false);
			getScene()->addSceneElement(staple);
			// The gravity of the staple is disabled to prevent it from rotating about the line
			// connecting the two points of constraints on the staple.
			staple->getComponents<SurgSim::Physics::Representation>()[0]->setIsGravityEnabled(false);
			stapleAdded = true;
		}

		// Find the corresponding Phsyics::Representation for the target Collision::Representation.
		// Note that the targetPhysicsRepresentation will NOT be a nullptr, because the
		// collisionsMap was filtered earlier to remove Representations that returned nullptr
		// when the function findCorrespondingPhysicsRepresentation was called.
		// (see filterCollisionMapForStapleEnabledRepresentations above).
		std::shared_ptr<SurgSim::Physics::Representation> targetPhysicsRepresentation =
			findCorrespondingPhysicsRepresentation(targetRepresentationContacts.first);

		// Create a bilateral constraint between the targetPhysicsRepresentation and the staple.
		std::shared_ptr<SurgSim::Physics::Constraint> constraint =
			createBilateral3DConstraint(staple->getComponents<SurgSim::Physics::Representation>()[0],
										targetPhysicsRepresentation,
										targetContact->penetrationPoints.first);

		if (constraint == nullptr)
		{
			SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger())
				<< "Failed to create constaint between staple and "
				<< targetRepresentationContacts.first->getSceneElement()->getName()
				<< ". This might be because the createBilateral3DConstraint is not supporting the Physics Type: "
				<< targetPhysicsRepresentation->getType();
			continue;
		}

		// Create a component to store this constraint.
		std::shared_ptr<SurgSim::Physics::ConstraintComponent> constraintComponent =
			std::make_shared<SurgSim::Physics::ConstraintComponent>(
				"Bilateral3DConstraint" + boost::to_string(toothId++));

		constraintComponent->setConstraint(constraint);
		staple->addComponent(constraintComponent);
	}

	if (!stapleAdded)
	{
		// Create the staple element.
		getScene()->addSceneElement(staple);
	}
}

void StaplerBehavior::update(double dt)
{
	SurgSim::DataStructures::DataGroup dataGroup;
	m_from->getData(&dataGroup);

	// Get the button1 index.
	if (!m_button1IndexCached)
	{
		m_button1Index = dataGroup.booleans().getIndex("button1");
		m_button1IndexCached = true;
	}

	// Check if the stapler is being pressed.
	bool button1 = false;
	dataGroup.booleans().get(m_button1Index, &button1);

	if (button1 && !m_buttonPreviouslyPressed)
	{
		createStaple();
	}

	m_buttonPreviouslyPressed = button1;
}

int StaplerBehavior::getTargetManagerType() const
{
	return SurgSim::Framework::MANAGER_TYPE_INPUT;
}

bool StaplerBehavior::doInitialize()
{
	SURGSIM_ASSERT(m_from) << "StaplerBehavior: no InputComponent held.";
	return true;
}

bool StaplerBehavior::doWakeUp()
{
	return true;
}
<commit_msg>Enable StpleElement collision before adding to scene.<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.

#include "Examples/ExampleStapling/StaplerBehavior.h"

#include <boost/exception/to_string.hpp>

#include "Examples/ExampleStapling/StapleElement.h"
#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Graphics/SceneryRepresentation.h"
#include "SurgSim/Input/InputComponent.h"
#include "SurgSim/Physics/Constraint.h"
#include "SurgSim/Physics/ConstraintComponent.h"
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
#include "SurgSim/Physics/DeformableRepresentation.h"
#include "SurgSim/Physics/FixedRepresentationBilateral3D.h"
#include "SurgSim/Physics/Fem3DRepresentationBilateral3D.h"
#include "SurgSim/Physics/Localization.h"
#include "SurgSim/Physics/RigidCollisionRepresentation.h"
#include "SurgSim/Physics/RigidRepresentationBilateral3D.h"

using SurgSim::Physics::ConstraintImplementation;
using SurgSim::Physics::FixedRepresentationBilateral3D;
using SurgSim::Physics::RigidRepresentationBilateral3D;
using SurgSim::Physics::Fem3DRepresentationBilateral3D;
using SurgSim::Physics::Localization;

StaplerBehavior::StaplerBehavior(const std::string& name):
	SurgSim::Framework::Behavior(name),
	m_numElements(0),
	m_button1Index(-1),
	m_button1IndexCached(false),
	m_buttonPreviouslyPressed(false)
{
}

void StaplerBehavior::setInputComponent(std::shared_ptr<SurgSim::Input::InputComponent> inputComponent)
{
	m_from = inputComponent;
}

void StaplerBehavior::setRepresentation(
	 std::shared_ptr<SurgSim::Framework::Representation> staplerRepresentation)
{
	m_representation = staplerRepresentation;
}

void StaplerBehavior::setVirtualStaple(
	const std::array<std::shared_ptr<SurgSim::Collision::Representation>, 2>& virtualTeeth)
{
	m_virtualTeeth = virtualTeeth;
}

void StaplerBehavior::enableStaplingForSceneElement(std::string sceneElementName)
{
	m_stapleEnabledSceneElements.push_back(sceneElementName);
}

void StaplerBehavior::filterCollisionMapForStapleEnabledRepresentations(
	SurgSim::Collision::Representation::ContactMapType* collisionsMap)
{
	for (auto it = collisionsMap->begin(); it != collisionsMap->end();)
	{
		if (std::find(m_stapleEnabledSceneElements.begin(),
					  m_stapleEnabledSceneElements.end(),
					  (*it).first->getSceneElement()->getName()) == m_stapleEnabledSceneElements.end())
		{
			// Representation's scene element is not in the m_stapleEnabledSceneElements.
			it = collisionsMap->erase(it);
		}
		else
		{
			++it;
		}
	}
}

std::shared_ptr<SurgSim::Physics::Representation> StaplerBehavior::findCorrespondingPhysicsRepresentation(
	std::shared_ptr<SurgSim::Collision::Representation> collisionRepresentation)
{
	std::shared_ptr<SurgSim::Physics::Representation> physicsRepresentation = nullptr;

	// Check if the collisionRepresenation is for a Rigid body.
	std::shared_ptr<SurgSim::Physics::RigidCollisionRepresentation> rigidCollisionRepresentation =
		std::dynamic_pointer_cast<SurgSim::Physics::RigidCollisionRepresentation>(collisionRepresentation);

	if (rigidCollisionRepresentation != nullptr)
	{
		physicsRepresentation = rigidCollisionRepresentation->getRigidRepresentation();
	}
	else
	{
		// Check if the collisionRepresenation is for a deformable body.
		std::shared_ptr<SurgSim::Physics::DeformableCollisionRepresentation> deformableCollisionRepresentation =
			std::dynamic_pointer_cast<SurgSim::Physics::DeformableCollisionRepresentation>(collisionRepresentation);

		if (deformableCollisionRepresentation != nullptr)
		{
			physicsRepresentation = deformableCollisionRepresentation->getDeformableRepresentation();
		}
	}

	return physicsRepresentation;
}

void StaplerBehavior::filterCollisionMapForSupportedRepresentationTypes(
	SurgSim::Collision::Representation::ContactMapType* collisionsMap)
{
	for (auto it = collisionsMap->begin(); it != collisionsMap->end();)
	{
		if (findCorrespondingPhysicsRepresentation((*it).first) == nullptr)
		{
			// Representation type is not supported to be stapled.
			it = collisionsMap->erase(it);
		}
		else
		{
			++it;
		}
	}
}

std::shared_ptr<SurgSim::Physics::Constraint> StaplerBehavior::createBilateral3DConstraint(
	std::shared_ptr<SurgSim::Physics::Representation> stapleRep,
	std::shared_ptr<SurgSim::Physics::Representation> otherRep,
	SurgSim::Collision::Location contraintLocation)
{
	// Create a bilateral constraint between the physicsRepresentation and staple.
	// First find the points where the constraint is going to be applied.
	std::shared_ptr<Localization> stapleRepLocalization
		= stapleRep->createLocalization(contraintLocation);
	stapleRepLocalization->setRepresentation(stapleRep);

	std::shared_ptr<Localization> otherRepLocatization
		= otherRep->createLocalization(contraintLocation);
	otherRepLocatization->setRepresentation(otherRep);

	std::shared_ptr<SurgSim::Physics::Constraint> constraint = nullptr;

	// Create the Constraint with appropriate constraint implementation.
	switch (otherRep->getType())
	{
	case SurgSim::Physics::REPRESENTATION_TYPE_FIXED:
		constraint = std::make_shared<SurgSim::Physics::Constraint>(
						std::make_shared<SurgSim::Physics::ConstraintData>(),
						std::make_shared<RigidRepresentationBilateral3D>(),
						stapleRepLocalization,
						std::make_shared<FixedRepresentationBilateral3D>(),
						otherRepLocatization);
		break;

	case SurgSim::Physics::REPRESENTATION_TYPE_RIGID:
		constraint = std::make_shared<SurgSim::Physics::Constraint>(
						std::make_shared<SurgSim::Physics::ConstraintData>(),
						std::make_shared<RigidRepresentationBilateral3D>(),
						stapleRepLocalization,
						std::make_shared<RigidRepresentationBilateral3D>(),
						otherRepLocatization);
		break;

	case SurgSim::Physics::REPRESENTATION_TYPE_FEM3D:
		constraint = std::make_shared<SurgSim::Physics::Constraint>(
						std::make_shared<SurgSim::Physics::ConstraintData>(),
						std::make_shared<RigidRepresentationBilateral3D>(),
						stapleRepLocalization,
						std::make_shared<Fem3DRepresentationBilateral3D>(),
						otherRepLocatization);
		break;
	}

	return constraint;
}

void StaplerBehavior::createStaple()
{
	// Create the staple (not added to the scene right now).
	auto staple = std::make_shared<StapleElement>("staple_" + boost::to_string(m_numElements++));
	staple->setPose(m_representation->getPose());

	int toothId = 0;
	bool stapleAdded = false;
	for (auto virtualTooth = m_virtualTeeth.begin(); virtualTooth != m_virtualTeeth.end(); ++virtualTooth)
	{
		// The virtual tooth could be in contact with any number of objects in the scene.
		// Get its collisionMap.
		SurgSim::Collision::Representation::ContactMapType collisionsMap = (*virtualTooth)->getCollisions();

		// If the virtualTooth has no collision, continue to next loop iteration.
		if (collisionsMap.empty())
		{
			continue;
		}

		// Remove representations from the collision map that are not enabled to be stapled.
		filterCollisionMapForStapleEnabledRepresentations(&collisionsMap);

		// If the collision map is emptied after filtering, continue to next loop iteration.
		if (collisionsMap.empty())
		{
			continue;
		}

		// Filter the map based on supported Physics::Represention types.
		filterCollisionMapForSupportedRepresentationTypes(&collisionsMap);

		// If the collision map is emptied after filtering, continue to next loop iteration.
		if (collisionsMap.empty())
		{
			continue;
		}

		// Find the row (representation, list of contacts) in the map that the virtualTooth has most
		// collision pairs with.
		SurgSim::Collision::Representation::ContactMapType::value_type targetRepresentationContacts
			= *std::max_element(collisionsMap.begin(), collisionsMap.end(),
								[](const SurgSim::Collision::Representation::ContactMapType::value_type& lhs,
								   const SurgSim::Collision::Representation::ContactMapType::value_type& rhs)
								{ return lhs.second.size() < rhs.second.size(); });

		// Iterate through the list of collision pairs to find a contact with the deepest penetration.
		std::shared_ptr<SurgSim::Collision::Contact> targetContact
			= *std::max_element(targetRepresentationContacts.second.begin(), targetRepresentationContacts.second.end(),
								[](const std::shared_ptr<SurgSim::Collision::Contact>& lhs,
								   const std::shared_ptr<SurgSim::Collision::Contact>& rhs)
								{ return lhs->depth < rhs->depth; });

		// Create the staple, before creating the constaint with the staple.
		// The staple is created with no collision representation, because it is going to be constrained.
		if (!stapleAdded)
		{
			staple->setHasCollisionRepresentation(false);
			getScene()->addSceneElement(staple);
			// The gravity of the staple is disabled to prevent it from rotating about the line
			// connecting the two points of constraints on the staple.
			staple->getComponents<SurgSim::Physics::Representation>()[0]->setIsGravityEnabled(false);
			stapleAdded = true;
		}

		// Find the corresponding Phsyics::Representation for the target Collision::Representation.
		// Note that the targetPhysicsRepresentation will NOT be a nullptr, because the
		// collisionsMap was filtered earlier to remove Representations that returned nullptr
		// when the function findCorrespondingPhysicsRepresentation was called.
		// (see filterCollisionMapForStapleEnabledRepresentations above).
		std::shared_ptr<SurgSim::Physics::Representation> targetPhysicsRepresentation =
			findCorrespondingPhysicsRepresentation(targetRepresentationContacts.first);

		// Create a bilateral constraint between the targetPhysicsRepresentation and the staple.
		std::shared_ptr<SurgSim::Physics::Constraint> constraint =
			createBilateral3DConstraint(staple->getComponents<SurgSim::Physics::Representation>()[0],
										targetPhysicsRepresentation,
										targetContact->penetrationPoints.first);

		if (constraint == nullptr)
		{
			SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger())
				<< "Failed to create constaint between staple and "
				<< targetRepresentationContacts.first->getSceneElement()->getName()
				<< ". This might be because the createBilateral3DConstraint is not supporting the Physics Type: "
				<< targetPhysicsRepresentation->getType();
			continue;
		}

		// Create a component to store this constraint.
		std::shared_ptr<SurgSim::Physics::ConstraintComponent> constraintComponent =
			std::make_shared<SurgSim::Physics::ConstraintComponent>(
				"Bilateral3DConstraint" + boost::to_string(toothId++));

		constraintComponent->setConstraint(constraint);
		staple->addComponent(constraintComponent);
	}

	if (!stapleAdded)
	{
		// Create the staple element.
		staple->setHasCollisionRepresentation(true);
		getScene()->addSceneElement(staple);
	}
}

void StaplerBehavior::update(double dt)
{
	SurgSim::DataStructures::DataGroup dataGroup;
	m_from->getData(&dataGroup);

	// Get the button1 index.
	if (!m_button1IndexCached)
	{
		m_button1Index = dataGroup.booleans().getIndex("button1");
		m_button1IndexCached = true;
	}

	// Check if the stapler is being pressed.
	bool button1 = false;
	dataGroup.booleans().get(m_button1Index, &button1);

	if (button1 && !m_buttonPreviouslyPressed)
	{
		createStaple();
	}

	m_buttonPreviouslyPressed = button1;
}

int StaplerBehavior::getTargetManagerType() const
{
	return SurgSim::Framework::MANAGER_TYPE_INPUT;
}

bool StaplerBehavior::doInitialize()
{
	SURGSIM_ASSERT(m_from) << "StaplerBehavior: no InputComponent held.";
	return true;
}

bool StaplerBehavior::doWakeUp()
{
	return true;
}
<|endoftext|>


<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef LUABIND_RETURN_REFERENCE_TO_POLICY_HPP_INCLUDED
#define LUABIND_RETURN_REFERENCE_TO_POLICY_HPP_INCLUDED

#include <luabind/detail/policy.hpp>    // for index_map, policy_cons, etc
#include <luabind/lua_include.hpp>      // for lua_State, lua_pushnil, etc

namespace luabind {
	namespace detail {

		struct cpp_to_lua;
		struct null_type;

		template<class T>
		struct return_reference_to_converter;

		template<>
		struct return_reference_to_converter<cpp_to_lua>
		{
			template<class T>
			void to_lua(lua_State* L, const T&)
			{
				lua_pushnil(L);
			}
		};

		template< unsigned int N >
		struct return_reference_to_policy : detail::converter_policy_has_postcall_tag
		{
			template<typename StackIndexList>
			static void postcall(lua_State* L, int results, StackIndexList)
			{
				lua_pushvalue(L, meta::get<StackIndexList, N>::value);
				lua_replace(L, meta::get<StackIndexList, 0>::value + results);
			}

			template<class T, class Direction>
			struct specialize
			{
				using type = return_reference_to_converter<Direction>;
			};
		};

	}

	template<unsigned int N>
	using return_reference_to = meta::type_list<converter_policy_injector<0, detail::return_reference_to_policy<N>>>;

}

#endif // LUABIND_RETURN_REFERENCE_TO_POLICY_HPP_INCLUDED

<commit_msg>Fixed build with using of Lua 5.3 (becaues of comma in the template, the preprocessor gets be confused. Extra breckets are fixing this)<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef LUABIND_RETURN_REFERENCE_TO_POLICY_HPP_INCLUDED
#define LUABIND_RETURN_REFERENCE_TO_POLICY_HPP_INCLUDED

#include <luabind/detail/policy.hpp>    // for index_map, policy_cons, etc
#include <luabind/lua_include.hpp>      // for lua_State, lua_pushnil, etc

namespace luabind {
	namespace detail {

		struct cpp_to_lua;
		struct null_type;

		template<class T>
		struct return_reference_to_converter;

		template<>
		struct return_reference_to_converter<cpp_to_lua>
		{
			template<class T>
			void to_lua(lua_State* L, const T&)
			{
				lua_pushnil(L);
			}
		};

		template< unsigned int N >
		struct return_reference_to_policy : detail::converter_policy_has_postcall_tag
		{
			template<typename StackIndexList>
			static void postcall(lua_State* L, int results, StackIndexList)
			{
				lua_pushvalue(L, (meta::get<StackIndexList, N>::value));
				lua_replace(L, (meta::get<StackIndexList, 0>::value + results));
			}

			template<class T, class Direction>
			struct specialize
			{
				using type = return_reference_to_converter<Direction>;
			};
		};

	}

	template<unsigned int N>
	using return_reference_to = meta::type_list<converter_policy_injector<0, detail::return_reference_to_policy<N>>>;

}

#endif // LUABIND_RETURN_REFERENCE_TO_POLICY_HPP_INCLUDED

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestHyperOctreeDual.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/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 notice for more information.

=========================================================================*/
// This example demonstrates how to use a vtkHyperOctreeSampleFunction and
// apply a vtkHyperOctreeCutter filter on it.
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/

// If WRITE_RESULT is defined, the result of the surface filter is saved.
//#define WRITE_RESULT

#include "vtkActor.h"
#include "vtkCellData.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include <assert.h>
#include "vtkLookupTable.h"
#include "vtkPolyData.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkHyperOctreeDualGridContourFilter.h"
#include "vtkContourFilter.h"
#include "vtkProperty.h"
#include "vtkDataSetMapper.h"
#include "vtkPolyDataMapper.h"
#include "vtkTimerLog.h"
#include "vtkHyperOctreeFractalSource.h"
#include "vtkSphere.h"
#include "vtkCamera.h"

int TestHyperOctreeDual(int argc, char* argv[])
{
  // Standard rendering classes
  vtkRenderer *renderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(renderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  vtkTimerLog *timer=vtkTimerLog::New();

  // 3D
  vtkHyperOctreeFractalSource* source3d = vtkHyperOctreeFractalSource::New();
  source3d->SetMaximumNumberOfIterations(17);
  source3d->SetMaximumLevel(7);
  source3d->SetMinimumLevel(3);

  cout<<"update source3d..."<<endl;
  timer->StartTimer();
  source3d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"source updated3d"<<endl;
  cout<<"source3d time="<<timer->GetElapsedTime()<<" s"<<endl;

  vtkHyperOctreeDualGridContourFilter *contour3d;
  contour3d = vtkHyperOctreeDualGridContourFilter::New();
  contour3d->SetNumberOfContours(2);
  contour3d->SetValue(0,4.5);
  contour3d->SetValue(1,10.5);

  contour3d->SetInputConnection(0,source3d->GetOutputPort(0));
  cout<<"update contour3d..."<<endl;
  timer->StartTimer();
  contour3d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"contour3d updated"<<endl;
  cout<<"contour3d time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lut3d = vtkLookupTable::New();
  lut3d->SetHueRange (0.667, 0.0);

  vtkPolyDataMapper *mapper3d = vtkPolyDataMapper::New();
  mapper3d->SetInputConnection(0, contour3d->GetOutputPort(0) );
  mapper3d->SetScalarRange(0, 17);

  vtkActor *actor3d = vtkActor::New();
  actor3d->SetMapper(mapper3d);
  renderer->AddActor(actor3d);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writer3d=vtkXMLPolyDataWriter::New();
  writer3d->SetInputConnection(0,contour3d->GetOutputPort(0));
  writer3d->SetFileName("contour3d.vtp");
  writer3d->SetDataModeToAscii();
  writer3d->Write();
  writer3d->Delete();
#endif // #ifdef WRITE_RESULT

  // 2D
  vtkHyperOctreeFractalSource* source2d = vtkHyperOctreeFractalSource::New();
  source2d->SetDimension(2);
  source2d->SetMaximumNumberOfIterations(17);
  source2d->SetMaximumLevel(7);
  source2d->SetMinimumLevel(4);

  cout<<"update source2d..."<<endl;
  timer->StartTimer();
  source2d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"source updated2d"<<endl;
  cout<<"source2d time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lut2d = vtkLookupTable::New();
  lut2d->SetHueRange (0.667, 0.0);

  vtkDataSetMapper *mapper2d = vtkDataSetMapper::New();
  mapper2d->SetInputConnection(0,source2d->GetOutputPort(0));
  mapper2d->SetLookupTable(lut2d);
  mapper2d->SetScalarRange(0, 17);

  vtkActor *actor2d = vtkActor::New();
  actor2d->SetPosition(2.5,0,0);
  actor2d->SetMapper(mapper2d);
  actor2d->GetProperty()->SetRepresentationToWireframe();
  renderer->AddActor(actor2d);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writer2d=vtkXMLPolyDataWriter::New();
  writer2d->SetInputConnection(0,source2d->GetOutputPort(0));
  writer2d->SetFileName("dual2d.vtp");
  writer2d->SetDataModeToAscii();
  writer2d->Write();
  writer2d->Delete();
#endif // #ifdef WRITE_RESULT

  // Contour using data set API.
  vtkContourFilter *contourDS=vtkContourFilter::New();
  contourDS->SetNumberOfContours(2);
  contourDS->SetValue(0,4.5);
  contourDS->SetValue(1,10.5);

  contourDS->SetInputConnection(0,source3d->GetOutputPort(0));
  cout<<"update contour1d..."<<endl;
  timer->StartTimer();
  contourDS->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"contour data set updated"<<endl;
  cout<<"contour data set time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lutDS = vtkLookupTable::New();
  lutDS->SetHueRange (0.667, 0.0);

  vtkPolyDataMapper *mapperDS = vtkPolyDataMapper::New();
  mapperDS->SetInputConnection(0,contourDS->GetOutputPort(0));
  mapperDS->SetLookupTable(lutDS);
  mapperDS->SetScalarRange(0, 17);

  vtkActor *actorDS = vtkActor::New();
  actorDS->SetPosition(2.5,2.5,0);
  actorDS->SetMapper(mapperDS);
  renderer->AddActor(actorDS);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writerDS=vtkXMLPolyDataWriter::New();
  writerDS->SetInputConnection(0,contourDS->GetOutputPort(0));
  writerDS->SetFileName("contourDS.vtp");
  writerDS->SetDataModeToAscii();
  writerDS->Write();
  writerDS->Delete();
#endif // #ifdef WRITE_RESULT

  // Standard testing code.
  renderer->SetBackground(0.5,0.5,0.5);
  renWin->SetSize(300,300);
  vtkCamera *cam=renderer->GetActiveCamera();
  renderer->ResetCamera();
  cam->Azimuth(180);
  cam->Zoom(1.35);
  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin );
  if (retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  // Cleanup
  renderer->Delete();
  renWin->Delete();
  iren->Delete();

  contourDS->Delete();
  lutDS->Delete();
  mapperDS->Delete();
  actorDS->Delete();

  source3d->Delete();
  contour3d->Delete();
  mapper3d->Delete();
  actor3d->Delete();
  lut3d->Delete();

  source2d->Delete();
  mapper2d->Delete();
  actor2d->Delete();
  lut2d->Delete();

  timer->Delete();

  return !retVal;
}
<commit_msg>BUG: Order of the triangles must have shaded them black on some systems.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestHyperOctreeDual.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/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 notice for more information.

=========================================================================*/
// This example demonstrates how to use a vtkHyperOctreeSampleFunction and
// apply a vtkHyperOctreeCutter filter on it.
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/

// If WRITE_RESULT is defined, the result of the surface filter is saved.
//#define WRITE_RESULT

#include "vtkActor.h"
#include "vtkCellData.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include <assert.h>
#include "vtkLookupTable.h"
#include "vtkPolyData.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkHyperOctreeDualGridContourFilter.h"
#include "vtkContourFilter.h"
#include "vtkProperty.h"
#include "vtkDataSetMapper.h"
#include "vtkPolyDataMapper.h"
#include "vtkTimerLog.h"
#include "vtkHyperOctreeFractalSource.h"
#include "vtkSphere.h"
#include "vtkCamera.h"

int TestHyperOctreeDual(int argc, char* argv[])
{
  // Standard rendering classes
  vtkRenderer *renderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(renderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  vtkTimerLog *timer=vtkTimerLog::New();

  // 3D
  vtkHyperOctreeFractalSource* source3d = vtkHyperOctreeFractalSource::New();
  source3d->SetMaximumNumberOfIterations(17);
  source3d->SetMaximumLevel(7);
  source3d->SetMinimumLevel(3);

  cout<<"update source3d..."<<endl;
  timer->StartTimer();
  source3d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"source updated3d"<<endl;
  cout<<"source3d time="<<timer->GetElapsedTime()<<" s"<<endl;

  vtkHyperOctreeDualGridContourFilter *contour3d;
  contour3d = vtkHyperOctreeDualGridContourFilter::New();
  contour3d->SetNumberOfContours(2);
  contour3d->SetValue(0,4.5);
  contour3d->SetValue(1,10.5);

  contour3d->SetInputConnection(0,source3d->GetOutputPort(0));
  cout<<"update contour3d..."<<endl;
  timer->StartTimer();
  contour3d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"contour3d updated"<<endl;
  cout<<"contour3d time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lut3d = vtkLookupTable::New();
  lut3d->SetHueRange (0.667, 0.0);

  vtkPolyDataMapper *mapper3d = vtkPolyDataMapper::New();
  mapper3d->SetInputConnection(0, contour3d->GetOutputPort(0) );
  mapper3d->SetScalarRange(0, 17);

  vtkActor *actor3d = vtkActor::New();
  actor3d->SetMapper(mapper3d);
  renderer->AddActor(actor3d);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writer3d=vtkXMLPolyDataWriter::New();
  writer3d->SetInputConnection(0,contour3d->GetOutputPort(0));
  writer3d->SetFileName("contour3d.vtp");
  writer3d->SetDataModeToAscii();
  writer3d->Write();
  writer3d->Delete();
#endif // #ifdef WRITE_RESULT

  // 2D
  vtkHyperOctreeFractalSource* source2d = vtkHyperOctreeFractalSource::New();
  source2d->SetDimension(2);
  source2d->SetMaximumNumberOfIterations(17);
  source2d->SetMaximumLevel(7);
  source2d->SetMinimumLevel(4);

  cout<<"update source2d..."<<endl;
  timer->StartTimer();
  source2d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"source updated2d"<<endl;
  cout<<"source2d time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lut2d = vtkLookupTable::New();
  lut2d->SetHueRange (0.667, 0.0);

  vtkDataSetMapper *mapper2d = vtkDataSetMapper::New();
  mapper2d->SetInputConnection(0,source2d->GetOutputPort(0));
  mapper2d->SetLookupTable(lut2d);
  mapper2d->SetScalarRange(0, 17);

  vtkActor *actor2d = vtkActor::New();
  actor2d->SetPosition(2.5,0,0);
  actor2d->SetOrientation(180,0,0);
  actor2d->SetMapper(mapper2d);
  actor2d->GetProperty()->SetRepresentationToWireframe();
  renderer->AddActor(actor2d);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writer2d=vtkXMLPolyDataWriter::New();
  writer2d->SetInputConnection(0,source2d->GetOutputPort(0));
  writer2d->SetFileName("dual2d.vtp");
  writer2d->SetDataModeToAscii();
  writer2d->Write();
  writer2d->Delete();
#endif // #ifdef WRITE_RESULT

  // Contour using data set API.
  vtkContourFilter *contourDS=vtkContourFilter::New();
  contourDS->SetNumberOfContours(2);
  contourDS->SetValue(0,4.5);
  contourDS->SetValue(1,10.5);

  contourDS->SetInputConnection(0,source3d->GetOutputPort(0));
  cout<<"update contour1d..."<<endl;
  timer->StartTimer();
  contourDS->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"contour data set updated"<<endl;
  cout<<"contour data set time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lutDS = vtkLookupTable::New();
  lutDS->SetHueRange (0.667, 0.0);

  vtkPolyDataMapper *mapperDS = vtkPolyDataMapper::New();
  mapperDS->SetInputConnection(0,contourDS->GetOutputPort(0));
  mapperDS->SetLookupTable(lutDS);
  mapperDS->SetScalarRange(0, 17);

  vtkActor *actorDS = vtkActor::New();
  actorDS->SetPosition(2.5,2.5,0);
  actorDS->SetMapper(mapperDS);
  renderer->AddActor(actorDS);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writerDS=vtkXMLPolyDataWriter::New();
  writerDS->SetInputConnection(0,contourDS->GetOutputPort(0));
  writerDS->SetFileName("contourDS.vtp");
  writerDS->SetDataModeToAscii();
  writerDS->Write();
  writerDS->Delete();
#endif // #ifdef WRITE_RESULT

  // Standard testing code.
  renderer->SetBackground(0.5,0.5,0.5);
  renWin->SetSize(300,300);
  vtkCamera *cam=renderer->GetActiveCamera();
  renderer->ResetCamera();
  cam->Azimuth(180);
  cam->Zoom(1.35);
  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin );
  if (retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  // Cleanup
  renderer->Delete();
  renWin->Delete();
  iren->Delete();

  contourDS->Delete();
  lutDS->Delete();
  mapperDS->Delete();
  actorDS->Delete();

  source3d->Delete();
  contour3d->Delete();
  mapper3d->Delete();
  actor3d->Delete();
  lut3d->Delete();

  source2d->Delete();
  mapper2d->Delete();
  actor2d->Delete();
  lut2d->Delete();

  timer->Delete();

  return !retVal;
}
<|endoftext|>


<commit_before>//
//  download_manager.cpp
//  Cooloi_Assets_Downloader
//
//  Created by ESoragoto on 11/17/15.
//
//

#include "download_manager.hpp"
#include "assets_downloader.hpp"

#include "SimpleAudioEngine.h"

#include <iostream>
#include <string>
#include <fstream>
#include <regex>
#include <stdio.h>

#include "json/rapidjson.h"
#include "json/document.h"
#include "json/writer.h"
#include "json/stringbuffer.h"

using namespace cocos2d;
using namespace CocosDenshion;

#pragma mark - Initialization
DownloadManager::DownloadManager():
downloader_(nullptr),
stage_(DownloadStage ::kNull),
conf_(),
finished_(),
update_(),
now_downloading_(""),
now_number_(0)
{
} // DownloadManager

DownloadManager::~DownloadManager()
{
    if (downloader_)
        CC_SAFE_DELETE(downloader_);
} // ~DownloadManager

// on "init" you need to initialize your instance
bool DownloadManager::init()
{
    if ( !Scene::init() )
    {
        return false;
    }

    LoadConfig();

    InitDownloader();

    LoadUpdate();

    return true;
} // init

DownloadManager* DownloadManager::Create()
{
    auto d = new DownloadManager();
    if(d->init())
        return d;
    CC_SAFE_DELETE(d);
    return nullptr;
} // Create

void DownloadManager::update(float dt)
{
    if (downloader_->downloading()) return;

    unscheduleUpdate();

    switch (downloader()->status())
    {
//        case AssetsManager::ErrorCode::CREATE_FILE:
//        {
//            return;
//        }
//            break;

        case AssetsManager::ErrorCode::UNCOMPRESS:
        {
            set_stage(DownloadStage::kNull);
            return;
        }
            break;

        case AssetsManager::ErrorCode::NETWORK:
        {
            set_stage(DownloadStage::kNull);
            return;
        }
            break;

        default:
            break;
    }

    switch (stage())
    {
        case DownloadStage ::kLoadUpdate:
        {
            CheckUpdate();
        }
            break;

        case DownloadStage ::kGetUpdate:
        {
            GetUpdate();
        }
            break;

        default:
            break;
    }
} // update

#pragma mark - Member Function
#pragma mark -stage

int DownloadManager::LoadConfig()
{
    log("\nStage : Load config info.\n");
    set_stage(DownloadStage::kLoadConfig);
    auto ret = 0;
    std::string file_name = "";
//#if COCOS2D_DEBUG
//    file_name = "Cooloi_ASDL_DEBUG.conf";
////    file_name = "Cooloi_ASDL.conf";
//#else
//    file_name = "Cooloi_ASDL.conf";
//#endif
//    ret = ReadConf(file_name,
//                   conf_);

#if COCOS2D_DEBUG
    file_name = "Cooloi_ASDL_DEBUG.json";
    //    file_name = "Cooloi_ASDL.json";
#else
    file_name = "Cooloi_ASDL.json";
#endif
    ret = ReadConfigFromJson(file_name,
                             conf_);

    if (0 != ret)
    {
        set_stage(DownloadStage::kNull);
    }
    return ret;
} // LoadConfig

int DownloadManager::InitDownloader()
{
    log("\nStage : Initialization Downloader.\n");
    set_stage(DownloadStage::kInitDownloader);
    downloader_ = new AssetsDownloader(conf_["URL"],
                                       conf_["VER"],
                                       conf_["DIR"],
                                       std::stoi(conf_["TRY"]));
    downloader_->Init();
    return 0;
} // InitDownloader

int DownloadManager::LoadUpdate()
{
    log("\nStage : Download update info.\n");
    set_stage(DownloadStage::kLoadUpdate);
    Download(conf_["URL"]);
    return 0;
} // LoadUpdate

int DownloadManager::CheckUpdate()
{
    log("\nStage : Check update info.\n");
    set_stage(DownloadStage::kCheckUpdate);
    auto ret = 0;
    if ("" != now_downloading_) push_finished(now_downloading());
//    ret = ReadConf(conf_["NAME"], pkg_map_);
//    ret = ReadConf(conf_["LOCAL_NAME"], loc_map_);

    ret = ReadConfigFromJson(conf_["NAME"], pkg_map_);
    ret = ReadConfigFromJson(conf_["LOCAL_NAME"], loc_map_);

    for (auto p : pkg_map())
    {
        if (p.second != loc_map_[p.first])
        {
            push_update(p.first);
        }
    }

    if (update().empty())
    {
        set_stage(DownloadStage::kFinished);
    }
    else
    {
        log("New package find!");
//        GetUpdate();
    }
    return ret;
} // CheckUpdate

int DownloadManager::GetUpdate()
{
    log("\nStage : Get update package.\n");
    set_stage(DownloadStage::kGetUpdate);
    auto ret = 0;
    if ("" != now_downloading_) push_finished(now_downloading());

    for (auto u : update())
    {
        auto jump = false;
        for (auto f : finished())
        {
            if (u == f)
            {
                jump = true;
                break;
            }
        }
        if (jump) continue;

        set_now_downloading(u);
        Download(conf().at("SER") + pkg_map_[u]);
        break;
    }

    if (update().size() == finished().size())
    {
        std::string content = "#loacl list\n";
        for (auto p : pkg_map())
        {
            content += (p.first + " = " + p.second + "\n");
        }
        WriteFile(conf_["LOCAL_NAME"], content);
        auto s = FileUtils::getInstance()->getStringFromFile(conf_["LOCAL_NAME"]);
        log("%s", s.c_str());
        set_stage(DownloadStage::kFinished);
    }

    return ret;
} // GetUpdate

void DownloadManager::Close()
{
    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
} // Close

#pragma mark -other

int DownloadManager::Download(const std::string pkg_url)
{
    log("Request to download resource : %s", pkg_url.c_str());
    downloader_->Download(pkg_url);

    scheduleUpdate();
    return 0;
} // Download

int DownloadManager::ReadConf(const std::string file_name,
                              std::map<std::string, std::string> &conf_map)
{
    log("Read config file : %s", file_name.c_str());
    std::string path_with_file = "";
    FindPathWithFile(file_name, path_with_file);
    if ("" == path_with_file)
    {
        WriteFile(file_name, "");
        return 1;
    }

    auto str = FileUtils::getInstance()->getStringFromFile(file_name);
    log("getStringFromFile\n%s",str.c_str());

    std::ifstream in_file(path_with_file);
    if(in_file.fail())
        return 1001;

    std::string str_by_line = "";
    while (std::getline(in_file, str_by_line))
    {
        std::string arg;
        std::string value;
        ConfRegex(str_by_line, arg, value);
        conf_map[arg] = value;
    }
    return 0;
} // ReadConf

int DownloadManager::ConfRegex(const std::string str,
                               std::string &arg,
                               std::string &value)
{
    log("Regex line : %s", str.c_str());
    std::regex rgx("^(\\w+)\\s*\\=\\s*([^\\s]+)$");
    std::smatch match;

    if (std::regex_search(str.begin(), str.end(), match, rgx))
    {
        for(auto q : match)
        {
            log("\t%s", q.str().c_str());
        }
        log("----");
        arg = match[1].str();
        value = match[2].str();
    }
    return 0;
} // ConfRegex

int DownloadManager::ReadConfigFromJson(const std::string file_name,
                                        std::map<std::string, std::string> &conf_map)
{
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);
    auto str = FileUtils::getInstance()->getStringFromFile(file_with_path.c_str());
    if ("" == str)
    {
        log("Open file %s fail!", file_name.c_str());
        set_stage(DownloadStage::kFileNotFound);
        return 1404;
    }
    rapidjson::Document d;
    d.Parse<0>(str.c_str());
    if(!d.IsObject())
    {
        set_stage(DownloadStage::kFileNotFound);
        return 1404;
    }
    for (auto iter = d.MemberBegin() ; iter != d.MemberEnd() ; iter++)
    {
        log("\tKey\t : %s\n\tValue : %s\n-----",
            iter->name.GetString(),
            iter->value.GetString());
        conf_map[iter->name.GetString()] = iter->value.GetString();
    }
    return 0;
}

int DownloadManager::WriteConfigToJson(const std::string file_name,
                                       std::map<std::string, std::string> &conf_map)
{
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);

    rapidjson::Document d;
    d.SetObject();
    for(auto c : conf_map)
    {
        log("write config name is %s, value is %s", c.first.c_str(), c.second.c_str());
        rapidjson::Value name(rapidjson::kStringType);
        name.SetString(c.first.c_str(), (int)c.first.length());

        rapidjson::Value value(rapidjson::kStringType);
        value.SetString(c.second.c_str(), (int)c.second.length());

        d.AddMember(name, value, d.GetAllocator());
    }

    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> write(buffer);
    d.Accept(write);

    log("now write config is %s", buffer.GetString());

    if ("" == file_with_path)
    {
        file_with_path = FileUtils::getInstance()->getWritablePath() + file_name;
    }

    FILE* file = fopen(file_with_path.c_str(), "wb");
    if (file)
    {
        fputs(buffer.GetString(), file);
        fclose(file);
    }
    return 0;
}

int DownloadManager::ReadFile(const std::string file_name,
                              std::string &content)
{
    log("Preparing Read file : %s", file_name.c_str());
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);
    if ("" == file_with_path)
        return 1404;

    log("Full path: %s", file_with_path.c_str());
    auto file = FileUtils::getInstance()->getStringFromFile(file_with_path);

    if ("" == file)
    {
        std::ifstream infile(file_with_path);

        if (infile.fail())
        {
            log("Open file fail, file name: %s", file_name.c_str());
            return 1001;
        }

        std::string str((std::istreambuf_iterator<char>(infile)),
                        std::istreambuf_iterator<char>());
        file = str.c_str();
        infile.close();
    }

    log("open file:\n----\n%s\n----", file.c_str());
    content = file;
    return 0;
} // ReadFile

int DownloadManager::WriteFile(const std::string file_name,
                               const std::string content)
{
    log("Preparing write file : %s", file_name.c_str());
    std::string file_to_write = "";
    FindPathWithFile(file_name, file_to_write);
    if ("" == file_to_write)
    {
        file_to_write = FileUtils::getInstance()->getWritablePath();
//        file_to_write += conf_["Dir"];
        file_to_write += file_name;
    }

    log("Write path : %s", file_to_write.c_str());
    std::ofstream outfile;
    outfile.open(file_to_write);
    if (outfile.fail())
    {
        log("Open file fail, file name: %s", file_name.c_str());
        return 1001;
    }
    std::string str = "#" + file_name + "\n" + content;
    outfile << str;
    log("write file with fstream : \n----\n%s\n----", str.c_str());
    outfile.close();
    return 0;
} // WriteFile

int DownloadManager::AppendFile(const std::string file_name,
                                const std::string content)
{
    auto ret = 0;
    std::string path_with_file = "";
    FindPathWithFile(file_name, path_with_file);

    if ("" == path_with_file)
    {
        return 1404;
    }
    log("Full path: %s", path_with_file.c_str());

    std::string front_content = "";
    ret = ReadFile(file_name,
                   front_content);
    if (0 != ret)
        return ret;

    ret = WriteFile(file_name, front_content + "\n" + content);
    return ret;
} // AppendFile

int DownloadManager::FindPathWithFile(const std::string file_name,
                                      std::string &path_with_file)
{
    auto path = FileUtils::getInstance()->fullPathForFilename(file_name);
    if ("" == path)
    {
        auto temp_name = FileUtils::getInstance()->getWritablePath() + file_name;
        path = FileUtils::getInstance()->fullPathForFilename(temp_name);
        if ("" == path) log("File not exist!");
    }
    if ("" != path)
        log("Find file with : %s", path.c_str());
    path_with_file = path;
    return 0;
} // FindPathWithFile
<commit_msg>style<commit_after>//
//  download_manager.cpp
//  Cooloi_Assets_Downloader
//
//  Created by ESoragoto on 11/17/15.
//
//

#include "download_manager.hpp"
#include "assets_downloader.hpp"

#include "SimpleAudioEngine.h"

#include <iostream>
#include <string>
#include <fstream>
#include <regex>
#include <stdio.h>

#include "json/rapidjson.h"
#include "json/document.h"
#include "json/writer.h"
#include "json/stringbuffer.h"

using namespace cocos2d;
using namespace CocosDenshion;

#pragma mark - Initialization
DownloadManager::DownloadManager():
downloader_(nullptr),
stage_(DownloadStage ::kNull),
conf_(),
finished_(),
update_(),
now_downloading_(""),
now_number_(0)
{
} // DownloadManager

DownloadManager::~DownloadManager()
{
    if (downloader_)
        CC_SAFE_DELETE(downloader_);
} // ~DownloadManager

// on "init" you need to initialize your instance
bool DownloadManager::init()
{
    if ( !Scene::init() )
    {
        return false;
    }

    LoadConfig();

    InitDownloader();

    LoadUpdate();

    return true;
} // init

DownloadManager* DownloadManager::Create()
{
    auto d = new DownloadManager();
    if(d->init())
        return d;
    CC_SAFE_DELETE(d);
    return nullptr;
} // Create

void DownloadManager::update(float dt)
{
    if (downloader_->downloading()) return;

    unscheduleUpdate();

    switch (downloader()->status())
    {
//        case AssetsManager::ErrorCode::CREATE_FILE:
//        {
//            return;
//        }
//            break;

        case AssetsManager::ErrorCode::UNCOMPRESS:
        {
            set_stage(DownloadStage::kNull);
            return;
        }
            break;

        case AssetsManager::ErrorCode::NETWORK:
        {
            set_stage(DownloadStage::kNull);
            return;
        }
            break;

        default:
            break;
    }

    switch (stage())
    {
        case DownloadStage ::kLoadUpdate:
        {
            CheckUpdate();
        }
            break;

        case DownloadStage ::kGetUpdate:
        {
            GetUpdate();
        }
            break;

        default:
            break;
    }
} // update

#pragma mark - Member Function
#pragma mark -stage

int DownloadManager::LoadConfig()
{
    log("\nStage : Load config info.\n");
    set_stage(DownloadStage::kLoadConfig);
    auto ret = 0;
    std::string file_name = "";
//#if COCOS2D_DEBUG
//    file_name = "Cooloi_ASDL_DEBUG.conf";
////    file_name = "Cooloi_ASDL.conf";
//#else
//    file_name = "Cooloi_ASDL.conf";
//#endif
//    ret = ReadConf(file_name,
//                   conf_);

#if COCOS2D_DEBUG
    file_name = "Cooloi_ASDL_DEBUG.json";
    //    file_name = "Cooloi_ASDL.json";
#else
    file_name = "Cooloi_ASDL.json";
#endif
    ret = ReadConfigFromJson(file_name,
                             conf_);

    if (0 != ret)
    {
        set_stage(DownloadStage::kNull);
    }
    return ret;
} // LoadConfig

int DownloadManager::InitDownloader()
{
    log("\nStage : Initialization Downloader.\n");
    set_stage(DownloadStage::kInitDownloader);
    downloader_ = new AssetsDownloader(conf_["URL"],
                                       conf_["VER"],
                                       conf_["DIR"],
                                       std::stoi(conf_["TRY"]));
    downloader_->Init();
    return 0;
} // InitDownloader

int DownloadManager::LoadUpdate()
{
    log("\nStage : Download update info.\n");
    set_stage(DownloadStage::kLoadUpdate);
    Download(conf_["URL"]);
    return 0;
} // LoadUpdate

int DownloadManager::CheckUpdate()
{
    log("\nStage : Check update info.\n");
    set_stage(DownloadStage::kCheckUpdate);
    auto ret = 0;
    if ("" != now_downloading_) push_finished(now_downloading());
//    ret = ReadConf(conf_["NAME"], pkg_map_);
//    ret = ReadConf(conf_["LOCAL_NAME"], loc_map_);

    ret = ReadConfigFromJson(conf_["NAME"], pkg_map_);
    ret = ReadConfigFromJson(conf_["LOCAL_NAME"], loc_map_);

    for (auto p : pkg_map())
    {
        if (p.second != loc_map_[p.first])
        {
            push_update(p.first);
        }
    }

    if (update().empty())
    {
        set_stage(DownloadStage::kFinished);
    }
    else
    {
        log("New package find!");
//        GetUpdate();
    }
    return ret;
} // CheckUpdate

int DownloadManager::GetUpdate()
{
    log("\nStage : Get update package.\n");
    set_stage(DownloadStage::kGetUpdate);
    auto ret = 0;
    if ("" != now_downloading_) push_finished(now_downloading());

    for (auto u : update())
    {
        auto jump = false;
        for (auto f : finished())
        {
            if (u == f)
            {
                jump = true;
                break;
            }
        }
        if (jump) continue;

        set_now_downloading(u);
        Download(conf().at("SER") + pkg_map_[u]);
        break;
    }

    if (update().size() == finished().size())
    {
        std::string content = "#loacl list\n";
        for (auto p : pkg_map())
        {
            content += (p.first + " = " + p.second + "\n");
        }
        WriteFile(conf_["LOCAL_NAME"], content);
        auto s = FileUtils::getInstance()->getStringFromFile(conf_["LOCAL_NAME"]);
        log("%s", s.c_str());
        set_stage(DownloadStage::kFinished);
    }

    return ret;
} // GetUpdate

void DownloadManager::Close()
{
    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
} // Close

#pragma mark -other

int DownloadManager::Download(const std::string pkg_url)
{
    log("Request to download resource : %s", pkg_url.c_str());
    downloader_->Download(pkg_url);

    scheduleUpdate();
    return 0;
} // Download

int DownloadManager::ReadConf(const std::string file_name,
                              std::map<std::string, std::string> &conf_map)
{
    log("Read config file : %s", file_name.c_str());
    std::string path_with_file = "";
    FindPathWithFile(file_name, path_with_file);
    if ("" == path_with_file)
    {
        WriteFile(file_name, "");
        return 1;
    }

    auto str = FileUtils::getInstance()->getStringFromFile(file_name);
    log("getStringFromFile\n%s",str.c_str());

    std::ifstream in_file(path_with_file);
    if(in_file.fail())
        return 1001;

    std::string str_by_line = "";
    while (std::getline(in_file, str_by_line))
    {
        std::string arg;
        std::string value;
        ConfRegex(str_by_line, arg, value);
        conf_map[arg] = value;
    }
    return 0;
} // ReadConf

int DownloadManager::ConfRegex(const std::string str,
                               std::string &arg,
                               std::string &value)
{
    log("Regex line : %s", str.c_str());
    std::regex rgx("^(\\w+)\\s*\\=\\s*([^\\s]+)$");
    std::smatch match;

    if (std::regex_search(str.begin(), str.end(), match, rgx))
    {
        for(auto q : match)
        {
            log("\t%s", q.str().c_str());
        }
        log("----");
        arg = match[1].str();
        value = match[2].str();
    }
    return 0;
} // ConfRegex

int DownloadManager::ReadConfigFromJson(const std::string file_name,
                                        std::map<std::string, std::string> &conf_map)
{
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);
    auto str = FileUtils::getInstance()->getStringFromFile(file_with_path.c_str());
    if ("" == str)
    {
        log("Open file %s fail!", file_name.c_str());
        set_stage(DownloadStage::kFileNotFound);
        return 1404;
    }
    rapidjson::Document d;
    d.Parse<0>(str.c_str());
    if(!d.IsObject())
    {
        set_stage(DownloadStage::kFileNotFound);
        return 1404;
    }
    for (auto iter = d.MemberBegin() ; iter != d.MemberEnd() ; iter++)
    {
        log("\tKey\t : %s\n\tValue : %s\n\t----",
            iter->name.GetString(),
            iter->value.GetString());
        conf_map[iter->name.GetString()] = iter->value.GetString();
    }
    return 0;
}

int DownloadManager::WriteConfigToJson(const std::string file_name,
                                       std::map<std::string, std::string> &conf_map)
{
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);

    rapidjson::Document d;
    d.SetObject();
    for(auto c : conf_map)
    {
        log("write config name is %s, value is %s", c.first.c_str(), c.second.c_str());
        rapidjson::Value name(rapidjson::kStringType);
        name.SetString(c.first.c_str(), (int)c.first.length());

        rapidjson::Value value(rapidjson::kStringType);
        value.SetString(c.second.c_str(), (int)c.second.length());

        d.AddMember(name, value, d.GetAllocator());
    }

    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> write(buffer);
    d.Accept(write);

    log("now write config is %s", buffer.GetString());

    if ("" == file_with_path)
    {
        file_with_path = FileUtils::getInstance()->getWritablePath() + file_name;
    }

    FILE* file = fopen(file_with_path.c_str(), "wb");
    if (file)
    {
        fputs(buffer.GetString(), file);
        fclose(file);
    }
    return 0;
}

int DownloadManager::ReadFile(const std::string file_name,
                              std::string &content)
{
    log("Preparing Read file : %s", file_name.c_str());
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);
    if ("" == file_with_path)
        return 1404;

    log("Full path: %s", file_with_path.c_str());
    auto file = FileUtils::getInstance()->getStringFromFile(file_with_path);

    if ("" == file)
    {
        std::ifstream infile(file_with_path);

        if (infile.fail())
        {
            log("Open file fail, file name: %s", file_name.c_str());
            return 1001;
        }

        std::string str((std::istreambuf_iterator<char>(infile)),
                        std::istreambuf_iterator<char>());
        file = str.c_str();
        infile.close();
    }

    log("open file:\n----\n%s\n----", file.c_str());
    content = file;
    return 0;
} // ReadFile

int DownloadManager::WriteFile(const std::string file_name,
                               const std::string content)
{
    log("Preparing write file : %s", file_name.c_str());
    std::string file_to_write = "";
    FindPathWithFile(file_name, file_to_write);
    if ("" == file_to_write)
    {
        file_to_write = FileUtils::getInstance()->getWritablePath();
//        file_to_write += conf_["Dir"];
        file_to_write += file_name;
    }

    log("Write path : %s", file_to_write.c_str());
    std::ofstream outfile;
    outfile.open(file_to_write);
    if (outfile.fail())
    {
        log("Open file fail, file name: %s", file_name.c_str());
        return 1001;
    }
    std::string str = "#" + file_name + "\n" + content;
    outfile << str;
    log("write file with fstream : \n----\n%s\n----", str.c_str());
    outfile.close();
    return 0;
} // WriteFile

int DownloadManager::AppendFile(const std::string file_name,
                                const std::string content)
{
    auto ret = 0;
    std::string path_with_file = "";
    FindPathWithFile(file_name, path_with_file);

    if ("" == path_with_file)
    {
        return 1404;
    }
    log("Full path: %s", path_with_file.c_str());

    std::string front_content = "";
    ret = ReadFile(file_name,
                   front_content);
    if (0 != ret)
        return ret;

    ret = WriteFile(file_name, front_content + "\n" + content);
    return ret;
} // AppendFile

int DownloadManager::FindPathWithFile(const std::string file_name,
                                      std::string &path_with_file)
{
    auto path = FileUtils::getInstance()->fullPathForFilename(file_name);
    if ("" == path)
    {
        auto temp_name = FileUtils::getInstance()->getWritablePath() + file_name;
        path = FileUtils::getInstance()->fullPathForFilename(temp_name);
        if ("" == path) log("File not exist!");
    }
    if ("" != path)
        log("Find file with : %s", path.c_str());
    path_with_file = path;
    return 0;
} // FindPathWithFile
<|endoftext|>


<commit_before>/** @file
 *
 * @ingroup modularLibrary
 *
 * @brief An audio output component for Jamoma models.
 *
 * @details
 *
 * @authors Timothy Place
 *
 * @copyright © 2013, Timothy Place @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTOutputAudio.h"

#define thisTTClass			TTOutputAudio
#define thisTTClassName		"Output.audio"
#define thisTTClassTags		"output"

TTObjectBasePtr TTOutputAudio::instantiate (TTSymbol& name, TTValue& arguments)
{
	return new TTOutputAudio(arguments);
}

extern "C" void TTOutputAudio::registerClass()
{
	TTClassRegister(TTSymbol("Output.audio"), thisTTClassTags, TTOutputAudio::instantiate);
}

TTOutputAudio::TTOutputAudio(TTValue& arguments) :
TTOutput(arguments)
{
	TTValue				args;

	mType = "audio";

	// the only argument is the owner, which is used as a baton to hand to the callback
	if (arguments.size())
		mReturnSignalCallback = TTCallbackPtr((TTObjectBasePtr)arguments[0]);
	if (arguments.size() > 1)
		mReturnLinkCallback = TTCallbackPtr((TTObjectBasePtr)arguments[1]);

	TTObjectBaseInstantiate(kTTSym_audiosignal, &mSignalIn, 1);
	TTObjectBaseInstantiate(kTTSym_audiosignal, &mSignalOut, 1);
	TTObjectBaseInstantiate(kTTSym_audiosignal, &mSignalTemp, 1);
	TTObjectBaseInstantiate(kTTSym_audiosignal, &mSignalZero, 1);
	TTObjectBaseInstantiate(TTSymbol("crossfade"), &mMixUnit, 1);
	mMixUnit->setAttributeValue(TTSymbol("position"), 1.0);
	TTObjectBaseInstantiate(TTSymbol("gain"), &mGainUnit, 1);
	mGainUnit->setAttributeValue(TTSymbol("linearGain"), 1.0);
	TTObjectBaseInstantiate(TTSymbol("ramp"), &mRampMixUnit, 1);
	TTObjectBaseInstantiate(TTSymbol("ramp"), &mRampGainUnit, 1);
}

TTOutputAudio::~TTOutputAudio()
{
	TTObjectBaseRelease(&mSignalIn);
	TTObjectBaseRelease(&mSignalOut);
	TTObjectBaseRelease(&mSignalTemp);
	TTObjectBaseRelease(&mSignalZero);
	TTObjectBaseRelease(&mMixUnit);
	TTObjectBaseRelease(&mGainUnit);
	TTObjectBaseRelease(&mRampMixUnit);
	TTObjectBaseRelease(&mRampGainUnit);
}

void TTOutputAudio::process(TTSampleValue* anInputSampleVector, TTSampleValue* anOutputSampleVector, TTUInt16 aVectorSize)
{
	// Store the audio vector as a proper audio signal
	TTAudioSignalPtr(mSignalIn)->setVector64Copy(0, aVectorSize, anInputSampleVector);

	// if the output signal is muted
	if (mMute)
		TTAudioSignal::copy(*TTAudioSignalPtr(mSignalZero), *TTAudioSignalPtr(mSignalOut));

	// if input signal exists
	else if (mInputObject) {

		// if input signal is bypassed : copy input (in Temp)
		if (mInputObject->mBypass)
			TTAudioSignal::copy(*TTAudioSignalPtr(mInputObject->mSignalIn), *TTAudioSignalPtr(mSignalTemp));

		// otherwise mix input and output signals (in Temp)
		else
			TTAudioObjectBasePtr(mMixUnit)->process(TTAudioSignalPtr(mInputObject->mSignalOut), TTAudioSignalPtr(mSignalIn), TTAudioSignalPtr(mSignalTemp));

		// then perform gain control (from Temp)
		TTAudioObjectBasePtr(mGainUnit)->process(TTAudioSignalPtr(mSignalTemp), TTAudioSignalPtr(mSignalOut));
	}
	// otherwise just perform gain control
	else
		TTAudioObjectBasePtr(mGainUnit)->process(TTAudioSignalPtr(mSignalIn), TTAudioSignalPtr(mSignalOut));

	// Send the input on to the outlets for the algorithm
	TTAudioSignalPtr(mSignalOut)->getVectorCopy(0, aVectorSize, anOutputSampleVector);
}

<commit_msg>Preventing from uninstanciatied unit case<commit_after>/** @file
 *
 * @ingroup modularLibrary
 *
 * @brief An audio output component for Jamoma models.
 *
 * @details
 *
 * @authors Timothy Place
 *
 * @copyright © 2013, Timothy Place @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTOutputAudio.h"

#define thisTTClass			TTOutputAudio
#define thisTTClassName		"Output.audio"
#define thisTTClassTags		"output"

TTObjectBasePtr TTOutputAudio::instantiate (TTSymbol& name, TTValue& arguments)
{
	return new TTOutputAudio(arguments);
}

extern "C" void TTOutputAudio::registerClass()
{
	TTClassRegister(TTSymbol("Output.audio"), thisTTClassTags, TTOutputAudio::instantiate);
}

TTOutputAudio::TTOutputAudio(TTValue& arguments) :
TTOutput(arguments)
{
	TTValue				args;

	mType = "audio";

	// the only argument is the owner, which is used as a baton to hand to the callback
	if (arguments.size())
		mReturnSignalCallback = TTCallbackPtr((TTObjectBasePtr)arguments[0]);
	if (arguments.size() > 1)
		mReturnLinkCallback = TTCallbackPtr((TTObjectBasePtr)arguments[1]);

	TTObjectBaseInstantiate(kTTSym_audiosignal, &mSignalIn, 1);
	TTObjectBaseInstantiate(kTTSym_audiosignal, &mSignalOut, 1);
	TTObjectBaseInstantiate(kTTSym_audiosignal, &mSignalTemp, 1);
	TTObjectBaseInstantiate(kTTSym_audiosignal, &mSignalZero, 1);

	TTObjectBaseInstantiate(TTSymbol("crossfade"), &mMixUnit, 1);
	if (mMixUnit)
        mMixUnit->setAttributeValue(TTSymbol("position"), 1.0);

    TTObjectBaseInstantiate(TTSymbol("gain"), &mGainUnit, 1);
    if (mGainUnit)
        mGainUnit->setAttributeValue(TTSymbol("linearGain"), 1.0);

	TTObjectBaseInstantiate(TTSymbol("ramp"), &mRampMixUnit, 1);
	TTObjectBaseInstantiate(TTSymbol("ramp"), &mRampGainUnit, 1);
}

TTOutputAudio::~TTOutputAudio()
{
	TTObjectBaseRelease(&mSignalIn);
	TTObjectBaseRelease(&mSignalOut);
	TTObjectBaseRelease(&mSignalTemp);
	TTObjectBaseRelease(&mSignalZero);
	TTObjectBaseRelease(&mMixUnit);
	TTObjectBaseRelease(&mGainUnit);
	TTObjectBaseRelease(&mRampMixUnit);
	TTObjectBaseRelease(&mRampGainUnit);
}

void TTOutputAudio::process(TTSampleValue* anInputSampleVector, TTSampleValue* anOutputSampleVector, TTUInt16 aVectorSize)
{
	// Store the audio vector as a proper audio signal
	TTAudioSignalPtr(mSignalIn)->setVector64Copy(0, aVectorSize, anInputSampleVector);

	// if the output signal is muted
	if (mMute)
		TTAudioSignal::copy(*TTAudioSignalPtr(mSignalZero), *TTAudioSignalPtr(mSignalOut));

	// if input signal exists
	else if (mInputObject) {

		// if input signal is bypassed : copy input (in Temp)
		if (mInputObject->mBypass)
			TTAudioSignal::copy(*TTAudioSignalPtr(mInputObject->mSignalIn), *TTAudioSignalPtr(mSignalTemp));

		// otherwise mix input and output signals (in Temp)
		else
			TTAudioObjectBasePtr(mMixUnit)->process(TTAudioSignalPtr(mInputObject->mSignalOut), TTAudioSignalPtr(mSignalIn), TTAudioSignalPtr(mSignalTemp));

		// then perform gain control (from Temp)
		TTAudioObjectBasePtr(mGainUnit)->process(TTAudioSignalPtr(mSignalTemp), TTAudioSignalPtr(mSignalOut));
	}
	// otherwise just perform gain control
	else
		TTAudioObjectBasePtr(mGainUnit)->process(TTAudioSignalPtr(mSignalIn), TTAudioSignalPtr(mSignalOut));

	// Send the input on to the outlets for the algorithm
	TTAudioSignalPtr(mSignalOut)->getVectorCopy(0, aVectorSize, anOutputSampleVector);
}

<|endoftext|>


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

namespace itk
{

// If not C++11, then no constexpr and declaration is needed
#if !(__cplusplus >= 201103L)

const bool NumericTraits< bool >:: Zero;
const bool NumericTraits< bool >:: One;

const unsigned char NumericTraits< unsigned char >:: Zero;
const unsigned char NumericTraits< unsigned char >:: One;

const signed char NumericTraits< signed char >:: Zero;
const signed char NumericTraits< signed char >:: One;

const char NumericTraits< char >:: Zero;
const char NumericTraits< char >:: One;

const unsigned short NumericTraits< unsigned short >:: Zero;
const unsigned short NumericTraits< unsigned short >:: One;

const short NumericTraits< short >:: Zero;
const short NumericTraits< short >:: One;

const unsigned int NumericTraits< unsigned int >:: Zero;
const unsigned int NumericTraits< unsigned int >:: One;

const int NumericTraits< int >:: Zero;
const int NumericTraits< int >:: One;

const unsigned long NumericTraits< unsigned long >:: Zero;
const unsigned long NumericTraits< unsigned long >:: One;

const long NumericTraits< long >:: Zero;
const long NumericTraits< long >:: One;

const long long NumericTraits< long long >:: Zero;
const long long NumericTraits< long long >:: One;

const unsigned long long NumericTraits< unsigned long long >:: Zero;
const unsigned long long NumericTraits< unsigned long long >:: One;

const float NumericTraits< float >:: Zero = 0.0F;
const float NumericTraits< float >:: One = 1.0F;

const double NumericTraits< double >:: Zero = 0.0;
const double NumericTraits< double >:: One = 1.0;

const long double NumericTraits< long double >:: Zero = 0.0;
const long double NumericTraits< long double >:: One = 1.0;

#endif

const std::complex< char >  NumericTraits< std::complex< char > >:: Zero = std::complex< char >(0, 0);
const std::complex< char >  NumericTraits< std::complex< char > >:: One  = std::complex< char >(1, 0);

const std::complex< unsigned char >  NumericTraits< std::complex< unsigned char > >:: Zero = std::complex< unsigned char >(0, 0);
const std::complex< unsigned char >  NumericTraits< std::complex< unsigned char > >:: One  = std::complex< unsigned char >(1, 0);

const std::complex< short >  NumericTraits< std::complex< short > >:: Zero = std::complex< short >(0, 0);
const std::complex< short >  NumericTraits< std::complex< short > >:: One  = std::complex< short >(1, 0);

const std::complex< unsigned short >  NumericTraits< std::complex< unsigned short > >:: Zero = std::complex< unsigned short >(0, 0);
const std::complex< unsigned short >  NumericTraits< std::complex< unsigned short > >:: One  = std::complex< unsigned short >(1, 0);

const std::complex< int >  NumericTraits< std::complex< int > >:: Zero = std::complex< int >(0, 0);
const std::complex< int >  NumericTraits< std::complex< int > >:: One  = std::complex< int >(1, 0);

const std::complex< unsigned int >  NumericTraits< std::complex< unsigned int > >:: Zero = std::complex< unsigned int >(0, 0);
const std::complex< unsigned int >  NumericTraits< std::complex< unsigned int > >:: One  = std::complex< unsigned int >(1, 0);

const std::complex< long >  NumericTraits< std::complex< long > >:: Zero = std::complex< long >(0L, 0L);
const std::complex< long >  NumericTraits< std::complex< long > >:: One  = std::complex< long >(1L, 0L);

const std::complex< unsigned long >  NumericTraits< std::complex< unsigned long > >:: Zero = std::complex< unsigned long >(0UL, 0UL);
const std::complex< unsigned long >  NumericTraits< std::complex< unsigned long > >:: One  = std::complex< unsigned long >(1UL, 0UL);

const std::complex< float >  NumericTraits< std::complex< float > >:: Zero = std::complex< float >(0.0f, 0.0f);
const std::complex< float >  NumericTraits< std::complex< float > >:: One  = std::complex< float >(1.0f, 0.0f);

const std::complex< double >  NumericTraits< std::complex< double > >:: Zero = std::complex< double >(0.0, 0.0);
const std::complex< double >  NumericTraits< std::complex< double > >:: One  = std::complex< double >(1.0, 0.0);

const std::complex< long double >  NumericTraits< std::complex< long double > >:: Zero = std::complex< long double >(0.0, 0.0);
const std::complex< long double >  NumericTraits< std::complex< long double > >:: One  = std::complex< long double >(1.0, 0.0);

} // end namespace itk
<commit_msg>BUG: Add definition of static constexpr NumericTrait members<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include "itkNumericTraits.h"

namespace itk
{

const bool NumericTraits< bool >:: Zero;
const bool NumericTraits< bool >:: One;

const unsigned char NumericTraits< unsigned char >:: Zero;
const unsigned char NumericTraits< unsigned char >:: One;

const signed char NumericTraits< signed char >:: Zero;
const signed char NumericTraits< signed char >:: One;

const char NumericTraits< char >:: Zero;
const char NumericTraits< char >:: One;

const unsigned short NumericTraits< unsigned short >:: Zero;
const unsigned short NumericTraits< unsigned short >:: One;

const short NumericTraits< short >:: Zero;
const short NumericTraits< short >:: One;

const unsigned int NumericTraits< unsigned int >:: Zero;
const unsigned int NumericTraits< unsigned int >:: One;

const int NumericTraits< int >:: Zero;
const int NumericTraits< int >:: One;

const unsigned long NumericTraits< unsigned long >:: Zero;
const unsigned long NumericTraits< unsigned long >:: One;

const long NumericTraits< long >:: Zero;
const long NumericTraits< long >:: One;

const long long NumericTraits< long long >:: Zero;
const long long NumericTraits< long long >:: One;

const unsigned long long NumericTraits< unsigned long long >:: Zero;
const unsigned long long NumericTraits< unsigned long long >:: One;

// If not C++11, then use static initialization for real types
#if !(__cplusplus >= 201103L)

const float NumericTraits< float >:: Zero = 0.0F;
const float NumericTraits< float >:: One = 1.0F;

const double NumericTraits< double >:: Zero = 0.0;
const double NumericTraits< double >:: One = 1.0;

const long double NumericTraits< long double >:: Zero = 0.0;
const long double NumericTraits< long double >:: One = 1.0;

#else

const float NumericTraits< float >:: Zero;
const float NumericTraits< float >:: One;

const double NumericTraits< double >:: Zero;
const double NumericTraits< double >:: One;

const long double NumericTraits< long double >:: Zero;
const long double NumericTraits< long double >:: One;

#endif

const std::complex< char >  NumericTraits< std::complex< char > >:: Zero = std::complex< char >(0, 0);
const std::complex< char >  NumericTraits< std::complex< char > >:: One  = std::complex< char >(1, 0);

const std::complex< unsigned char >  NumericTraits< std::complex< unsigned char > >:: Zero = std::complex< unsigned char >(0, 0);
const std::complex< unsigned char >  NumericTraits< std::complex< unsigned char > >:: One  = std::complex< unsigned char >(1, 0);

const std::complex< short >  NumericTraits< std::complex< short > >:: Zero = std::complex< short >(0, 0);
const std::complex< short >  NumericTraits< std::complex< short > >:: One  = std::complex< short >(1, 0);

const std::complex< unsigned short >  NumericTraits< std::complex< unsigned short > >:: Zero = std::complex< unsigned short >(0, 0);
const std::complex< unsigned short >  NumericTraits< std::complex< unsigned short > >:: One  = std::complex< unsigned short >(1, 0);

const std::complex< int >  NumericTraits< std::complex< int > >:: Zero = std::complex< int >(0, 0);
const std::complex< int >  NumericTraits< std::complex< int > >:: One  = std::complex< int >(1, 0);

const std::complex< unsigned int >  NumericTraits< std::complex< unsigned int > >:: Zero = std::complex< unsigned int >(0, 0);
const std::complex< unsigned int >  NumericTraits< std::complex< unsigned int > >:: One  = std::complex< unsigned int >(1, 0);

const std::complex< long >  NumericTraits< std::complex< long > >:: Zero = std::complex< long >(0L, 0L);
const std::complex< long >  NumericTraits< std::complex< long > >:: One  = std::complex< long >(1L, 0L);

const std::complex< unsigned long >  NumericTraits< std::complex< unsigned long > >:: Zero = std::complex< unsigned long >(0UL, 0UL);
const std::complex< unsigned long >  NumericTraits< std::complex< unsigned long > >:: One  = std::complex< unsigned long >(1UL, 0UL);

const std::complex< float >  NumericTraits< std::complex< float > >:: Zero = std::complex< float >(0.0f, 0.0f);
const std::complex< float >  NumericTraits< std::complex< float > >:: One  = std::complex< float >(1.0f, 0.0f);

const std::complex< double >  NumericTraits< std::complex< double > >:: Zero = std::complex< double >(0.0, 0.0);
const std::complex< double >  NumericTraits< std::complex< double > >:: One  = std::complex< double >(1.0, 0.0);

const std::complex< long double >  NumericTraits< std::complex< long double > >:: Zero = std::complex< long double >(0.0, 0.0);
const std::complex< long double >  NumericTraits< std::complex< long double > >:: One  = std::complex< long double >(1.0, 0.0);

} // end namespace itk
<|endoftext|>


<commit_before>//
// Created by playmice on 4/26/17.
//

<commit_msg>Finished trial division algorithm<commit_after>//
// Created by playmice on 4/26/17.
//

#include <iostream>
#include <cmath>

using namespace std;
bool trialDivision(int number);

int main() {
    int num;
    cout << "Enter the number you want to test: " << endl;
    cin >> num;
    bool primality = trialDivision(num);
    cout << primality;
}

bool trialDivision(int number) {
    if (number == 1) {
        return 0;
    }
    int squareRoot = (int) sqrt(number);
    for(int i = 2; i <= squareRoot; i++) {
        if (number%i == 0) {
            return false;
        }
    }

    return true;
}<|endoftext|>