<commit_before>// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2015 Benjamin Huber and Sebastian Wolf.
//
// Xerus is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Xerus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at contact@libXerus.org.

/**
 * @file
 * @brief Implementation of the PerformanceData class.
 */

#include <string>
#include <fstream>
#include <xerus/performanceData.h>
#include <xerus/misc/missingFunctions.h>

namespace xerus {

	PerformanceData::Histogram::Histogram(const std::vector< xerus::PerformanceData::DataPoint >& _data, const xerus::value_t _base) : base(_base), totalTime(0) {
		for (size_t i = 1; i<_data.size(); ++i) {
			if (_data[i].residual >= _data[i-1].residual) {
				continue;
			}

			// assume x_2 = x_1 * 2^(-alpha * delta-t)
			value_t relativeChange = _data[i].residual/_data[i-1].residual;
			value_t exponent = log(relativeChange) / log(2);
			size_t delta_t = _data[i].elapsedTime - _data[i-1].elapsedTime;
			value_t rate = - exponent / value_t(delta_t);
			int logRate = int(log(rate)/log(base));
			buckets[logRate] += delta_t;
			totalTime += delta_t;
		}
	}

	PerformanceData::Histogram::Histogram(const xerus::value_t _base) : base(_base), totalTime(0) {}

	PerformanceData::Histogram PerformanceData::Histogram::operator+=(const Histogram &_other) {
		REQUIRE(misc::approx_equal(_other.base, base), "only histograms of identical base can be added");
		for (const auto &h : _other.buckets) {
			buckets[h.first] += h.second;
		}
		totalTime += _other.totalTime;
		return *this;
	}

	PerformanceData::Histogram PerformanceData::Histogram::read_from_file(const std::string &_fileName) {
		std::ifstream in(_fileName);
		Histogram result(0.0);
		std::string line;
		std::getline(in, line);
		REQUIRE(line == "# raw data:", "unknown histogram file format " << _fileName); //TODO this should throw an exception
		char c;
		in >> c;
		REQUIRE(c == '#', "missing information in histogram file " << _fileName);
		in >> result.base >> result.totalTime;
		std::getline(in, line); // read in rest of this line
		std::getline(in, line); // line now contains all buckets
		std::stringstream bucketData(line);
		bucketData >> c;
		REQUIRE(c == '#', "missing information in histogram file " << _fileName);
		int bucketIndex;
		while (bucketData >> bucketIndex) {
			size_t count;
			if (!(bucketData >> count)) {
				LOG(fatal, "missing bucket count in histogram file " << _fileName);
			}
			result.buckets[bucketIndex] = count;
		}
		return result;
	}

	void PerformanceData::Histogram::dump_to_file(const std::string &_fileName) const {
		std::ofstream out(_fileName);
		out << "# raw data:\n";
		out << "# " << base << ' ' << totalTime << '\n';
		out << '#';
		for (auto &h : buckets) {
			out << ' ' << h.first << ' ' << h.second;
		}
		out << "\n# plotable data:\n";
		for (auto &h : buckets) {
			out << pow(base, h.first) << " " << double(h.second)/double(totalTime) << '\n';
		}
		out.close();
	}

	void PerformanceData::add(const size_t _itrCount, const xerus::value_t _residual, const std::vector<size_t> _ranks, const size_t _flags) {
		if (active) {
			if (startTime == ~0ul) {
				start();
			}
			data.emplace_back(_itrCount, get_runtime(), _residual, _ranks, _flags);

			if(printProgress) {
				LOG(PerformanceData, "Iteration " << std::setw(4) << std::setfill(' ') << _itrCount
					<< " Time: " <<  std::setw(6) << std::setfill(' ') << std::fixed << double(data.back().elapsedTime)*1e-6
					<< "s Residual: " <<  std::setw(11) << std::setfill(' ') << std::scientific << _residual << " Flags: " << _flags << " Ranks: " << _ranks);
			}
		}
	}

	void PerformanceData::add(const xerus::value_t _residual, const TensorNetwork::RankTuple _ranks, const size_t _flags) {
		if (active) {
			if (data.empty()) {
				add(0, _residual, _ranks, _flags);
			} else {
				add(data.back().iterationCount+1, _residual, _ranks, _flags);
			}
		}
	}

	void PerformanceData::dump_to_file(const std::string &_fileName) const {
		std::string header;
		header += "# ";
		header += additionalInformation;
		misc::replace(header, "\n", "\n# ");
		header += "\n# \n#itr \ttime[us] \tresidual \tflags \tranks...\n";
		std::ofstream out(_fileName);
		out << header;
		for (const DataPoint &d : data) {
			out << d.iterationCount << '\t' << d.elapsedTime << '\t' << d.residual << '\t' << d.flags;
			for (size_t r : d.ranks) {
				out << '\t' << r;
			}
			out << '\n';
		}
		out.close();
	}

	PerformanceData::Histogram PerformanceData::get_histogram(const xerus::value_t _base) const {
		return Histogram(data, _base);
	}

	PerformanceData NoPerfData(false);
}
<commit_msg>consistency check for Histogram::read_from_file<commit_after>// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2015 Benjamin Huber and Sebastian Wolf.
//
// Xerus is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Xerus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at contact@libXerus.org.

/**
 * @file
 * @brief Implementation of the PerformanceData class.
 */

#include <string>
#include <fstream>
#include <xerus/performanceData.h>
#include <xerus/misc/missingFunctions.h>

namespace xerus {

	PerformanceData::Histogram::Histogram(const std::vector< xerus::PerformanceData::DataPoint >& _data, const xerus::value_t _base) : base(_base), totalTime(0) {
		for (size_t i = 1; i<_data.size(); ++i) {
			if (_data[i].residual >= _data[i-1].residual) {
				continue;
			}

			// assume x_2 = x_1 * 2^(-alpha * delta-t)
			value_t relativeChange = _data[i].residual/_data[i-1].residual;
			value_t exponent = log(relativeChange) / log(2);
			size_t delta_t = _data[i].elapsedTime - _data[i-1].elapsedTime;
			value_t rate = - exponent / value_t(delta_t);
			int logRate = int(log(rate)/log(base));
			buckets[logRate] += delta_t;
			totalTime += delta_t;
		}
	}

	PerformanceData::Histogram::Histogram(const xerus::value_t _base) : base(_base), totalTime(0) {}

	PerformanceData::Histogram PerformanceData::Histogram::operator+=(const Histogram &_other) {
		REQUIRE(misc::approx_equal(_other.base, base), "only histograms of identical base can be added");
		for (const auto &h : _other.buckets) {
			buckets[h.first] += h.second;
		}
		totalTime += _other.totalTime;
		return *this;
	}

	PerformanceData::Histogram PerformanceData::Histogram::read_from_file(const std::string &_fileName) {
		std::ifstream in(_fileName);
		Histogram result(0.0);
		std::string line;
		std::getline(in, line);
		REQUIRE(line == "# raw data:", "unknown histogram file format " << _fileName); //TODO this should throw an exception
		char c;
		in >> c;
		REQUIRE(c == '#', "missing information in histogram file " << _fileName);
		in >> result.base >> result.totalTime;
		std::getline(in, line); // read in rest of this line
		std::getline(in, line); // line now contains all buckets
		std::stringstream bucketData(line);
		bucketData >> c;
		REQUIRE(c == '#', "missing information in histogram file " << _fileName);
		int bucketIndex;
		while (bucketData >> bucketIndex) {
			size_t count;
			if (!(bucketData >> count)) {
				LOG(fatal, "missing bucket count in histogram file " << _fileName);
			}
			result.buckets[bucketIndex] = count;
		}
		size_t accountedTime=0;
		for (auto &h : result.buckets) {
			accountedTime += h.second;
		}
		REQUIRE(accountedTime == result.totalTime, "histogram data inconsistent in file " << _fileName);
		return result;
	}

	void PerformanceData::Histogram::dump_to_file(const std::string &_fileName) const {
		std::ofstream out(_fileName);
		out << "# raw data:\n";
		out << "# " << base << ' ' << totalTime << '\n';
		out << '#';
		for (auto &h : buckets) {
			out << ' ' << h.first << ' ' << h.second;
		}
		out << "\n# plotable data:\n";
		for (auto &h : buckets) {
			out << pow(base, h.first) << " " << double(h.second)/double(totalTime) << '\n';
		}
		out.close();
	}

	void PerformanceData::add(const size_t _itrCount, const xerus::value_t _residual, const std::vector<size_t> _ranks, const size_t _flags) {
		if (active) {
			if (startTime == ~0ul) {
				start();
			}
			data.emplace_back(_itrCount, get_runtime(), _residual, _ranks, _flags);

			if(printProgress) {
				LOG(PerformanceData, "Iteration " << std::setw(4) << std::setfill(' ') << _itrCount
					<< " Time: " <<  std::setw(6) << std::setfill(' ') << std::fixed << double(data.back().elapsedTime)*1e-6
					<< "s Residual: " <<  std::setw(11) << std::setfill(' ') << std::scientific << _residual << " Flags: " << _flags << " Ranks: " << _ranks);
			}
		}
	}

	void PerformanceData::add(const xerus::value_t _residual, const TensorNetwork::RankTuple _ranks, const size_t _flags) {
		if (active) {
			if (data.empty()) {
				add(0, _residual, _ranks, _flags);
			} else {
				add(data.back().iterationCount+1, _residual, _ranks, _flags);
			}
		}
	}

	void PerformanceData::dump_to_file(const std::string &_fileName) const {
		std::string header;
		header += "# ";
		header += additionalInformation;
		misc::replace(header, "\n", "\n# ");
		header += "\n# \n#itr \ttime[us] \tresidual \tflags \tranks...\n";
		std::ofstream out(_fileName);
		out << header;
		for (const DataPoint &d : data) {
			out << d.iterationCount << '\t' << d.elapsedTime << '\t' << d.residual << '\t' << d.flags;
			for (size_t r : d.ranks) {
				out << '\t' << r;
			}
			out << '\n';
		}
		out.close();
	}

	PerformanceData::Histogram PerformanceData::get_histogram(const xerus::value_t _base) const {
		return Histogram(data, _base);
	}

	PerformanceData NoPerfData(false);
}
<|endoftext|>


<commit_before><commit_msg>DevTools: wire Inspect Element action to DOMAgent-enabled inspector controller. TBR=mnaganov<commit_after><|endoftext|>


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

// MOOSE includes
#include "ComputeElemAuxBcsThread.h"
#include "AuxiliarySystem.h"
#include "FEProblem.h"
#include "DisplacedProblem.h"
#include "Assembly.h"
#include "AuxKernel.h"
#include "SwapBackSentinel.h"

#include "libmesh/threads.h"

template <typename AuxKernelType>
ComputeElemAuxBcsThread<AuxKernelType>::ComputeElemAuxBcsThread(
    FEProblemBase & problem,
    const MooseObjectWarehouse<AuxKernelType> & storage,
    const std::vector<std::vector<MooseVariableFEBase *>> & vars,
    bool need_materials)
  : _problem(problem),
    _aux_sys(problem.getAuxiliarySystem()),
    _storage(storage),
    _aux_vars(vars),
    _need_materials(need_materials)
{
}

// Splitting Constructor
template <typename AuxKernelType>
ComputeElemAuxBcsThread<AuxKernelType>::ComputeElemAuxBcsThread(ComputeElemAuxBcsThread & x,
                                                                Threads::split /*split*/)
  : _problem(x._problem),
    _aux_sys(x._aux_sys),
    _storage(x._storage),
    _aux_vars(x._aux_vars),
    _need_materials(x._need_materials)
{
}

template <typename AuxKernelType>
void
ComputeElemAuxBcsThread<AuxKernelType>::operator()(const ConstBndElemRange & range)
{
  ParallelUniqueId puid;
  _tid = puid.id;

  // Reference to all boundary restricted AuxKernels for the current thread
  const auto & boundary_kernels = _storage.getActiveBoundaryObjects(_tid);

  for (const auto & belem : range)
  {
    const Elem * elem = belem->_elem;
    unsigned short int side = belem->_side;
    BoundaryID boundary_id = belem->_bnd_id;

    // need to update the boundary ID in assembly
    _problem.setCurrentBoundaryID(boundary_id, _tid);

    if (elem->processor_id() == _problem.processor_id())
    {
      // prepare variables
      for (auto * var : _aux_vars[_tid])
        var->prepareAux();

      // Locate the AuxKernel objects for the current BoundaryID
      const auto iter = boundary_kernels.find(boundary_id);

      if (iter != boundary_kernels.end() && !(iter->second.empty()))
      {
        _problem.setCurrentSubdomainID(elem, _tid);
        _problem.prepare(elem, _tid);
        _problem.reinitElemFace(elem, side, boundary_id, _tid);

        if (_need_materials)
        {
          std::set<unsigned int> needed_mat_props;
          for (const auto & aux : iter->second)
          {
            const std::set<unsigned int> & mp_deps = aux->getMatPropDependencies();
            needed_mat_props.insert(mp_deps.begin(), mp_deps.end());
          }
          _problem.setActiveMaterialProperties(needed_mat_props, _tid);

          const Elem * neighbor = elem->neighbor_ptr(side);

          _problem.reinitMaterialsFace(elem->subdomain_id(), _tid);
          if (neighbor != nullptr)
            if (neighbor->active())
            {
              SwapBackSentinel neighbor_sentinel(
                  _problem, &FEProblem::swapBackMaterialsNeighbor, _tid);
              _problem.reinitNeighbor(elem, side, _tid);
            }

          _problem.reinitMaterialsBoundary(boundary_id, _tid);
          _problem.reinitMaterialsInterface(boundary_id, _tid);
        }

        for (const auto & aux : iter->second)
          aux->compute();

        if (_need_materials)
        {
          _problem.swapBackMaterialsFace(_tid);
          _problem.clearActiveMaterialProperties(_tid);
        }
      }

      // update the solution vector
      {
        Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
        for (auto * var : _aux_vars[_tid])
          var->insert(_aux_sys.solution());
      }
    }
  }
}

template <typename AuxKernelType>
void
ComputeElemAuxBcsThread<AuxKernelType>::join(const ComputeElemAuxBcsThread & /*y*/)
{
}

template class ComputeElemAuxBcsThread<AuxKernel>;
template class ComputeElemAuxBcsThread<VectorAuxKernel>;
<commit_msg>Dont treat InterfaceMaterials as boundary materials<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

// MOOSE includes
#include "ComputeElemAuxBcsThread.h"
#include "AuxiliarySystem.h"
#include "FEProblem.h"
#include "DisplacedProblem.h"
#include "Assembly.h"
#include "AuxKernel.h"
#include "SwapBackSentinel.h"

#include "libmesh/threads.h"

template <typename AuxKernelType>
ComputeElemAuxBcsThread<AuxKernelType>::ComputeElemAuxBcsThread(
    FEProblemBase & problem,
    const MooseObjectWarehouse<AuxKernelType> & storage,
    const std::vector<std::vector<MooseVariableFEBase *>> & vars,
    bool need_materials)
  : _problem(problem),
    _aux_sys(problem.getAuxiliarySystem()),
    _storage(storage),
    _aux_vars(vars),
    _need_materials(need_materials)
{
}

// Splitting Constructor
template <typename AuxKernelType>
ComputeElemAuxBcsThread<AuxKernelType>::ComputeElemAuxBcsThread(ComputeElemAuxBcsThread & x,
                                                                Threads::split /*split*/)
  : _problem(x._problem),
    _aux_sys(x._aux_sys),
    _storage(x._storage),
    _aux_vars(x._aux_vars),
    _need_materials(x._need_materials)
{
}

template <typename AuxKernelType>
void
ComputeElemAuxBcsThread<AuxKernelType>::operator()(const ConstBndElemRange & range)
{
  ParallelUniqueId puid;
  _tid = puid.id;

  // Reference to all boundary restricted AuxKernels for the current thread
  const auto & boundary_kernels = _storage.getActiveBoundaryObjects(_tid);

  for (const auto & belem : range)
  {
    const Elem * elem = belem->_elem;
    unsigned short int side = belem->_side;
    BoundaryID boundary_id = belem->_bnd_id;

    // need to update the boundary ID in assembly
    _problem.setCurrentBoundaryID(boundary_id, _tid);

    if (elem->processor_id() == _problem.processor_id())
    {
      // prepare variables
      for (auto * var : _aux_vars[_tid])
        var->prepareAux();

      // Locate the AuxKernel objects for the current BoundaryID
      const auto iter = boundary_kernels.find(boundary_id);

      if (iter != boundary_kernels.end() && !(iter->second.empty()))
      {
        _problem.setCurrentSubdomainID(elem, _tid);
        _problem.prepare(elem, _tid);
        _problem.reinitElemFace(elem, side, boundary_id, _tid);

        if (_need_materials)
        {
          std::set<unsigned int> needed_mat_props;
          for (const auto & aux : iter->second)
          {
            const std::set<unsigned int> & mp_deps = aux->getMatPropDependencies();
            needed_mat_props.insert(mp_deps.begin(), mp_deps.end());
          }
          _problem.setActiveMaterialProperties(needed_mat_props, _tid);

          const Elem * neighbor = elem->neighbor_ptr(side);

          _problem.reinitMaterialsFace(elem->subdomain_id(), _tid);
          if (neighbor != nullptr)
            if (neighbor->active())
            {
              SwapBackSentinel neighbor_sentinel(
                  _problem, &FEProblem::swapBackMaterialsNeighbor, _tid);
              _problem.reinitNeighbor(elem, side, _tid);
            }

          _problem.reinitMaterialsBoundary(boundary_id, _tid);
          // We need to think about whether it makes sense to do interface materials here because in
          // order for them to function properly we would also need to reinit materials on the
          // neighboring element face. That just doesn't seem appropriate
          // _problem.reinitMaterialsInterface(boundary_id, _tid);
        }

        for (const auto & aux : iter->second)
          aux->compute();

        if (_need_materials)
        {
          _problem.swapBackMaterialsFace(_tid);
          _problem.clearActiveMaterialProperties(_tid);
        }
      }

      // update the solution vector
      {
        Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
        for (auto * var : _aux_vars[_tid])
          var->insert(_aux_sys.solution());
      }
    }
  }
}

template <typename AuxKernelType>
void
ComputeElemAuxBcsThread<AuxKernelType>::join(const ComputeElemAuxBcsThread & /*y*/)
{
}

template class ComputeElemAuxBcsThread<AuxKernel>;
template class ComputeElemAuxBcsThread<VectorAuxKernel>;
<|endoftext|>


<commit_before>/**
 * \file
 *
 * \date   3 Jul 2013
 * \author Ben Gray (\@benjamg)
 */

#ifndef ZMQPP_CONTEXT_OPTIONS_HPP_
#define ZMQPP_CONTEXT_OPTIONS_HPP_

namespace zmqpp
{

/** \todo Expand the information on the options to make it actually useful. */
/*!
 * \brief possible Context options in zmq
 */

enum class context_option {
	io_threads  = ZMQ_IO_THREADS,          /*!< I/O thread count */
	max_sockets = ZMQ_MAX_SOCKETS,         /*!< Maximum supported sockets */
};

}

#endif /* ZMQPP_CONTEXT_OPTIONS_HPP_ */
<commit_msg>Added ipv6 flag for cool people<commit_after>/**
 * \file
 *
 * \date   3 Jul 2013
 * \author Ben Gray (\@benjamg)
 */

#ifndef ZMQPP_CONTEXT_OPTIONS_HPP_
#define ZMQPP_CONTEXT_OPTIONS_HPP_

namespace zmqpp
{

/** \todo Expand the information on the options to make it actually useful. */
/*!
 * \brief possible Context options in zmq
 */

enum class context_option {
	io_threads  = ZMQ_IO_THREADS,          /*!< I/O thread count */
	max_sockets = ZMQ_MAX_SOCKETS,         /*!< Maximum supported sockets */
#if (ZMQ_VERSION_MAJOR >= 4)
	ipv6        = ZMQ_IPV6,                /*!< IPv6 support */
#endif
};

}

#endif /* ZMQPP_CONTEXT_OPTIONS_HPP_ */
<|endoftext|>


<commit_before>// -*- c++ -*-

/*!
 * This file is part of CameraPlus.
 *
 * Copyright (C) 2012-2013 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "viewfinder.h"
#include "camera.h"
#include "cameraconfig.h"
#include "qtcamviewfinderrenderer.h"
#if defined(QT4)
#include <QDeclarativeInfo>
#elif defined(QT5)
#include <QQmlInfo>
#endif
#include <QPainter>
#include "qtcamdevice.h"
#include <QMatrix4x4>

#if defined(QT4)
Viewfinder::Viewfinder(QDeclarativeItem *parent) :
  QDeclarativeItem(parent),
#elif defined(QT5)
Viewfinder::Viewfinder(QQuickItem *parent) :
  QQuickPaintedItem(parent),
#endif
  m_renderer(0),
  m_cam(0),
  m_conf(0),
  m_dev(0),
  m_enabled(true) {

#if defined(QT4)
  setFlag(QGraphicsItem::ItemHasNoContents, false);
#endif

#if defined(QT5)
  setRenderTarget(QQuickPaintedItem::FramebufferObject);
  setSmooth(false);
  setAntialiasing(false);
#endif
}

Viewfinder::~Viewfinder() {

}

bool Viewfinder::isRenderingEnabled() const {
  return m_enabled;
}

void Viewfinder::setRenderingEnabled(bool enabled) {
  if (m_enabled != enabled) {
    m_enabled = enabled;
    emit renderingEnabledChanged();
  }
}

Camera *Viewfinder::camera() const {
  return m_cam;
}

void Viewfinder::setCamera(Camera *camera) {
  if (m_cam == camera) {
    return;
  }

  if (m_cam && m_cam != camera) {
    qmlInfo(this) << "Cannot reset Camera";
    return;
  }

  if (!camera) {
    qmlInfo(this) << "Camera cannot be empty";
    return;
  }

  if (m_cam) {
    QObject::disconnect(m_cam, SIGNAL(deviceChanged()), this, SLOT(deviceChanged()));
    QObject::disconnect(m_cam, SIGNAL(prepareForDeviceChange()), this, SLOT(prepareForDeviceChange()));
  }

  m_cam = camera;

  if (m_cam) {
    QObject::connect(m_cam, SIGNAL(deviceChanged()), this, SLOT(deviceChanged()));
    QObject::connect(m_cam, SIGNAL(prepareForDeviceChange()), this, SLOT(prepareForDeviceChange()));
  }

  if (isComponentComplete()) {
    deviceChanged();
  }

  emit cameraChanged();
}

CameraConfig *Viewfinder::cameraConfig() const {
  return m_conf;
}

void Viewfinder::setCameraConfig(CameraConfig *config) {
  if (m_conf && m_conf != config) {
    qmlInfo(this) << "Cannot reset CameraConfig";
    return;
  }

  if (!config) {
    qmlInfo(this) << "CameraConfig cannot be empty";
    return;
  }

  if (m_conf == config) {
    return;
  }

  m_conf = config;

  if (isComponentComplete()) {
    deviceChanged();
  }

  emit cameraConfigChanged();
}

#if defined(QT4)
void Viewfinder::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
		       QWidget *widget) {

  Q_UNUSED(widget);
  Q_UNUSED(option);
  painter->fillRect(boundingRect(), Qt::black);
#elif defined(QT5)
void Viewfinder::paint(QPainter *painter) {
  painter->fillRect(contentsBoundingRect(), Qt::black);
#endif

  if (!m_renderer || !m_enabled) {
    return;
  }

  bool needsNativePainting = m_renderer->needsNativePainting();

  if (needsNativePainting) {
    painter->beginNativePainting();
  }

  m_renderer->paint(QMatrix4x4(painter->combinedTransform()), painter->viewport());

  if (needsNativePainting) {
    painter->endNativePainting();
  }
}

QRectF Viewfinder::renderArea() const {
  return m_renderer ? m_renderer->renderArea() : QRectF();
}

QSizeF Viewfinder::videoResolution() const {
  return m_renderer ? m_renderer->videoResolution() : QSizeF();
}

void Viewfinder::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) {
#if defined(QT4)
  QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
#elif defined(QT5)
  QQuickPaintedItem::geometryChanged(newGeometry, oldGeometry);
#endif

  if (m_renderer) {
    m_renderer->resize(newGeometry.size());
  }
}

void Viewfinder::componentComplete() {
#if defined(QT4)
  QDeclarativeItem::componentComplete();
#elif defined(QT5)
  QQuickPaintedItem::componentComplete();
#endif

  if (!m_cam) {
    qmlInfo(this) << "Camera not set";
    return;
  }

  if (!m_conf) {
    qmlInfo(this) << "CameraConfig not set";
    return;
  }

  m_renderer = QtCamViewfinderRenderer::create(m_conf->config(), this);
  if (!m_renderer) {
    qmlInfo(this) << "Failed to create viewfinder renderer";
    return;
  }

  m_renderer->resize(QSizeF(width(), height()));
  QObject::connect(m_renderer, SIGNAL(updateRequested()), this, SLOT(updateRequested()));
  QObject::connect(m_renderer, SIGNAL(renderAreaChanged()), this, SIGNAL(renderAreaChanged()));
  QObject::connect(m_renderer, SIGNAL(videoResolutionChanged()), this, SIGNAL(videoResolutionChanged()));
}

void Viewfinder::deviceChanged() {
  if (!m_renderer) {
    qmlInfo(this) << "No renderer";
    return;
  }

  if (m_dev) {
    qmlInfo(this) << "Cannot set a new device without cleaning up the existing one";
    abort();
  }

  m_dev = m_cam->device();

  if (m_dev) {
    m_dev->setViewfinder(this);
  }

  emit renderAreaChanged();
  emit videoResolutionChanged();
}

GstElement *Viewfinder::sinkElement() {
  return m_renderer ? m_renderer->sinkElement() : 0;
}

void Viewfinder::stop() {
  if (m_renderer) {
    m_renderer->reset();
  }
}

void Viewfinder::updateRequested() {
  if (m_enabled) {
    update();
  }
}

void Viewfinder::prepareForDeviceChange() {
  if (m_dev) {
    m_dev->setViewfinder(0);
    m_dev = 0;
  }
}
<commit_msg>Unset QtCamdevice viewfinder when Viewfinder is being destructed.<commit_after>// -*- c++ -*-

/*!
 * This file is part of CameraPlus.
 *
 * Copyright (C) 2012-2013 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "viewfinder.h"
#include "camera.h"
#include "cameraconfig.h"
#include "qtcamviewfinderrenderer.h"
#if defined(QT4)
#include <QDeclarativeInfo>
#elif defined(QT5)
#include <QQmlInfo>
#endif
#include <QPainter>
#include "qtcamdevice.h"
#include <QMatrix4x4>

#if defined(QT4)
Viewfinder::Viewfinder(QDeclarativeItem *parent) :
  QDeclarativeItem(parent),
#elif defined(QT5)
Viewfinder::Viewfinder(QQuickItem *parent) :
  QQuickPaintedItem(parent),
#endif
  m_renderer(0),
  m_cam(0),
  m_conf(0),
  m_dev(0),
  m_enabled(true) {

#if defined(QT4)
  setFlag(QGraphicsItem::ItemHasNoContents, false);
#endif

#if defined(QT5)
  setRenderTarget(QQuickPaintedItem::FramebufferObject);
  setSmooth(false);
  setAntialiasing(false);
#endif
}

Viewfinder::~Viewfinder() {
  if (m_cam) {
    m_cam->stop(true);
  }

  if (m_dev) {
    m_dev->setViewfinder(0);
  }
}

bool Viewfinder::isRenderingEnabled() const {
  return m_enabled;
}

void Viewfinder::setRenderingEnabled(bool enabled) {
  if (m_enabled != enabled) {
    m_enabled = enabled;
    emit renderingEnabledChanged();
  }
}

Camera *Viewfinder::camera() const {
  return m_cam;
}

void Viewfinder::setCamera(Camera *camera) {
  if (m_cam == camera) {
    return;
  }

  if (m_cam && m_cam != camera) {
    qmlInfo(this) << "Cannot reset Camera";
    return;
  }

  if (!camera) {
    qmlInfo(this) << "Camera cannot be empty";
    return;
  }

  if (m_cam) {
    QObject::disconnect(m_cam, SIGNAL(deviceChanged()), this, SLOT(deviceChanged()));
    QObject::disconnect(m_cam, SIGNAL(prepareForDeviceChange()), this, SLOT(prepareForDeviceChange()));
  }

  m_cam = camera;

  if (m_cam) {
    QObject::connect(m_cam, SIGNAL(deviceChanged()), this, SLOT(deviceChanged()));
    QObject::connect(m_cam, SIGNAL(prepareForDeviceChange()), this, SLOT(prepareForDeviceChange()));
  }

  if (isComponentComplete()) {
    deviceChanged();
  }

  emit cameraChanged();
}

CameraConfig *Viewfinder::cameraConfig() const {
  return m_conf;
}

void Viewfinder::setCameraConfig(CameraConfig *config) {
  if (m_conf && m_conf != config) {
    qmlInfo(this) << "Cannot reset CameraConfig";
    return;
  }

  if (!config) {
    qmlInfo(this) << "CameraConfig cannot be empty";
    return;
  }

  if (m_conf == config) {
    return;
  }

  m_conf = config;

  if (isComponentComplete()) {
    deviceChanged();
  }

  emit cameraConfigChanged();
}

#if defined(QT4)
void Viewfinder::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
		       QWidget *widget) {

  Q_UNUSED(widget);
  Q_UNUSED(option);
  painter->fillRect(boundingRect(), Qt::black);
#elif defined(QT5)
void Viewfinder::paint(QPainter *painter) {
  painter->fillRect(contentsBoundingRect(), Qt::black);
#endif

  if (!m_renderer || !m_enabled) {
    return;
  }

  bool needsNativePainting = m_renderer->needsNativePainting();

  if (needsNativePainting) {
    painter->beginNativePainting();
  }

  m_renderer->paint(QMatrix4x4(painter->combinedTransform()), painter->viewport());

  if (needsNativePainting) {
    painter->endNativePainting();
  }
}

QRectF Viewfinder::renderArea() const {
  return m_renderer ? m_renderer->renderArea() : QRectF();
}

QSizeF Viewfinder::videoResolution() const {
  return m_renderer ? m_renderer->videoResolution() : QSizeF();
}

void Viewfinder::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) {
#if defined(QT4)
  QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
#elif defined(QT5)
  QQuickPaintedItem::geometryChanged(newGeometry, oldGeometry);
#endif

  if (m_renderer) {
    m_renderer->resize(newGeometry.size());
  }
}

void Viewfinder::componentComplete() {
#if defined(QT4)
  QDeclarativeItem::componentComplete();
#elif defined(QT5)
  QQuickPaintedItem::componentComplete();
#endif

  if (!m_cam) {
    qmlInfo(this) << "Camera not set";
    return;
  }

  if (!m_conf) {
    qmlInfo(this) << "CameraConfig not set";
    return;
  }

  m_renderer = QtCamViewfinderRenderer::create(m_conf->config(), this);
  if (!m_renderer) {
    qmlInfo(this) << "Failed to create viewfinder renderer";
    return;
  }

  m_renderer->resize(QSizeF(width(), height()));
  QObject::connect(m_renderer, SIGNAL(updateRequested()), this, SLOT(updateRequested()));
  QObject::connect(m_renderer, SIGNAL(renderAreaChanged()), this, SIGNAL(renderAreaChanged()));
  QObject::connect(m_renderer, SIGNAL(videoResolutionChanged()), this, SIGNAL(videoResolutionChanged()));
}

void Viewfinder::deviceChanged() {
  if (!m_renderer) {
    qmlInfo(this) << "No renderer";
    return;
  }

  if (m_dev) {
    qmlInfo(this) << "Cannot set a new device without cleaning up the existing one";
    abort();
  }

  m_dev = m_cam->device();

  if (m_dev) {
    m_dev->setViewfinder(this);
  }

  emit renderAreaChanged();
  emit videoResolutionChanged();
}

GstElement *Viewfinder::sinkElement() {
  return m_renderer ? m_renderer->sinkElement() : 0;
}

void Viewfinder::stop() {
  if (m_renderer) {
    m_renderer->reset();
  }
}

void Viewfinder::updateRequested() {
  if (m_enabled) {
    update();
  }
}

void Viewfinder::prepareForDeviceChange() {
  if (m_dev) {
    m_dev->setViewfinder(0);
    m_dev = 0;
  }
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_FUN_LGAMMA_HPP
#define STAN_MATH_PRIM_FUN_LGAMMA_HPP

/**
 * The lgamma implementation in stan-math is based on either the
 * reentrant safe lgamma_r implementation from C or the
 * boost::math::lgamma implementation. The reentrant safe lgamma_r
 * implementation is preferred as it is faster when compared to the
 * boost version. However, the reentrant safe lgamma_r C function is
 * not available with MinGW compilers used on Windows. Therefore, the
 * boost version is used on Windows with MinGW compilers as fall
 * back. For details on the speed evaluations, please refer to
 * https://github.com/stan-dev/math/pull/1255 .
 */
#if !__MINGW32__ || !_BOOST_LGAMMA
// _REENTRANT must be defined during compilation to ensure that cmath
// exports the reentrant safe lgamma_r version.
#if !_REENTRANT
#error \
    "stan-math requires _REENTRANT being defined during compilation" \
    "to make lgamma_r available."
#endif
#include <cmath>
#else
// MinGW compilers on Windows do not provide the reentrant lgamma_r
// such that we fall back to boost whenever we are on MinGW.
#include <stan/math/prim/fun/boost_policy.hpp>
#include <boost/math/special_functions/gamma.hpp>
#include <limits>
#endif
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/functor/apply_scalar_unary.hpp>

namespace stan {
namespace math {

/**
 * Return the natural logarithm of the gamma function applied to
 * the specified argument.
 *
   \f[
   \mbox{lgamma}(x) =
   \begin{cases}
     \textrm{error} & \mbox{if } x\in \{\dots, -3, -2, -1, 0\}\\
     \ln\Gamma(x) & \mbox{if } x\not\in \{\dots, -3, -2, -1, 0\}\\[6pt]
     \textrm{NaN} & \mbox{if } x = \textrm{NaN}
   \end{cases}
   \f]

   \f[
   \frac{\partial\, \mbox{lgamma}(x)}{\partial x} =
   \begin{cases}
     \textrm{error} & \mbox{if } x\in \{\dots, -3, -2, -1, 0\}\\
     \Psi(x) & \mbox{if } x\not\in \{\dots, -3, -2, -1, 0\}\\[6pt]
     \textrm{NaN} & \mbox{if } x = \textrm{NaN}
   \end{cases}
\f]
*
* @param x argument
* @return natural logarithm of the gamma function applied to
* argument
*/
inline double lgamma(double x) {
#if !__MINGW32__ || !_BOOST_LGAMMA
  int sign = 1;
  return ::lgamma_r(x, &sign);
#else
  if (unlikely(x == 0.0))
    return std::numeric_limits<double>::infinity();
  return boost::math::lgamma(x, boost_policy_t<>());
#endif
}

/**
 * Return the natural logarithm of the gamma function applied
 * to the specified argument.
 *
 * @param x argument
 * @return natural logarithm of the gamma function applied to
 * argument
 */
inline double lgamma(int x) {
#if !__MINGW32__ || !_BOOST_LGAMMA
  int sign = 1;
  return ::lgamma_r(x, &sign);
#else
  if (unlikely(x == 0.0))
    return std::numeric_limits<double>::infinity();
  return boost::math::lgamma(x, boost_policy_t<>());
#endif
}

/**
 * Structure to wrap lgamma() so that it can be vectorized.
 *
 * @tparam T type of variable
 * @param x variable
 * @return Natural log of the gamma function applied to x.
 * @throw std::domain_error if x is a negative integer or 0.
 */
struct lgamma_fun {
  template <typename T>
  static inline T fun(const T& x) {
    return lgamma(x);
  }
};

/**
 * Vectorized version of lgamma().
 *
 * @tparam T type of container
 * @param x container
 * @return Natural log of the gamma function
 *         applied to each value in x.
 * @throw std::domain_error if any value is a negative integer or 0.
 */
template <typename T, require_not_var_matrix_t<T>* = nullptr,
          require_not_nonscalar_prim_or_rev_kernel_expression_t<T>* = nullptr>
inline auto lgamma(const T& x) {
  return apply_scalar_unary<lgamma_fun, T>::apply(x);
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>Wrong logic<commit_after>#ifndef STAN_MATH_PRIM_FUN_LGAMMA_HPP
#define STAN_MATH_PRIM_FUN_LGAMMA_HPP

/**
 * The lgamma implementation in stan-math is based on either the
 * reentrant safe lgamma_r implementation from C or the
 * boost::math::lgamma implementation. The reentrant safe lgamma_r
 * implementation is preferred as it is faster when compared to the
 * boost version. However, the reentrant safe lgamma_r C function is
 * not available with MinGW compilers used on Windows. Therefore, the
 * boost version is used on Windows with MinGW compilers as fall
 * back. For details on the speed evaluations, please refer to
 * https://github.com/stan-dev/math/pull/1255 .
 */
#if !__MINGW32__ && !_BOOST_LGAMMA
// _REENTRANT must be defined during compilation to ensure that cmath
// exports the reentrant safe lgamma_r version.
#if !_REENTRANT
#error \
    "stan-math requires _REENTRANT being defined during compilation" \
    "to make lgamma_r available."
#endif
#include <cmath>
#else
// MinGW compilers on Windows do not provide the reentrant lgamma_r
// such that we fall back to boost whenever we are on MinGW.
#include <stan/math/prim/fun/boost_policy.hpp>
#include <boost/math/special_functions/gamma.hpp>
#include <limits>
#endif
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/functor/apply_scalar_unary.hpp>

namespace stan {
namespace math {

/**
 * Return the natural logarithm of the gamma function applied to
 * the specified argument.
 *
   \f[
   \mbox{lgamma}(x) =
   \begin{cases}
     \textrm{error} & \mbox{if } x\in \{\dots, -3, -2, -1, 0\}\\
     \ln\Gamma(x) & \mbox{if } x\not\in \{\dots, -3, -2, -1, 0\}\\[6pt]
     \textrm{NaN} & \mbox{if } x = \textrm{NaN}
   \end{cases}
   \f]

   \f[
   \frac{\partial\, \mbox{lgamma}(x)}{\partial x} =
   \begin{cases}
     \textrm{error} & \mbox{if } x\in \{\dots, -3, -2, -1, 0\}\\
     \Psi(x) & \mbox{if } x\not\in \{\dots, -3, -2, -1, 0\}\\[6pt]
     \textrm{NaN} & \mbox{if } x = \textrm{NaN}
   \end{cases}
\f]
*
* @param x argument
* @return natural logarithm of the gamma function applied to
* argument
*/
inline double lgamma(double x) {
#if !__MINGW32__ && !_BOOST_LGAMMA
  int sign = 1;
  return ::lgamma_r(x, &sign);
#else
  if (unlikely(x == 0.0))
    return std::numeric_limits<double>::infinity();
  return boost::math::lgamma(x, boost_policy_t<>());
#endif
}

/**
 * Return the natural logarithm of the gamma function applied
 * to the specified argument.
 *
 * @param x argument
 * @return natural logarithm of the gamma function applied to
 * argument
 */
inline double lgamma(int x) {
#if !__MINGW32__ && !_BOOST_LGAMMA
  int sign = 1;
  return ::lgamma_r(x, &sign);
#else
  if (unlikely(x == 0.0))
    return std::numeric_limits<double>::infinity();
  return boost::math::lgamma(x, boost_policy_t<>());
#endif
}

/**
 * Structure to wrap lgamma() so that it can be vectorized.
 *
 * @tparam T type of variable
 * @param x variable
 * @return Natural log of the gamma function applied to x.
 * @throw std::domain_error if x is a negative integer or 0.
 */
struct lgamma_fun {
  template <typename T>
  static inline T fun(const T& x) {
    return lgamma(x);
  }
};

/**
 * Vectorized version of lgamma().
 *
 * @tparam T type of container
 * @param x container
 * @return Natural log of the gamma function
 *         applied to each value in x.
 * @throw std::domain_error if any value is a negative integer or 0.
 */
template <typename T, require_not_var_matrix_t<T>* = nullptr,
          require_not_nonscalar_prim_or_rev_kernel_expression_t<T>* = nullptr>
inline auto lgamma(const T& x) {
  return apply_scalar_unary<lgamma_fun, T>::apply(x);
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <memory>

#include <unotools/mediadescriptor.hxx>
#include <unotools/ucbstreamhelper.hxx>

#include <document.hxx>
#include <mathtype.hxx>
#include <unomodel.hxx>

using namespace ::com::sun::star;

/// Invokes the MathType importer via UNO.
class MathTypeFilter : public cppu::WeakImplHelper
    <
    document::XFilter,
    document::XImporter,
    lang::XServiceInfo
    >
{
    uno::Reference<uno::XComponentContext> m_xContext;
    uno::Reference<lang::XComponent> m_xDstDoc;

public:
    MathTypeFilter(const uno::Reference<uno::XComponentContext>& xContext);
    virtual ~MathTypeFilter();

    // XFilter
    virtual sal_Bool SAL_CALL filter(const uno::Sequence<beans::PropertyValue>& rDescriptor) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL cancel() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE;

    // XImporter
    virtual void SAL_CALL setTargetDocument(const uno::Reference<lang::XComponent>& xDoc) throw (lang::IllegalArgumentException, uno::RuntimeException, std::exception) SAL_OVERRIDE;

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual uno::Sequence<OUString> SAL_CALL getSupportedServiceNames() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE;
};

MathTypeFilter::MathTypeFilter(const uno::Reference< uno::XComponentContext >& rxContext)
    : m_xContext(rxContext)
{
}

MathTypeFilter::~MathTypeFilter()
{
}

sal_Bool MathTypeFilter::filter(const uno::Sequence<beans::PropertyValue>& rDescriptor) throw(uno::RuntimeException, std::exception)
{
    bool bSuccess = false;
    try
    {
        utl::MediaDescriptor aMediaDesc(rDescriptor);
        aMediaDesc.addInputStream();
        uno::Reference<io::XInputStream> xInputStream;
        aMediaDesc[utl::MediaDescriptor::PROP_INPUTSTREAM()] >>= xInputStream;
        std::unique_ptr<SvStream> pStream(utl::UcbStreamHelper::CreateStream(xInputStream));
        if (pStream)
        {
            if (SotStorage::IsStorageFile(pStream.get()))
            {
                tools::SvRef<SotStorage> aStorage(new SotStorage(pStream.get(), false));
                // Is this a MathType Storage?
                if (aStorage->IsStream(OUString("Equation Native")))
                {
                    if (SmModel* pModel = dynamic_cast<SmModel*>(m_xDstDoc.get()))
                    {
                        SmDocShell* pDocShell = static_cast<SmDocShell*>(pModel->GetObjectShell());
                        OUString aText = pDocShell->GetText();
                        MathType aEquation(aText);
                        bSuccess = aEquation.Parse(aStorage) == 1;
                        if (bSuccess)
                        {
                            pDocShell->SetText(aText);
                            pDocShell->Parse();
                        }
                    }
                }
            }
        }
    }
    catch (const uno::Exception& rException)
    {
        SAL_WARN("starmath", "Exception caught: " << rException.Message);
    }
    return bSuccess;
}

void MathTypeFilter::cancel() throw(uno::RuntimeException, std::exception)
{
}

void MathTypeFilter::setTargetDocument(const uno::Reference< lang::XComponent >& xDoc) throw(lang::IllegalArgumentException, uno::RuntimeException, std::exception)
{
    m_xDstDoc = xDoc;
}

OUString MathTypeFilter::getImplementationName() throw(uno::RuntimeException, std::exception)
{
    return OUString("com.sun.star.comp.Math.MathTypeFilter");
}

sal_Bool MathTypeFilter::supportsService(const OUString& rServiceName) throw(uno::RuntimeException, std::exception)
{
    return cppu::supportsService(this, rServiceName);
}

uno::Sequence<OUString> MathTypeFilter::getSupportedServiceNames() throw(uno::RuntimeException, std::exception)
{
    uno::Sequence<OUString> aRet =
    {
        OUString("com.sun.star.document.ImportFilter")
    };
    return aRet;
}

extern "C" SAL_DLLPUBLIC_EXPORT uno::XInterface* SAL_CALL com_sun_star_comp_Math_MathTypeFilter_get_implementation(uno::XComponentContext* pComponent, uno::Sequence<uno::Any> const&)
{
    return cppu::acquire(new MathTypeFilter(pComponent));
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cppcheck: noExplicitConstructor<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <memory>

#include <unotools/mediadescriptor.hxx>
#include <unotools/ucbstreamhelper.hxx>

#include <document.hxx>
#include <mathtype.hxx>
#include <unomodel.hxx>

using namespace ::com::sun::star;

/// Invokes the MathType importer via UNO.
class MathTypeFilter : public cppu::WeakImplHelper
    <
    document::XFilter,
    document::XImporter,
    lang::XServiceInfo
    >
{
    uno::Reference<uno::XComponentContext> m_xContext;
    uno::Reference<lang::XComponent> m_xDstDoc;

public:
    explicit MathTypeFilter(const uno::Reference<uno::XComponentContext>& xContext);
    virtual ~MathTypeFilter();

    // XFilter
    virtual sal_Bool SAL_CALL filter(const uno::Sequence<beans::PropertyValue>& rDescriptor) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL cancel() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE;

    // XImporter
    virtual void SAL_CALL setTargetDocument(const uno::Reference<lang::XComponent>& xDoc) throw (lang::IllegalArgumentException, uno::RuntimeException, std::exception) SAL_OVERRIDE;

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual uno::Sequence<OUString> SAL_CALL getSupportedServiceNames() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE;
};

MathTypeFilter::MathTypeFilter(const uno::Reference< uno::XComponentContext >& rxContext)
    : m_xContext(rxContext)
{
}

MathTypeFilter::~MathTypeFilter()
{
}

sal_Bool MathTypeFilter::filter(const uno::Sequence<beans::PropertyValue>& rDescriptor) throw(uno::RuntimeException, std::exception)
{
    bool bSuccess = false;
    try
    {
        utl::MediaDescriptor aMediaDesc(rDescriptor);
        aMediaDesc.addInputStream();
        uno::Reference<io::XInputStream> xInputStream;
        aMediaDesc[utl::MediaDescriptor::PROP_INPUTSTREAM()] >>= xInputStream;
        std::unique_ptr<SvStream> pStream(utl::UcbStreamHelper::CreateStream(xInputStream));
        if (pStream)
        {
            if (SotStorage::IsStorageFile(pStream.get()))
            {
                tools::SvRef<SotStorage> aStorage(new SotStorage(pStream.get(), false));
                // Is this a MathType Storage?
                if (aStorage->IsStream(OUString("Equation Native")))
                {
                    if (SmModel* pModel = dynamic_cast<SmModel*>(m_xDstDoc.get()))
                    {
                        SmDocShell* pDocShell = static_cast<SmDocShell*>(pModel->GetObjectShell());
                        OUString aText = pDocShell->GetText();
                        MathType aEquation(aText);
                        bSuccess = aEquation.Parse(aStorage) == 1;
                        if (bSuccess)
                        {
                            pDocShell->SetText(aText);
                            pDocShell->Parse();
                        }
                    }
                }
            }
        }
    }
    catch (const uno::Exception& rException)
    {
        SAL_WARN("starmath", "Exception caught: " << rException.Message);
    }
    return bSuccess;
}

void MathTypeFilter::cancel() throw(uno::RuntimeException, std::exception)
{
}

void MathTypeFilter::setTargetDocument(const uno::Reference< lang::XComponent >& xDoc) throw(lang::IllegalArgumentException, uno::RuntimeException, std::exception)
{
    m_xDstDoc = xDoc;
}

OUString MathTypeFilter::getImplementationName() throw(uno::RuntimeException, std::exception)
{
    return OUString("com.sun.star.comp.Math.MathTypeFilter");
}

sal_Bool MathTypeFilter::supportsService(const OUString& rServiceName) throw(uno::RuntimeException, std::exception)
{
    return cppu::supportsService(this, rServiceName);
}

uno::Sequence<OUString> MathTypeFilter::getSupportedServiceNames() throw(uno::RuntimeException, std::exception)
{
    uno::Sequence<OUString> aRet =
    {
        OUString("com.sun.star.document.ImportFilter")
    };
    return aRet;
}

extern "C" SAL_DLLPUBLIC_EXPORT uno::XInterface* SAL_CALL com_sun_star_comp_Math_MathTypeFilter_get_implementation(uno::XComponentContext* pComponent, uno::Sequence<uno::Any> const&)
{
    return cppu::acquire(new MathTypeFilter(pComponent));
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/* Copyright (c) 2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/

/**
 * @file mc_att_control_base.cpp
 *
 * MC Attitude Controller : Control and math code
 *
 * @author Tobias Naegeli <naegelit@student.ethz.ch>
 * @author Lorenz Meier <lm@inf.ethz.ch>
 * @author Anton Babushkin <anton.babushkin@me.com>
 * @author Thomas Gubler <thomasgubler@gmail.com>
 * @author Julian Oes <julian@oes.ch>
 * @author Roman Bapst <bapstr@ethz.ch>
 *
 */

#include "mc_att_control_base.h"
#include <geo/geo.h>
#include <math.h>
#include <lib/mathlib/mathlib.h>

#ifdef CONFIG_ARCH_ARM
#else
#include <cmath>
using namespace std;
#endif

MulticopterAttitudeControlBase::MulticopterAttitudeControlBase() :
	_v_att_sp_mod(),
	_v_rates_sp_mod(),
	_actuators(),
	_publish_att_sp(false)

{
	_params.att_p.zero();
	_params.rate_p.zero();
	_params.rate_i.zero();
	_params.rate_d.zero();
	_params.yaw_ff = 0.0f;
	_params.yaw_rate_max = 0.0f;
	_params.man_roll_max = 0.0f;
	_params.man_pitch_max = 0.0f;
	_params.man_yaw_max = 0.0f;
	_params.acro_rate_max.zero();

	_rates_prev.zero();
	_rates_sp.zero();
	_rates_int.zero();
	_thrust_sp = 0.0f;
	_att_control.zero();

	_I.identity();
}

MulticopterAttitudeControlBase::~MulticopterAttitudeControlBase()
{
}

void MulticopterAttitudeControlBase::control_attitude(float dt)
{
	float yaw_sp_move_rate = 0.0f;
	_publish_att_sp = false;

	if (_v_control_mode->data().flag_control_manual_enabled) {
		/* manual input, set or modify attitude setpoint */

		if (_v_control_mode->data().flag_control_velocity_enabled
		    || _v_control_mode->data().flag_control_climb_rate_enabled) {
			/* in assisted modes poll 'vehicle_attitude_setpoint' topic and modify it */
			//XXX get rid of memcpy
			memcpy(&(_v_att_sp_mod.data()), &_v_att_sp->data(), sizeof(_v_att_sp_mod.data()));
		}

		if (!_v_control_mode->data().flag_control_climb_rate_enabled) {
			/* pass throttle directly if not in altitude stabilized mode */
			_v_att_sp_mod.data().thrust = _manual_control_sp->data().z;
			_publish_att_sp = true;
		}

		if (!_armed->data().armed) {
			/* reset yaw setpoint when disarmed */
			_reset_yaw_sp = true;
		}

		/* move yaw setpoint in all modes */
		if (_v_att_sp_mod.data().thrust < 0.1f) {
			// TODO
			//if (_status.condition_landed) {
			/* reset yaw setpoint if on ground */
			//	reset_yaw_sp = true;
			//}
		} else {
			/* move yaw setpoint */
			yaw_sp_move_rate = _manual_control_sp->data().r * _params.man_yaw_max;
			_v_att_sp_mod.data().yaw_body = _wrap_pi(
						     _v_att_sp_mod.data().yaw_body + yaw_sp_move_rate * dt);
			float yaw_offs_max = _params.man_yaw_max / _params.att_p(2);
			float yaw_offs = _wrap_pi(_v_att_sp_mod.data().yaw_body - _v_att->data().yaw);

			if (yaw_offs < -yaw_offs_max) {
				_v_att_sp_mod.data().yaw_body = _wrap_pi(_v_att->data().yaw - yaw_offs_max);

			} else if (yaw_offs > yaw_offs_max) {
				_v_att_sp_mod.data().yaw_body = _wrap_pi(_v_att->data().yaw + yaw_offs_max);
			}

			_v_att_sp_mod.data().R_valid = false;
			// _publish_att_sp = true;
		}

		/* reset yaw setpoint to current position if needed */
		if (_reset_yaw_sp) {
			_reset_yaw_sp = false;
			_v_att_sp_mod.data().yaw_body = _v_att->data().yaw;
			_v_att_sp_mod.data().R_valid = false;
			// _publish_att_sp = true;
		}

		if (!_v_control_mode->data().flag_control_velocity_enabled) {
			/* update attitude setpoint if not in position control mode */
			_v_att_sp_mod.data().roll_body = _manual_control_sp->data().y * _params.man_roll_max;
			_v_att_sp_mod.data().pitch_body = -_manual_control_sp->data().x
					       * _params.man_pitch_max;
			_v_att_sp_mod.data().R_valid = false;
			// _publish_att_sp = true;
		}

	} else {
		/* in non-manual mode use 'vehicle_attitude_setpoint' topic */
		//XXX get rid of memcpy
		memcpy(&(_v_att_sp_mod.data()), &_v_att_sp->data(), sizeof(_v_att_sp_mod.data()));

		/* reset yaw setpoint after non-manual control mode */
		_reset_yaw_sp = true;
	}

	_thrust_sp = _v_att_sp_mod.data().thrust;

	/* construct attitude setpoint rotation matrix */
	math::Matrix<3, 3> R_sp;

	if (_v_att_sp_mod.data().R_valid) {
		/* rotation matrix in _att_sp is valid, use it */
		R_sp.set(&_v_att_sp_mod.data().R_body[0]);

	} else {
		/* rotation matrix in _att_sp is not valid, use euler angles instead */
		R_sp.from_euler(_v_att_sp_mod.data().roll_body, _v_att_sp_mod.data().pitch_body,
				_v_att_sp_mod.data().yaw_body);

		/* copy rotation matrix back to setpoint struct */
		memcpy(&_v_att_sp_mod.data().R_body[0], &R_sp.data[0][0],
		       sizeof(_v_att_sp_mod.data().R_body));
		_v_att_sp_mod.data().R_valid = true;
	}

	/* rotation matrix for current state */
	math::Matrix<3, 3> R;
	R.set(_v_att->data().R);

	/* all input data is ready, run controller itself */

	/* try to move thrust vector shortest way, because yaw response is slower than roll/pitch */
	math::Vector < 3 > R_z(R(0, 2), R(1, 2), R(2, 2));
	math::Vector < 3 > R_sp_z(R_sp(0, 2), R_sp(1, 2), R_sp(2, 2));

	/* axis and sin(angle) of desired rotation */
	math::Vector < 3 > e_R = R.transposed() * (R_z % R_sp_z);

	/* calculate angle error */
	float e_R_z_sin = e_R.length();
	float e_R_z_cos = R_z * R_sp_z;

	/* calculate weight for yaw control */
	float yaw_w = R_sp(2, 2) * R_sp(2, 2);

	/* calculate rotation matrix after roll/pitch only rotation */
	math::Matrix<3, 3> R_rp;

	if (e_R_z_sin > 0.0f) {
		/* get axis-angle representation */
		float e_R_z_angle = atan2f(e_R_z_sin, e_R_z_cos);
		math::Vector < 3 > e_R_z_axis = e_R / e_R_z_sin;

		e_R = e_R_z_axis * e_R_z_angle;

		/* cross product matrix for e_R_axis */
		math::Matrix<3, 3> e_R_cp;
		e_R_cp.zero();
		e_R_cp(0, 1) = -e_R_z_axis(2);
		e_R_cp(0, 2) = e_R_z_axis(1);
		e_R_cp(1, 0) = e_R_z_axis(2);
		e_R_cp(1, 2) = -e_R_z_axis(0);
		e_R_cp(2, 0) = -e_R_z_axis(1);
		e_R_cp(2, 1) = e_R_z_axis(0);

		/* rotation matrix for roll/pitch only rotation */
		R_rp = R
		       * (_I + e_R_cp * e_R_z_sin
			  + e_R_cp * e_R_cp * (1.0f - e_R_z_cos));

	} else {
		/* zero roll/pitch rotation */
		R_rp = R;
	}

	/* R_rp and R_sp has the same Z axis, calculate yaw error */
	math::Vector < 3 > R_sp_x(R_sp(0, 0), R_sp(1, 0), R_sp(2, 0));
	math::Vector < 3 > R_rp_x(R_rp(0, 0), R_rp(1, 0), R_rp(2, 0));
	e_R(2) = atan2f((R_rp_x % R_sp_x) * R_sp_z, R_rp_x * R_sp_x) * yaw_w;

	if (e_R_z_cos < 0.0f) {
		/* for large thrust vector rotations use another rotation method:
		 * calculate angle and axis for R -> R_sp rotation directly */
		math::Quaternion q;
		q.from_dcm(R.transposed() * R_sp);
		math::Vector < 3 > e_R_d = q.imag();
		e_R_d.normalize();
		e_R_d *= 2.0f * atan2f(e_R_d.length(), q(0));

		/* use fusion of Z axis based rotation and direct rotation */
		float direct_w = e_R_z_cos * e_R_z_cos * yaw_w;
		e_R = e_R * (1.0f - direct_w) + e_R_d * direct_w;
	}

	/* calculate angular rates setpoint */
	_rates_sp = _params.att_p.emult(e_R);

	/* limit yaw rate */
	_rates_sp(2) = math::constrain(_rates_sp(2), -_params.yaw_rate_max,
				       _params.yaw_rate_max);

	/* feed forward yaw setpoint rate */
	_rates_sp(2) += yaw_sp_move_rate * yaw_w * _params.yaw_ff;
}

void MulticopterAttitudeControlBase::control_attitude_rates(float dt)
{
	/* reset integral if disarmed */
	if (!_armed->data().armed || !_v_status->data().is_rotary_wing) {
		_rates_int.zero();
	}

	/* current body angular rates */
	math::Vector < 3 > rates;
	rates(0) = _v_att->data().rollspeed;
	rates(1) = _v_att->data().pitchspeed;
	rates(2) = _v_att->data().yawspeed;

	/* angular rates error */
	math::Vector < 3 > rates_err = _rates_sp - rates;
	_att_control = _params.rate_p.emult(rates_err)
		       + _params.rate_d.emult(_rates_prev - rates) / dt + _rates_int;
	_rates_prev = rates;

	/* update integral only if not saturated on low limit */
	if (_thrust_sp > MIN_TAKEOFF_THRUST) {
		for (int i = 0; i < 3; i++) {
			if (fabsf(_att_control(i)) < _thrust_sp) {
				float rate_i = _rates_int(i)
					       + _params.rate_i(i) * rates_err(i) * dt;

				if (isfinite(
					    rate_i) && rate_i > -RATES_I_LIMIT && rate_i < RATES_I_LIMIT &&
				    _att_control(i) > -RATES_I_LIMIT && _att_control(i) < RATES_I_LIMIT) {
					_rates_int(i) = rate_i;
				}
			}
		}
	}

}

void MulticopterAttitudeControlBase::set_actuator_controls()
{
	_actuators.data().control[0] = (isfinite(_att_control(0))) ? _att_control(0) : 0.0f;
	_actuators.data().control[1] = (isfinite(_att_control(1))) ? _att_control(1) : 0.0f;
	_actuators.data().control[2] = (isfinite(_att_control(2))) ? _att_control(2) : 0.0f;
	_actuators.data().control[3] = (isfinite(_thrust_sp)) ? _thrust_sp : 0.0f;
}
<commit_msg>multiplat mc att ctrl: move yaw sp only if xy is not controlled<commit_after>/* Copyright (c) 2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/

/**
 * @file mc_att_control_base.cpp
 *
 * MC Attitude Controller : Control and math code
 *
 * @author Tobias Naegeli <naegelit@student.ethz.ch>
 * @author Lorenz Meier <lm@inf.ethz.ch>
 * @author Anton Babushkin <anton.babushkin@me.com>
 * @author Thomas Gubler <thomasgubler@gmail.com>
 * @author Julian Oes <julian@oes.ch>
 * @author Roman Bapst <bapstr@ethz.ch>
 *
 */

#include "mc_att_control_base.h"
#include <geo/geo.h>
#include <math.h>
#include <lib/mathlib/mathlib.h>

#ifdef CONFIG_ARCH_ARM
#else
#include <cmath>
using namespace std;
#endif

MulticopterAttitudeControlBase::MulticopterAttitudeControlBase() :
	_v_att_sp_mod(),
	_v_rates_sp_mod(),
	_actuators(),
	_publish_att_sp(false)

{
	_params.att_p.zero();
	_params.rate_p.zero();
	_params.rate_i.zero();
	_params.rate_d.zero();
	_params.yaw_ff = 0.0f;
	_params.yaw_rate_max = 0.0f;
	_params.man_roll_max = 0.0f;
	_params.man_pitch_max = 0.0f;
	_params.man_yaw_max = 0.0f;
	_params.acro_rate_max.zero();

	_rates_prev.zero();
	_rates_sp.zero();
	_rates_int.zero();
	_thrust_sp = 0.0f;
	_att_control.zero();

	_I.identity();
}

MulticopterAttitudeControlBase::~MulticopterAttitudeControlBase()
{
}

void MulticopterAttitudeControlBase::control_attitude(float dt)
{
	float yaw_sp_move_rate = 0.0f;
	_publish_att_sp = false;

	if (_v_control_mode->data().flag_control_manual_enabled) {
		/* manual input, set or modify attitude setpoint */

		if (_v_control_mode->data().flag_control_velocity_enabled
		    || _v_control_mode->data().flag_control_climb_rate_enabled) {
			/* in assisted modes poll 'vehicle_attitude_setpoint' topic and modify it */
			//XXX get rid of memcpy
			memcpy(&(_v_att_sp_mod.data()), &_v_att_sp->data(), sizeof(_v_att_sp_mod.data()));
		}

		if (!_v_control_mode->data().flag_control_climb_rate_enabled) {
			/* pass throttle directly if not in altitude stabilized mode */
			_v_att_sp_mod.data().thrust = _manual_control_sp->data().z;
			_publish_att_sp = true;
		}

		if (!_armed->data().armed) {
			/* reset yaw setpoint when disarmed */
			_reset_yaw_sp = true;
		}

		/* reset yaw setpoint to current position if needed */
		if (_reset_yaw_sp) {
			_reset_yaw_sp = false;
			_v_att_sp_mod.data().yaw_body = _v_att->data().yaw;
			_v_att_sp_mod.data().R_valid = false;
			// _publish_att_sp = true;
		}

		if (!_v_control_mode->data().flag_control_velocity_enabled) {

			if (_v_att_sp_mod.data().thrust < 0.1f) {
				// TODO
				//if (_status.condition_landed) {
				/* reset yaw setpoint if on ground */
				//	reset_yaw_sp = true;
				//}
			} else {
				/* move yaw setpoint */
				yaw_sp_move_rate = _manual_control_sp->data().r * _params.man_yaw_max;
				_v_att_sp_mod.data().yaw_body = _wrap_pi(
							     _v_att_sp_mod.data().yaw_body + yaw_sp_move_rate * dt);
				float yaw_offs_max = _params.man_yaw_max / _params.att_p(2);
				float yaw_offs = _wrap_pi(_v_att_sp_mod.data().yaw_body - _v_att->data().yaw);

				if (yaw_offs < -yaw_offs_max) {
					_v_att_sp_mod.data().yaw_body = _wrap_pi(_v_att->data().yaw - yaw_offs_max);

				} else if (yaw_offs > yaw_offs_max) {
					_v_att_sp_mod.data().yaw_body = _wrap_pi(_v_att->data().yaw + yaw_offs_max);
				}

				_v_att_sp_mod.data().R_valid = false;
				// _publish_att_sp = true;
			}
			/* update attitude setpoint if not in position control mode */
			_v_att_sp_mod.data().roll_body = _manual_control_sp->data().y * _params.man_roll_max;
			_v_att_sp_mod.data().pitch_body = -_manual_control_sp->data().x
					       * _params.man_pitch_max;
			_v_att_sp_mod.data().R_valid = false;
			// _publish_att_sp = true;
		}

	} else {
		/* in non-manual mode use 'vehicle_attitude_setpoint' topic */
		//XXX get rid of memcpy
		memcpy(&(_v_att_sp_mod.data()), &_v_att_sp->data(), sizeof(_v_att_sp_mod.data()));

		/* reset yaw setpoint after non-manual control mode */
		_reset_yaw_sp = true;
	}

	_thrust_sp = _v_att_sp_mod.data().thrust;

	/* construct attitude setpoint rotation matrix */
	math::Matrix<3, 3> R_sp;

	if (_v_att_sp_mod.data().R_valid) {
		/* rotation matrix in _att_sp is valid, use it */
		R_sp.set(&_v_att_sp_mod.data().R_body[0]);

	} else {
		/* rotation matrix in _att_sp is not valid, use euler angles instead */
		R_sp.from_euler(_v_att_sp_mod.data().roll_body, _v_att_sp_mod.data().pitch_body,
				_v_att_sp_mod.data().yaw_body);

		/* copy rotation matrix back to setpoint struct */
		memcpy(&_v_att_sp_mod.data().R_body[0], &R_sp.data[0][0],
		       sizeof(_v_att_sp_mod.data().R_body));
		_v_att_sp_mod.data().R_valid = true;
	}

	/* rotation matrix for current state */
	math::Matrix<3, 3> R;
	R.set(_v_att->data().R);

	/* all input data is ready, run controller itself */

	/* try to move thrust vector shortest way, because yaw response is slower than roll/pitch */
	math::Vector < 3 > R_z(R(0, 2), R(1, 2), R(2, 2));
	math::Vector < 3 > R_sp_z(R_sp(0, 2), R_sp(1, 2), R_sp(2, 2));

	/* axis and sin(angle) of desired rotation */
	math::Vector < 3 > e_R = R.transposed() * (R_z % R_sp_z);

	/* calculate angle error */
	float e_R_z_sin = e_R.length();
	float e_R_z_cos = R_z * R_sp_z;

	/* calculate weight for yaw control */
	float yaw_w = R_sp(2, 2) * R_sp(2, 2);

	/* calculate rotation matrix after roll/pitch only rotation */
	math::Matrix<3, 3> R_rp;

	if (e_R_z_sin > 0.0f) {
		/* get axis-angle representation */
		float e_R_z_angle = atan2f(e_R_z_sin, e_R_z_cos);
		math::Vector < 3 > e_R_z_axis = e_R / e_R_z_sin;

		e_R = e_R_z_axis * e_R_z_angle;

		/* cross product matrix for e_R_axis */
		math::Matrix<3, 3> e_R_cp;
		e_R_cp.zero();
		e_R_cp(0, 1) = -e_R_z_axis(2);
		e_R_cp(0, 2) = e_R_z_axis(1);
		e_R_cp(1, 0) = e_R_z_axis(2);
		e_R_cp(1, 2) = -e_R_z_axis(0);
		e_R_cp(2, 0) = -e_R_z_axis(1);
		e_R_cp(2, 1) = e_R_z_axis(0);

		/* rotation matrix for roll/pitch only rotation */
		R_rp = R
		       * (_I + e_R_cp * e_R_z_sin
			  + e_R_cp * e_R_cp * (1.0f - e_R_z_cos));

	} else {
		/* zero roll/pitch rotation */
		R_rp = R;
	}

	/* R_rp and R_sp has the same Z axis, calculate yaw error */
	math::Vector < 3 > R_sp_x(R_sp(0, 0), R_sp(1, 0), R_sp(2, 0));
	math::Vector < 3 > R_rp_x(R_rp(0, 0), R_rp(1, 0), R_rp(2, 0));
	e_R(2) = atan2f((R_rp_x % R_sp_x) * R_sp_z, R_rp_x * R_sp_x) * yaw_w;

	if (e_R_z_cos < 0.0f) {
		/* for large thrust vector rotations use another rotation method:
		 * calculate angle and axis for R -> R_sp rotation directly */
		math::Quaternion q;
		q.from_dcm(R.transposed() * R_sp);
		math::Vector < 3 > e_R_d = q.imag();
		e_R_d.normalize();
		e_R_d *= 2.0f * atan2f(e_R_d.length(), q(0));

		/* use fusion of Z axis based rotation and direct rotation */
		float direct_w = e_R_z_cos * e_R_z_cos * yaw_w;
		e_R = e_R * (1.0f - direct_w) + e_R_d * direct_w;
	}

	/* calculate angular rates setpoint */
	_rates_sp = _params.att_p.emult(e_R);

	/* limit yaw rate */
	_rates_sp(2) = math::constrain(_rates_sp(2), -_params.yaw_rate_max,
				       _params.yaw_rate_max);

	/* feed forward yaw setpoint rate */
	_rates_sp(2) += yaw_sp_move_rate * yaw_w * _params.yaw_ff;
}

void MulticopterAttitudeControlBase::control_attitude_rates(float dt)
{
	/* reset integral if disarmed */
	if (!_armed->data().armed || !_v_status->data().is_rotary_wing) {
		_rates_int.zero();
	}

	/* current body angular rates */
	math::Vector < 3 > rates;
	rates(0) = _v_att->data().rollspeed;
	rates(1) = _v_att->data().pitchspeed;
	rates(2) = _v_att->data().yawspeed;

	/* angular rates error */
	math::Vector < 3 > rates_err = _rates_sp - rates;
	_att_control = _params.rate_p.emult(rates_err)
		       + _params.rate_d.emult(_rates_prev - rates) / dt + _rates_int;
	_rates_prev = rates;

	/* update integral only if not saturated on low limit */
	if (_thrust_sp > MIN_TAKEOFF_THRUST) {
		for (int i = 0; i < 3; i++) {
			if (fabsf(_att_control(i)) < _thrust_sp) {
				float rate_i = _rates_int(i)
					       + _params.rate_i(i) * rates_err(i) * dt;

				if (isfinite(
					    rate_i) && rate_i > -RATES_I_LIMIT && rate_i < RATES_I_LIMIT &&
				    _att_control(i) > -RATES_I_LIMIT && _att_control(i) < RATES_I_LIMIT) {
					_rates_int(i) = rate_i;
				}
			}
		}
	}

}

void MulticopterAttitudeControlBase::set_actuator_controls()
{
	_actuators.data().control[0] = (isfinite(_att_control(0))) ? _att_control(0) : 0.0f;
	_actuators.data().control[1] = (isfinite(_att_control(1))) ? _att_control(1) : 0.0f;
	_actuators.data().control[2] = (isfinite(_att_control(2))) ? _att_control(2) : 0.0f;
	_actuators.data().control[3] = (isfinite(_thrust_sp)) ? _thrust_sp : 0.0f;
}
<|endoftext|>


<commit_before>#include <functional>
#include <future>
#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "geos/geom/CoordinateArraySequence.h"
#include "geos/geom/LinearRing.h"
#include "geos/geom/Polygon.h"
#include "geos/geom/GeometryFactory.h"
#include "feature.h"
#include "factory.h"
#include "abstractfactory.h"
#include "featurefactory.h"
#include "featurecoverage.h"
#include "featureiterator.h"
#include "symboltable.h"
#include "OperationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
//#include "commandhandler.h"
#include "gridding.h"

using namespace Ilwis;
using namespace FeatureOperations;

Gridding::Gridding()
{
}

Gridding::Gridding(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{

}

bool Gridding::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;

    for(int fx=0; fx < _xsize; ++fx) {
        for(int fy=0; fy < _ysize; ++fy) {
            Coordinate c1(_top + std::vector<double>{_cellXSize * fx, _cellYSize * fy });
            Coordinate c2(_top +std::vector<double>{_cellXSize * (fx+1), _cellYSize * fy });
            Coordinate c3(_top + std::vector<double>{_cellXSize * (fx+1), _cellYSize * (fy+1) });
            Coordinate c4(_top + std::vector<double>{_cellXSize * fx, _cellYSize * (fy+1) });
            geos::geom::CoordinateSequence *coords = new geos::geom::CoordinateArraySequence();
            coords->add(c1);
            coords->add(c2);
            coords->add(c3);
            coords->add(c4);
            coords->add(c1);
            geos::geom::LinearRing *outer = _outfeatures->geomfactory()->createLinearRing(coords);
            geos::geom::Geometry *pol = _outfeatures->geomfactory()->createPolygon(outer, 0);
            _outfeatures->newFeature(pol);
        }
    }

    if ( ctx != 0) {
        QVariant value;
        value.setValue<IFeatureCoverage>(_outfeatures);
        ctx->setOutput(symTable, value, _outfeatures->name(), itFEATURE,_outfeatures->source());
    }
    return true;
}

OperationImplementation *Gridding::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new  Gridding(metaid, expr)   ;
}

quint64 Gridding::createMetadata()
{
    QString url = QString("ilwis://operations/gridding");
    Resource resource(QUrl(url), itOPERATIONMETADATA);
    resource.addProperty("namespace","ilwis");
    resource.addProperty("longname","gridding");
    resource.addProperty("syntax","gridding(coordinatesyste,top-coordinate,x-cell-size, y-cell-size, horizontal-cells, vertical-cells)");
    resource.addProperty("description",TR("generates a new featurecoverage(polygons) were the polygons form a rectangular grid"));
    resource.addProperty("inparameters","6");
    resource.addProperty("pin_1_type", itCOORDSYSTEM);
    resource.addProperty("pin_1_name", TR("coordinate-syste,"));
    resource.addProperty("pin_1_desc",TR("The coordinate system of the to be created polygon coverage"));
    resource.addProperty("pin_2_type", itCOORDINATE);
    resource.addProperty("pin_2_name", TR("top corner"));
    resource.addProperty("pin_2_desc",TR("The top corner of the polygonmap expressed in coordinates of the coordinate system"));
    resource.addProperty("pin_3_type", itDOUBLE);
    resource.addProperty("pin_3_name", TR("X cell size"));
    resource.addProperty("pin_3_desc",TR("Size in the x direction of a cell in the grid expressed in untis of the coordinate system"));
    resource.addProperty("pin_4_type", itDOUBLE);
    resource.addProperty("pin_4_name", TR("Y cell size"));
    resource.addProperty("pin_4_desc",TR("Size in the y direction of a cell in the grid expressed in untis of the coordinate system"));
    resource.addProperty("pin_5_type", itINTEGER);
    resource.addProperty("pin_5_name", TR("Horizontal cells"));
    resource.addProperty("pin_5_desc",TR("Number of cells in the x directions"));
    resource.addProperty("pin_6_type", itINTEGER);
    resource.addProperty("pin_6_name", TR("Vertical cells"));
    resource.addProperty("pin_6_desc",TR("Number of cells in the y directions"));
    resource.addProperty("outparameters",1);
    resource.addProperty("pout_1_type", itPOLYGON);
    resource.addProperty("pout_1_name", TR("output polygon coverage"));
    resource.addProperty("pout_1_desc",TR("output polygon coverage"));

    resource.prepare();
    url += "=" + QString::number(resource.id());
    resource.setUrl(url);

    mastercatalog()->addItems({resource});
    return resource.id();
}

OperationImplementation::State Gridding::prepare(ExecutionContext *ctx, const SymbolTable &symTable)
{
    QString csyName =  _expression.parm(0).value();
    if (!_csy.prepare(csyName)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,csyName,"" );
        return sPREPAREFAILED;
    }

    QString name = _expression.parm(1).value();
    QVariant var = symTable.getValue(name);
    _top = var.value<Coordinate>();
    if (!_top.isValid() || _top.is0()) {
        _top = var.value<Coordinate>();
    }
    if (!_top.isValid() || _top.is0()) {
        ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value",name);
        return sPREPAREFAILED;
    }
    bool ok;
    _cellXSize = _expression.parm(2).value().toDouble(&ok);
    if ( !ok ) {
        ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","3");
        return sPREPAREFAILED;
    }

    _cellYSize = _expression.parm(3).value().toDouble(&ok);
    if ( !ok ) {
        ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","4");
        return sPREPAREFAILED;
    }

    _xsize = _expression.parm(4).value().toDouble(&ok);
    if ( !ok ) {
        ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","5");
        return sPREPAREFAILED;
    }

    _ysize = _expression.parm(5).value().toDouble(&ok);
    if ( !ok ) {
        ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","6");
        return sPREPAREFAILED;
    }
    QString outputName = _expression.parm(0,false).value();
     Resource resource = outputName != sUNDEF ? Resource("ilwis://internalcatalog/" + outputName, itFLATTABLE) : Resource(itFLATTABLE);
    _attTable.prepare(resource);
    IDomain covdom;
    if (!covdom.prepare("count")){
        return sPREPAREFAILED;
    }
    _attTable->addColumn(FEATUREIDCOLUMN,covdom);
    _outfeatures.prepare();
    _outfeatures->coordinateSystem(_csy);
    _outfeatures->attributeTable(_attTable);
    Envelope env(_top, _top + std::vector<double>{_cellXSize * _xsize, _cellYSize * _ysize });
    _outfeatures->envelope(env);

    return sPREPARED;
}
<commit_msg>casing<commit_after>#include <functional>
#include <future>
#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "geos/geom/CoordinateArraySequence.h"
#include "geos/geom/LinearRing.h"
#include "geos/geom/Polygon.h"
#include "geos/geom/GeometryFactory.h"
#include "feature.h"
#include "factory.h"
#include "abstractfactory.h"
#include "featurefactory.h"
#include "featurecoverage.h"
#include "featureiterator.h"
#include "symboltable.h"
#include "operationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
//#include "commandhandler.h"
#include "gridding.h"

using namespace Ilwis;
using namespace FeatureOperations;

Gridding::Gridding()
{
}

Gridding::Gridding(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{

}

bool Gridding::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;

    for(int fx=0; fx < _xsize; ++fx) {
        for(int fy=0; fy < _ysize; ++fy) {
            Coordinate c1(_top + std::vector<double>{_cellXSize * fx, _cellYSize * fy });
            Coordinate c2(_top +std::vector<double>{_cellXSize * (fx+1), _cellYSize * fy });
            Coordinate c3(_top + std::vector<double>{_cellXSize * (fx+1), _cellYSize * (fy+1) });
            Coordinate c4(_top + std::vector<double>{_cellXSize * fx, _cellYSize * (fy+1) });
            geos::geom::CoordinateSequence *coords = new geos::geom::CoordinateArraySequence();
            coords->add(c1);
            coords->add(c2);
            coords->add(c3);
            coords->add(c4);
            coords->add(c1);
            geos::geom::LinearRing *outer = _outfeatures->geomfactory()->createLinearRing(coords);
            geos::geom::Geometry *pol = _outfeatures->geomfactory()->createPolygon(outer, 0);
            _outfeatures->newFeature(pol);
        }
    }

    if ( ctx != 0) {
        QVariant value;
        value.setValue<IFeatureCoverage>(_outfeatures);
        ctx->setOutput(symTable, value, _outfeatures->name(), itFEATURE,_outfeatures->source());
    }
    return true;
}

OperationImplementation *Gridding::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new  Gridding(metaid, expr)   ;
}

quint64 Gridding::createMetadata()
{
    QString url = QString("ilwis://operations/gridding");
    Resource resource(QUrl(url), itOPERATIONMETADATA);
    resource.addProperty("namespace","ilwis");
    resource.addProperty("longname","gridding");
    resource.addProperty("syntax","gridding(coordinatesyste,top-coordinate,x-cell-size, y-cell-size, horizontal-cells, vertical-cells)");
    resource.addProperty("description",TR("generates a new featurecoverage(polygons) were the polygons form a rectangular grid"));
    resource.addProperty("inparameters","6");
    resource.addProperty("pin_1_type", itCOORDSYSTEM);
    resource.addProperty("pin_1_name", TR("coordinate-syste,"));
    resource.addProperty("pin_1_desc",TR("The coordinate system of the to be created polygon coverage"));
    resource.addProperty("pin_2_type", itCOORDINATE);
    resource.addProperty("pin_2_name", TR("top corner"));
    resource.addProperty("pin_2_desc",TR("The top corner of the polygonmap expressed in coordinates of the coordinate system"));
    resource.addProperty("pin_3_type", itDOUBLE);
    resource.addProperty("pin_3_name", TR("X cell size"));
    resource.addProperty("pin_3_desc",TR("Size in the x direction of a cell in the grid expressed in untis of the coordinate system"));
    resource.addProperty("pin_4_type", itDOUBLE);
    resource.addProperty("pin_4_name", TR("Y cell size"));
    resource.addProperty("pin_4_desc",TR("Size in the y direction of a cell in the grid expressed in untis of the coordinate system"));
    resource.addProperty("pin_5_type", itINTEGER);
    resource.addProperty("pin_5_name", TR("Horizontal cells"));
    resource.addProperty("pin_5_desc",TR("Number of cells in the x directions"));
    resource.addProperty("pin_6_type", itINTEGER);
    resource.addProperty("pin_6_name", TR("Vertical cells"));
    resource.addProperty("pin_6_desc",TR("Number of cells in the y directions"));
    resource.addProperty("outparameters",1);
    resource.addProperty("pout_1_type", itPOLYGON);
    resource.addProperty("pout_1_name", TR("output polygon coverage"));
    resource.addProperty("pout_1_desc",TR("output polygon coverage"));

    resource.prepare();
    url += "=" + QString::number(resource.id());
    resource.setUrl(url);

    mastercatalog()->addItems({resource});
    return resource.id();
}

OperationImplementation::State Gridding::prepare(ExecutionContext *ctx, const SymbolTable &symTable)
{
    QString csyName =  _expression.parm(0).value();
    if (!_csy.prepare(csyName)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,csyName,"" );
        return sPREPAREFAILED;
    }

    QString name = _expression.parm(1).value();
    QVariant var = symTable.getValue(name);
    _top = var.value<Coordinate>();
    if (!_top.isValid() || _top.is0()) {
        _top = var.value<Coordinate>();
    }
    if (!_top.isValid() || _top.is0()) {
        ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value",name);
        return sPREPAREFAILED;
    }
    bool ok;
    _cellXSize = _expression.parm(2).value().toDouble(&ok);
    if ( !ok ) {
        ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","3");
        return sPREPAREFAILED;
    }

    _cellYSize = _expression.parm(3).value().toDouble(&ok);
    if ( !ok ) {
        ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","4");
        return sPREPAREFAILED;
    }

    _xsize = _expression.parm(4).value().toDouble(&ok);
    if ( !ok ) {
        ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","5");
        return sPREPAREFAILED;
    }

    _ysize = _expression.parm(5).value().toDouble(&ok);
    if ( !ok ) {
        ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","6");
        return sPREPAREFAILED;
    }
    QString outputName = _expression.parm(0,false).value();
     Resource resource = outputName != sUNDEF ? Resource("ilwis://internalcatalog/" + outputName, itFLATTABLE) : Resource(itFLATTABLE);
    _attTable.prepare(resource);
    IDomain covdom;
    if (!covdom.prepare("count")){
        return sPREPAREFAILED;
    }
    _attTable->addColumn(FEATUREIDCOLUMN,covdom);
    _outfeatures.prepare();
    _outfeatures->coordinateSystem(_csy);
    _outfeatures->attributeTable(_attTable);
    Envelope env(_top, _top + std::vector<double>{_cellXSize * _xsize, _cellYSize * _ysize });
    _outfeatures->envelope(env);

    return sPREPARED;
}
<|endoftext|>


<commit_before>#include "scene.h"
#include "camera.h"
#include <stdio.h>

#include "raytracer/rt_raytracer.h"
#include "rasterizer/ras_rasterizer.h"

Scene::Scene()
{
	this->camera = new Camera(0.86, 480, 480);
	this->raytracer = new RayTracer();
	this->rasterizer = new Rasterizer();

	this->rasterizer->setCamera(this->camera);
}

Scene::~Scene()
{
	for(int i = 0; i < this->meshes.size(); ++i) {
		delete this->meshes[i];
	}

	for (int i = 0; i < this->lights.size(); ++i) {
		delete this->lights[i];
	}

	for (int i = 0; i < this->materials.size(); ++i) {
		delete this->materials[i];
	}
	delete this->camera;
}

void Scene::addMesh(Mesh *mesh)
{
	this->raytracer->addMesh(mesh);
	this->rasterizer->addMesh(mesh);
	this->meshes.push_back(mesh);
}

void Scene::draw(unsigned char *output)
{
	int count;
	Eigen::Vector3f *positions, *normals;
	Result *results;
	ResultOffset *result_offsets;

	this->rasterizer->beginFrame();
	this->rasterizer->drawPrepass();
	this->rasterizer->drawLights(this->lights);
	this->rasterizer->drawMeshes();
	this->rasterizer->getRayTraceData(&count, &positions, &normals);
	this->raytracer->processRays(*this->camera, count, positions, normals, &results, &result_offsets, &count);
	this->rasterizer->drawRayData(results, result_offsets, count);
}
<commit_msg>Forgot a file for the last commit.<commit_after>#include "scene.h"
#include "camera.h"
#include <stdio.h>

#include "raytracer/rt_raytracer.h"
#include "rasterizer/ras_rasterizer.h"

Scene::Scene()
{
	this->camera = new Camera(0.86, 480, 480);
	this->raytracer = new RayTracer();
	this->rasterizer = new Rasterizer();

	this->rasterizer->setCamera(this->camera);
}

Scene::~Scene()
{
	for(int i = 0; i < this->meshes.size(); ++i) {
		delete this->meshes[i];
	}

	for (int i = 0; i < this->lights.size(); ++i) {
		delete this->lights[i];
	}

	for (int i = 0; i < this->materials.size(); ++i) {
		delete this->materials[i];
	}
	delete this->camera;
}

void Scene::addMesh(Mesh *mesh)
{
	this->raytracer->addMesh(mesh);
	this->rasterizer->addMesh(mesh);
	this->meshes.push_back(mesh);
}

void Scene::draw(unsigned char *output)
{
	int count, material_count;
	Eigen::Vector3f *positions, *normals;
	Result *results;
	ResultOffset *result_offsets;

	this->rasterizer->beginFrame();
	this->rasterizer->drawPrepass();
	this->rasterizer->drawLights(this->lights);
	this->rasterizer->drawMeshes();
	this->rasterizer->getRayTraceData(&count, &positions, &normals);
	this->raytracer->processRays(*this->camera, count, positions, normals, &results, &result_offsets, &count, &material_count);
	this->rasterizer->drawRayData(results, result_offsets, count, material_count);
//	unsigned char *color = new unsigned char[4 * this->camera->getWidth() * this->camera->getHeight()];
//	this->raytracer->renderScene(*this, this->camera->getWidth(), this->camera->getHeight(), color);
//	this->rasterizer->displayImageData(color);
//	delete [] color;
}
<|endoftext|>


<commit_before>/*
  Copyright (c) 2011-2012 - Tőkés Attila

  This file is part of SmtpClient for Qt.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  See the LICENSE file for more details.
*/

#include "mimecontentformatter.h"

using namespace SimpleMail;

MimeContentFormatter::MimeContentFormatter(int max_length) :
    max_length(max_length)
{

}

QByteArray MimeContentFormatter::format(const QByteArray &content, int &chars) const
{
    QByteArray out;
    out.reserve(6000);

    for (int i = 0, size = content.length(); i < size; i+=max_length) {
        out.append(content.mid(i,max_length));
        out.append(QByteArrayLiteral("\r\n"));
        chars += i;
    }

    return out;
}

QByteArray MimeContentFormatter::formatQuotedPrintable(const QByteArray &content, int &chars) const
{
    QByteArray out;

    for (int i = 0; i < content.length() ; ++i) {
        chars++;

        if (content[i] == '\n') {       // new line
            out.append(content[i]);
            chars = 0;
            continue;
        }

        if ((chars > max_length - 1)
                || ((content[i] == '=') && (chars > max_length - 3) )) {
            out.append(QByteArrayLiteral("=\r\n"));
            chars = 1;
        }

        out.append(content[i]);
    }

    return out;
}

void MimeContentFormatter::setMaxLength(int l)
{
    max_length = l;
}

int MimeContentFormatter::maxLength() const
{
    return max_length;
}
<commit_msg>Implement dot stuffing<commit_after>/*
  Copyright (c) 2011-2012 - Tőkés Attila

  This file is part of SmtpClient for Qt.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  See the LICENSE file for more details.
*/

#include "mimecontentformatter.h"

using namespace SimpleMail;

MimeContentFormatter::MimeContentFormatter(int max_length) :
    max_length(max_length)
{

}

QByteArray MimeContentFormatter::format(const QByteArray &content, int &chars) const
{
    QByteArray out;
    out.reserve(6000);

    for (int i = 0, size = content.length(); i < size; i+=max_length) {
        out.append(content.mid(i,max_length));
        out.append(QByteArrayLiteral("\r\n"));
        chars += i;
    }

    return out;
}

QByteArray MimeContentFormatter::formatQuotedPrintable(const QByteArray &content, int &chars) const
{
    QByteArray out;

    for (int i = 0; i < content.length() ; ++i) {
        chars++;

        if (content[i] == '\n') {       // new line
            out.append(content[i]);
            chars = 0;
            continue;
        }

        if ((chars > max_length - 1)
                || ((content[i] == '=') && (chars > max_length - 3) )) {
            out.append(QByteArrayLiteral("=\r\n"));
            chars = 1;
        }

        // dot stuffing: https://www.rfc-editor.org/rfc/rfc5321#section-4.5.2
        if (chars == 1 && content[i] == '.') {
            out.append('.');
            chars++;
        }

        out.append(content[i]);
    }

    return out;
}

void MimeContentFormatter::setMaxLength(int l)
{
    max_length = l;
}

int MimeContentFormatter::maxLength() const
{
    return max_length;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"

#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-closure-holder.h"

#include "vtrc-common/vtrc-thread-pool.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"

#include "protocol/hello.pb.h" /// hello protocol

#include "boost/lexical_cast.hpp"

#include "google/protobuf/descriptor.h" /// for descriptor( )->full_name( )

using namespace vtrc;

namespace {

class  hello_service_impl: public howto::hello_service {

    common::connection_iface *cl_;

    void send_hello(::google::protobuf::RpcController*  controller,
                    const ::howto::request_message*     request,
                    ::howto::response_message*          response,
                    ::google::protobuf::Closure*        done) /*override*/
    {
        common::closure_holder ch( done ); /// instead of done->Run( );
        std::ostringstream oss;

        oss << "Hello " << request->name( )
            << " from hello_service_impl::send_hello!\n"
            << "Your transport name is '"
            << cl_->name( ) << "'.\nHave a nice day.";

        response->set_hello( oss.str( ) );
        /// done->Run( ); /// ch will call it
    }

public:

    hello_service_impl( common::connection_iface *cl )
        :cl_(cl)
    { }

    static std::string const &service_name(  )
    {
        return howto::hello_service::descriptor( )->full_name( );
    }

};

class hello_application: public server::application {

    typedef common::rpc_service_wrapper     wrapper_type;
    typedef vtrc::shared_ptr<wrapper_type>  wrapper_sptr;

public:

    hello_application( common::thread_pool &tp )
        :server::application(tp.get_io_service( ))
    { }

    wrapper_sptr get_service_by_name( common::connection_iface* connection,
                                      const std::string &service_name )
    {
        if( service_name == hello_service_impl::service_name( ) ) {

             hello_service_impl *new_impl = new hello_service_impl(connection);

             return vtrc::make_shared<wrapper_type>( new_impl );

        }
        return wrapper_sptr( );
    }

};

}

int main( int argc, const char **argv )
{

    const char *address = "127.0.0.1";
    unsigned short port = 56560;

    if( argc > 2 ) {
        address = argv[1];
        port = boost::lexical_cast<unsigned short>( argv[2] );
    } else if( argc > 1 ) {
        port = boost::lexical_cast<unsigned short>( argv[1] );
    }

    common::thread_pool tp;
    hello_application app( tp );

    try {

        vtrc::shared_ptr<server::listener>
                tcp( server::listeners::tcp::create( app, address, port ) );

        tcp->start( );

        tp.attach( );

    } catch( const std::exception &ex ) {
        std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
    }

    tp.join_all( );

    /// make valgrind happy.
    google::protobuf::ShutdownProtobufLibrary( );

    return 0;
}

<commit_msg>hello<commit_after>#include <iostream>

#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"

#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-closure-holder.h"

#include "vtrc-common/vtrc-thread-pool.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"

#include "protocol/hello.pb.h" /// hello protocol

#include "boost/lexical_cast.hpp"

#include "google/protobuf/descriptor.h" /// for descriptor( )->full_name( )

using namespace vtrc;

namespace {

class  hello_service_impl: public howto::hello_service {

    common::connection_iface *cl_;

    void send_hello(::google::protobuf::RpcController*  controller,
                    const ::howto::request_message*     request,
                    ::howto::response_message*          response,
                    ::google::protobuf::Closure*        done) /*override*/
    {
        common::closure_holder ch( done ); /// instead of done->Run( );
        std::ostringstream oss;

        oss << "Hello " << request->name( )
            << " from hello_service_impl::send_hello!\n"
            << "Your transport name is '"
            << cl_->name( ) << "'.\nHave a nice day.";

        response->set_hello( oss.str( ) );
        /// done->Run( ); /// ch will call it
    }

public:

    hello_service_impl( common::connection_iface *cl )
        :cl_(cl)
    { }

    static std::string const &service_name(  )
    {
        return howto::hello_service::descriptor( )->full_name( );
    }

};

class hello_application: public server::application {

    typedef common::rpc_service_wrapper     wrapper_type;
    typedef vtrc::shared_ptr<wrapper_type>  wrapper_sptr;

public:

    hello_application( common::thread_pool &tp )
        :server::application(tp.get_io_service( ))
    { }

    wrapper_sptr get_service_by_name( common::connection_iface* connection,
                                      const std::string &service_name )
    {
        if( service_name == hello_service_impl::service_name( ) ) {

             hello_service_impl *new_impl = new hello_service_impl(connection);

             return vtrc::make_shared<wrapper_type>( new_impl );

        }
        return wrapper_sptr( );
    }

};

} // namespace

int main( int argc, const char **argv )
{

    const char *address = "127.0.0.1";
    unsigned short port = 56560;

    if( argc > 2 ) {
        address = argv[1];
        port = boost::lexical_cast<unsigned short>( argv[2] );
    } else if( argc > 1 ) {
        port = boost::lexical_cast<unsigned short>( argv[1] );
    }

    common::thread_pool tp;
    hello_application app( tp );

    try {

        vtrc::shared_ptr<server::listener>
                tcp( server::listeners::tcp::create( app, address, port ) );

        tcp->start( );

        tp.attach( );

    } catch( const std::exception &ex ) {
        std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
    }

    tp.join_all( );

    /// make valgrind happy.
    google::protobuf::ShutdownProtobufLibrary( );

    return 0;
}

<|endoftext|>