<commit_before>/**
 * \file Chebyshev1Filter.cpp
 */

#include <boost/math/special_functions/asinh.hpp>

#include "Chebyshev1Filter.h"
#include "IIRFilter.h"

namespace
{
  template<typename DataType>
  void create_chebyshev1_analog_coefficients(int order, DataType ripple, std::vector<std::complex<DataType> >& z, std::vector<std::complex<DataType> >& p, DataType& k)
  {
    z.clear(); // no zeros for this filter type
    p.clear();
    if(order == 0)
    {
      k = std::pow(10, (-ripple / 20));
      return;
    }

    DataType eps = std::sqrt(std::pow(10, (0.1 * ripple)) - 1.0);
    DataType mu = 1.0 / order * boost::math::asinh(1 / eps);

    for(int i = -order+1; i < order; i += 2)
    {
      DataType theta = boost::math::constants::pi<DataType>() * i / (2*order);
      p.push_back(-std::sinh(std::complex<DataType>(mu, theta)));
    }

    std::complex<DataType> f = 1;

    for(int i = 0; i < p.size(); ++i)
    {
      f *= -p[i];
    }
    k = f.real();
    if(order % 2 == 0)
    {
      k = k / std::sqrt((1 + eps * eps));
    }
  }

  template<typename DataType>
  void create_default_chebyshev1_coeffs(int order, DataType ripple, DataType Wn, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
  {
    std::vector<std::complex<DataType> > z;
    std::vector<std::complex<DataType> > p;
    DataType k;

    int fs = 2;
    create_chebyshev1_analog_coefficients(order, ripple, z, p, k);
    DataType warped = 2 * fs * std::tan(boost::math::constants::pi<DataType>() *  Wn / fs);
    zpk_lp2lp(warped, z, p, k);
    zpk_bilinear(fs, z, p, k);

    boost::math::tools::polynomial<DataType> b;
    boost::math::tools::polynomial<DataType> a;

    zpk2ba(fs, z, p, k, b, a);

    for(int i = 0; i < order + 1; ++i)
    {
      coefficients_in[i] = b[i];
    }
    for(int i = 0; i < order; ++i)
    {
      coefficients_out[i] = -a[i];
    }
  }

  template<typename DataType>
  void create_bp_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
  {
    std::vector<std::complex<DataType> > z;
    std::vector<std::complex<DataType> > p;
    DataType k;

    int fs = 2;
    create_chebyshev1_analog_coefficients(order/2, ripple, z, p, k);
    wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);
    wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);

    zpk_lp2bp(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);
    zpk_bilinear(fs, z, p, k);

    boost::math::tools::polynomial<DataType> b;
    boost::math::tools::polynomial<DataType> a;

    zpk2ba(fs, z, p, k, b, a);

    for(int i = 0; i < order + 1; ++i)
    {
      coefficients_in[i] = b[i];
    }
    for(int i = 0; i < order; ++i)
    {
      coefficients_out[i] = -a[i];
    }
  }

  template<typename DataType>
  void create_bs_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
  {
    std::vector<std::complex<DataType> > z;
    std::vector<std::complex<DataType> > p;
    DataType k;

    int fs = 2;
    create_chebyshev1_analog_coefficients(order/2, ripple, z, p, k);
    wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);
    wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);

    zpk_lp2bs(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);
    zpk_bilinear(fs, z, p, k);

    boost::math::tools::polynomial<DataType> b;
    boost::math::tools::polynomial<DataType> a;

    zpk2ba(fs, z, p, k, b, a);

    for(int i = 0; i < order + 1; ++i)
    {
      coefficients_in[i] = b[i];
    }
    for(int i = 0; i < order; ++i)
    {
      coefficients_out[i] = -a[i];
    }
  }
}

namespace ATK
{
  template <typename DataType>
  Chebyshev1LowPassCoefficients<DataType>::Chebyshev1LowPassCoefficients()
  :Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)
  {
  }

  template <typename DataType>
  void Chebyshev1LowPassCoefficients<DataType>::set_ripple(DataType ripple)
  {
    this->ripple = ripple;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1LowPassCoefficients<DataType>::DataType Chebyshev1LowPassCoefficients<DataType>::get_ripple() const
  {
    return ripple;
  }

  template <typename DataType>
  void Chebyshev1LowPassCoefficients<DataType>::set_cut_frequency(DataType cut_frequency)
  {
    this->cut_frequency = cut_frequency;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1LowPassCoefficients<DataType>::DataType Chebyshev1LowPassCoefficients<DataType>::get_cut_frequency() const
  {
    return cut_frequency;
  }

  template <typename DataType>
  void Chebyshev1LowPassCoefficients<DataType>::set_order(int order)
  {
    in_order = out_order = order;
    setup();
  }

  template <typename DataType>
  void Chebyshev1LowPassCoefficients<DataType>::setup()
  {
    Parent::setup();
    coefficients_in.assign(in_order+1, 0);
    coefficients_out.assign(out_order, 0);

    create_default_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);
  }

  template <typename DataType>
  Chebyshev1HighPassCoefficients<DataType>::Chebyshev1HighPassCoefficients()
  :Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)
  {
  }

  template <typename DataType>
  void Chebyshev1HighPassCoefficients<DataType>::set_cut_frequency(DataType cut_frequency)
  {
    this->cut_frequency = cut_frequency;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1HighPassCoefficients<DataType>::DataType Chebyshev1HighPassCoefficients<DataType>::get_cut_frequency() const
  {
    return cut_frequency;
  }

  template <typename DataType>
  void Chebyshev1HighPassCoefficients<DataType>::set_ripple(DataType ripple)
  {
    this->ripple = ripple;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1HighPassCoefficients<DataType>::DataType Chebyshev1HighPassCoefficients<DataType>::get_ripple() const
  {
    return ripple;
  }

  template <typename DataType>
  void Chebyshev1HighPassCoefficients<DataType>::set_order(int order)
  {
    in_order = out_order = order;
    setup();
  }

  template <typename DataType>
  void Chebyshev1HighPassCoefficients<DataType>::setup()
  {
    Parent::setup();
    coefficients_in.assign(in_order+1, 0);
    coefficients_out.assign(out_order, 0);

    create_default_chebyshev1_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);
    for(int i = in_order - 1; i >= 0; i -= 2)
    {
      coefficients_in[i] = - coefficients_in[i];
      coefficients_out[i] = - coefficients_out[i];
    }
  }

  template <typename DataType>
  Chebyshev1BandPassCoefficients<DataType>::Chebyshev1BandPassCoefficients()
  :Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)
  {
  }

  template <typename DataType>
  void Chebyshev1BandPassCoefficients<DataType>::set_cut_frequencies(std::pair<DataType, DataType> cut_frequencies)
  {
    this->cut_frequencies = cut_frequencies;
    setup();
  }

  template <typename DataType>
  void Chebyshev1BandPassCoefficients<DataType>::set_cut_frequencies(DataType f0, DataType f1)
  {
    this->cut_frequencies = std::make_pair(f0, f1);
    setup();
  }

  template <typename DataType>
  std::pair<typename Chebyshev1BandPassCoefficients<DataType>::DataType, typename Chebyshev1BandPassCoefficients<DataType>::DataType> Chebyshev1BandPassCoefficients<DataType>::get_cut_frequencies() const
  {
    return cut_frequencies;
  }

  template <typename DataType>
  void Chebyshev1BandPassCoefficients<DataType>::set_ripple(DataType ripple)
  {
    this->ripple = ripple;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1BandPassCoefficients<DataType>::DataType Chebyshev1BandPassCoefficients<DataType>::get_ripple() const
  {
    return ripple;
  }

  template <typename DataType>
  void Chebyshev1BandPassCoefficients<DataType>::set_order(int order)
  {
    in_order = out_order = 2 * order;
    setup();
  }

  template <typename DataType>
  void Chebyshev1BandPassCoefficients<DataType>::setup()
  {
    Parent::setup();
    coefficients_in.assign(in_order+1, 0);
    coefficients_out.assign(out_order, 0);

    create_bp_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);
  }

  template <typename DataType>
  Chebyshev1BandStopCoefficients<DataType>::Chebyshev1BandStopCoefficients()
  :Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)
  {
  }

  template <typename DataType>
  void Chebyshev1BandStopCoefficients<DataType>::set_cut_frequencies(std::pair<DataType, DataType> cut_frequencies)
  {
    this->cut_frequencies = cut_frequencies;
    setup();
  }

  template <typename DataType>
  void Chebyshev1BandStopCoefficients<DataType>::set_cut_frequencies(DataType f0, DataType f1)
  {
    this->cut_frequencies = std::make_pair(f0, f1);
    setup();
  }

  template <typename DataType>
  std::pair<typename Chebyshev1BandStopCoefficients<DataType>::DataType, typename Chebyshev1BandStopCoefficients<DataType>::DataType> Chebyshev1BandStopCoefficients<DataType>::get_cut_frequencies() const
  {
    return cut_frequencies;
  }

  template <typename DataType>
  void Chebyshev1BandStopCoefficients<DataType>::set_ripple(DataType ripple)
  {
    this->ripple = ripple;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1BandStopCoefficients<DataType>::DataType Chebyshev1BandStopCoefficients<DataType>::get_ripple() const
  {
    return ripple;
  }

  template <typename DataType>
  void Chebyshev1BandStopCoefficients<DataType>::set_order(int order)
  {
    in_order = out_order = 2 * order;
    setup();
  }

  template <typename DataType>
  void Chebyshev1BandStopCoefficients<DataType>::setup()
  {
    Parent::setup();
    coefficients_in.assign(in_order+1, 0);
    coefficients_out.assign(out_order, 0);

    create_bs_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);
  }

  template class Chebyshev1LowPassCoefficients<float>;
  template class Chebyshev1LowPassCoefficients<double>;
  template class Chebyshev1HighPassCoefficients<float>;
  template class Chebyshev1HighPassCoefficients<double>;
  template class Chebyshev1BandPassCoefficients<float>;
  template class Chebyshev1BandPassCoefficients<double>;
  template class Chebyshev1BandStopCoefficients<float>;
  template class Chebyshev1BandStopCoefficients<double>;

  template class IIRFilter<Chebyshev1LowPassCoefficients<float> >;
  template class IIRFilter<Chebyshev1LowPassCoefficients<double> >;
  template class IIRFilter<Chebyshev1HighPassCoefficients<float> >;
  template class IIRFilter<Chebyshev1HighPassCoefficients<double> >;
  template class IIRFilter<Chebyshev1BandPassCoefficients<float> >;
  template class IIRFilter<Chebyshev1BandPassCoefficients<double> >;
  template class IIRFilter<Chebyshev1BandStopCoefficients<float> >;
  template class IIRFilter<Chebyshev1BandStopCoefficients<double> >;

}
<commit_msg>Fixing Chebyshev type 1 setup<commit_after>/**
 * \file Chebyshev1Filter.cpp
 */

#include <boost/math/special_functions/asinh.hpp>

#include "Chebyshev1Filter.h"
#include "IIRFilter.h"

namespace
{
  template<typename DataType>
  void create_chebyshev1_analog_coefficients(int order, DataType ripple, std::vector<std::complex<DataType> >& z, std::vector<std::complex<DataType> >& p, DataType& k)
  {
    z.clear(); // no zeros for this filter type
    p.clear();
    if(ripple == 0)
    {
      return;
    }
    if(order == 0)
    {
      k = std::pow(10, (-ripple / 20));
      return;
    }

    DataType eps = std::sqrt(std::pow(10, (0.1 * ripple)) - 1.0);
    DataType mu = 1.0 / order * boost::math::asinh(1 / eps);

    for(int i = -order+1; i < order; i += 2)
    {
      DataType theta = boost::math::constants::pi<DataType>() * i / (2*order);
      p.push_back(-std::sinh(std::complex<DataType>(mu, theta)));
    }

    std::complex<DataType> f = 1;

    for(int i = 0; i < p.size(); ++i)
    {
      f *= -p[i];
    }
    k = f.real();
    if(order % 2 == 0)
    {
      k = k / std::sqrt((1 + eps * eps));
    }
  }

  template<typename DataType>
  void create_default_chebyshev1_coeffs(int order, DataType ripple, DataType Wn, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
  {
    std::vector<std::complex<DataType> > z;
    std::vector<std::complex<DataType> > p;
    DataType k;

    int fs = 2;
    create_chebyshev1_analog_coefficients(order, ripple, z, p, k);
    DataType warped = 2 * fs * std::tan(boost::math::constants::pi<DataType>() *  Wn / fs);
    zpk_lp2lp(warped, z, p, k);
    zpk_bilinear(fs, z, p, k);

    boost::math::tools::polynomial<DataType> b;
    boost::math::tools::polynomial<DataType> a;

    zpk2ba(fs, z, p, k, b, a);

    for(int i = 0; i < order + 1; ++i)
    {
      coefficients_in[i] = b[i];
    }
    for(int i = 0; i < order; ++i)
    {
      coefficients_out[i] = -a[i];
    }
  }

  template<typename DataType>
  void create_bp_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
  {
    std::vector<std::complex<DataType> > z;
    std::vector<std::complex<DataType> > p;
    DataType k;

    int fs = 2;
    create_chebyshev1_analog_coefficients(order/2, ripple, z, p, k);
    wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);
    wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);

    zpk_lp2bp(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);
    zpk_bilinear(fs, z, p, k);

    boost::math::tools::polynomial<DataType> b;
    boost::math::tools::polynomial<DataType> a;

    zpk2ba(fs, z, p, k, b, a);

    for(int i = 0; i < order + 1; ++i)
    {
      coefficients_in[i] = b[i];
    }
    for(int i = 0; i < order; ++i)
    {
      coefficients_out[i] = -a[i];
    }
  }

  template<typename DataType>
  void create_bs_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)
  {
    std::vector<std::complex<DataType> > z;
    std::vector<std::complex<DataType> > p;
    DataType k;

    int fs = 2;
    create_chebyshev1_analog_coefficients(order/2, ripple, z, p, k);
    wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);
    wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);

    zpk_lp2bs(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);
    zpk_bilinear(fs, z, p, k);

    boost::math::tools::polynomial<DataType> b;
    boost::math::tools::polynomial<DataType> a;

    zpk2ba(fs, z, p, k, b, a);

    for(int i = 0; i < order + 1; ++i)
    {
      coefficients_in[i] = b[i];
    }
    for(int i = 0; i < order; ++i)
    {
      coefficients_out[i] = -a[i];
    }
  }
}

namespace ATK
{
  template <typename DataType>
  Chebyshev1LowPassCoefficients<DataType>::Chebyshev1LowPassCoefficients()
  :Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)
  {
  }

  template <typename DataType>
  void Chebyshev1LowPassCoefficients<DataType>::set_ripple(DataType ripple)
  {
    this->ripple = ripple;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1LowPassCoefficients<DataType>::DataType Chebyshev1LowPassCoefficients<DataType>::get_ripple() const
  {
    return ripple;
  }

  template <typename DataType>
  void Chebyshev1LowPassCoefficients<DataType>::set_cut_frequency(DataType cut_frequency)
  {
    this->cut_frequency = cut_frequency;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1LowPassCoefficients<DataType>::DataType Chebyshev1LowPassCoefficients<DataType>::get_cut_frequency() const
  {
    return cut_frequency;
  }

  template <typename DataType>
  void Chebyshev1LowPassCoefficients<DataType>::set_order(int order)
  {
    in_order = out_order = order;
    setup();
  }

  template <typename DataType>
  void Chebyshev1LowPassCoefficients<DataType>::setup()
  {
    Parent::setup();
    coefficients_in.assign(in_order+1, 0);
    coefficients_out.assign(out_order, 0);

    create_default_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);
  }

  template <typename DataType>
  Chebyshev1HighPassCoefficients<DataType>::Chebyshev1HighPassCoefficients()
  :Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)
  {
  }

  template <typename DataType>
  void Chebyshev1HighPassCoefficients<DataType>::set_cut_frequency(DataType cut_frequency)
  {
    this->cut_frequency = cut_frequency;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1HighPassCoefficients<DataType>::DataType Chebyshev1HighPassCoefficients<DataType>::get_cut_frequency() const
  {
    return cut_frequency;
  }

  template <typename DataType>
  void Chebyshev1HighPassCoefficients<DataType>::set_ripple(DataType ripple)
  {
    this->ripple = ripple;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1HighPassCoefficients<DataType>::DataType Chebyshev1HighPassCoefficients<DataType>::get_ripple() const
  {
    return ripple;
  }

  template <typename DataType>
  void Chebyshev1HighPassCoefficients<DataType>::set_order(int order)
  {
    in_order = out_order = order;
    setup();
  }

  template <typename DataType>
  void Chebyshev1HighPassCoefficients<DataType>::setup()
  {
    Parent::setup();
    coefficients_in.assign(in_order+1, 0);
    coefficients_out.assign(out_order, 0);

    create_default_chebyshev1_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);
    for(int i = in_order - 1; i >= 0; i -= 2)
    {
      coefficients_in[i] = - coefficients_in[i];
      coefficients_out[i] = - coefficients_out[i];
    }
  }

  template <typename DataType>
  Chebyshev1BandPassCoefficients<DataType>::Chebyshev1BandPassCoefficients()
  :Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)
  {
  }

  template <typename DataType>
  void Chebyshev1BandPassCoefficients<DataType>::set_cut_frequencies(std::pair<DataType, DataType> cut_frequencies)
  {
    this->cut_frequencies = cut_frequencies;
    setup();
  }

  template <typename DataType>
  void Chebyshev1BandPassCoefficients<DataType>::set_cut_frequencies(DataType f0, DataType f1)
  {
    this->cut_frequencies = std::make_pair(f0, f1);
    setup();
  }

  template <typename DataType>
  std::pair<typename Chebyshev1BandPassCoefficients<DataType>::DataType, typename Chebyshev1BandPassCoefficients<DataType>::DataType> Chebyshev1BandPassCoefficients<DataType>::get_cut_frequencies() const
  {
    return cut_frequencies;
  }

  template <typename DataType>
  void Chebyshev1BandPassCoefficients<DataType>::set_ripple(DataType ripple)
  {
    this->ripple = ripple;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1BandPassCoefficients<DataType>::DataType Chebyshev1BandPassCoefficients<DataType>::get_ripple() const
  {
    return ripple;
  }

  template <typename DataType>
  void Chebyshev1BandPassCoefficients<DataType>::set_order(int order)
  {
    in_order = out_order = 2 * order;
    setup();
  }

  template <typename DataType>
  void Chebyshev1BandPassCoefficients<DataType>::setup()
  {
    Parent::setup();
    coefficients_in.assign(in_order+1, 0);
    coefficients_out.assign(out_order, 0);

    create_bp_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);
  }

  template <typename DataType>
  Chebyshev1BandStopCoefficients<DataType>::Chebyshev1BandStopCoefficients()
  :Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)
  {
  }

  template <typename DataType>
  void Chebyshev1BandStopCoefficients<DataType>::set_cut_frequencies(std::pair<DataType, DataType> cut_frequencies)
  {
    this->cut_frequencies = cut_frequencies;
    setup();
  }

  template <typename DataType>
  void Chebyshev1BandStopCoefficients<DataType>::set_cut_frequencies(DataType f0, DataType f1)
  {
    this->cut_frequencies = std::make_pair(f0, f1);
    setup();
  }

  template <typename DataType>
  std::pair<typename Chebyshev1BandStopCoefficients<DataType>::DataType, typename Chebyshev1BandStopCoefficients<DataType>::DataType> Chebyshev1BandStopCoefficients<DataType>::get_cut_frequencies() const
  {
    return cut_frequencies;
  }

  template <typename DataType>
  void Chebyshev1BandStopCoefficients<DataType>::set_ripple(DataType ripple)
  {
    this->ripple = ripple;
    setup();
  }

  template <typename DataType>
  typename Chebyshev1BandStopCoefficients<DataType>::DataType Chebyshev1BandStopCoefficients<DataType>::get_ripple() const
  {
    return ripple;
  }

  template <typename DataType>
  void Chebyshev1BandStopCoefficients<DataType>::set_order(int order)
  {
    in_order = out_order = 2 * order;
    setup();
  }

  template <typename DataType>
  void Chebyshev1BandStopCoefficients<DataType>::setup()
  {
    Parent::setup();
    coefficients_in.assign(in_order+1, 0);
    coefficients_out.assign(out_order, 0);

    create_bs_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);
  }

  template class Chebyshev1LowPassCoefficients<float>;
  template class Chebyshev1LowPassCoefficients<double>;
  template class Chebyshev1HighPassCoefficients<float>;
  template class Chebyshev1HighPassCoefficients<double>;
  template class Chebyshev1BandPassCoefficients<float>;
  template class Chebyshev1BandPassCoefficients<double>;
  template class Chebyshev1BandStopCoefficients<float>;
  template class Chebyshev1BandStopCoefficients<double>;

  template class IIRFilter<Chebyshev1LowPassCoefficients<float> >;
  template class IIRFilter<Chebyshev1LowPassCoefficients<double> >;
  template class IIRFilter<Chebyshev1HighPassCoefficients<float> >;
  template class IIRFilter<Chebyshev1HighPassCoefficients<double> >;
  template class IIRFilter<Chebyshev1BandPassCoefficients<float> >;
  template class IIRFilter<Chebyshev1BandPassCoefficients<double> >;
  template class IIRFilter<Chebyshev1BandStopCoefficients<float> >;
  template class IIRFilter<Chebyshev1BandStopCoefficients<double> >;

}
<|endoftext|>


<commit_before>#pragma once

#include <archive.h>

#include "../stream/stream.hh"
#include "../stream/buffer.hh"
#include "../non-copyable.hh"
#include "entry.hh"

namespace mimosa
{
  namespace archive
  {
    class Reader : public stream::Stream
    {
    public:
      MIMOSA_DEF_PTR(Reader);

      inline Reader() : archive_(archive_read_new()) {}
      inline ~Reader() { archive_read_free(archive_); }

      inline operator struct ::archive *() const { return archive_; }

      int open(stream::Stream::Ptr input);

      int nextHeader(Entry &e);

      int64_t read(char *data, uint64_t nbytes) override;
      int64_t write(const char *data, uint64_t nbytes) override;

      //////////////
      /// Filter ///
      //////////////

      inline int filterBzip2() { return archive_read_support_filter_bzip2(archive_); }
      inline int filterCompress() { return archive_read_support_filter_compress(archive_); }
      inline int filterGzip() { return archive_read_support_filter_gzip(archive_); }
      inline int filterLrzip() { return archive_read_support_filter_lrzip(archive_); }
      inline int filterLzip() { return archive_read_support_filter_lzip(archive_); }
      inline int filterLzma() { return archive_read_support_filter_lzma(archive_); }
      inline int filterLzop() { return archive_read_support_filter_lzop(archive_); }
      inline int filterNone() { return archive_read_support_filter_none(archive_); }
      inline int filterProgram(const std::string & cmd) {
        return archive_read_support_filter_program(archive_, cmd.c_str());
      }
      inline int filterXz() { return archive_read_support_filter_xz(archive_); }

      //////////////
      /// Format ///
      //////////////

      inline int format7zip() { return archive_read_support_format_7zip(archive_); }
      inline int formatAr() { return archive_read_support_format_ar(archive_); }
      inline int formatCpio() { return archive_read_support_format_cpio(archive_); }
      inline int formatGnutar() { return archive_read_support_format_gnutar(archive_); }
      inline int formatIso9660() { return archive_read_support_format_iso9660(archive_); }
      inline int formatMtree() { return archive_read_support_format_mtree(archive_); }
      inline int formatTar() { return archive_read_support_format_tar(archive_); }
      inline int formatXar() { return archive_read_support_format_xar(archive_); }
      inline int formatZip() { return archive_read_support_format_zip(archive_); }

    private:
      static int openCb(struct archive *, void *_client_data);
      static ssize_t readCb(struct archive *,
                            void *_client_data, const void **_buffer);
      static int closeCb(struct archive *, void *_client_data);

      void close() { archive_read_close(archive_); }

      struct ::archive *archive_;
      stream::Stream::Ptr stream_;
      stream::Buffer::Ptr buffer_;
    };
  }
}
<commit_msg>Fix warning<commit_after>#pragma once

#include <archive.h>

#include "../stream/stream.hh"
#include "../stream/buffer.hh"
#include "../non-copyable.hh"
#include "entry.hh"

namespace mimosa
{
  namespace archive
  {
    class Reader : public stream::Stream
    {
    public:
      MIMOSA_DEF_PTR(Reader);

      inline Reader() : archive_(archive_read_new()) {}
      inline ~Reader() { archive_read_free(archive_); }

      inline operator struct ::archive *() const { return archive_; }

      int open(stream::Stream::Ptr input);

      int nextHeader(Entry &e);

      int64_t read(char *data, uint64_t nbytes) override;
      int64_t write(const char *data, uint64_t nbytes) override;

      //////////////
      /// Filter ///
      //////////////

      inline int filterBzip2() { return archive_read_support_filter_bzip2(archive_); }
      inline int filterCompress() { return archive_read_support_filter_compress(archive_); }
      inline int filterGzip() { return archive_read_support_filter_gzip(archive_); }
      inline int filterLrzip() { return archive_read_support_filter_lrzip(archive_); }
      inline int filterLzip() { return archive_read_support_filter_lzip(archive_); }
      inline int filterLzma() { return archive_read_support_filter_lzma(archive_); }
      inline int filterLzop() { return archive_read_support_filter_lzop(archive_); }
      inline int filterNone() { return archive_read_support_filter_none(archive_); }
      inline int filterProgram(const std::string & cmd) {
        return archive_read_support_filter_program(archive_, cmd.c_str());
      }
      inline int filterXz() { return archive_read_support_filter_xz(archive_); }

      //////////////
      /// Format ///
      //////////////

      inline int format7zip() { return archive_read_support_format_7zip(archive_); }
      inline int formatAr() { return archive_read_support_format_ar(archive_); }
      inline int formatCpio() { return archive_read_support_format_cpio(archive_); }
      inline int formatGnutar() { return archive_read_support_format_gnutar(archive_); }
      inline int formatIso9660() { return archive_read_support_format_iso9660(archive_); }
      inline int formatMtree() { return archive_read_support_format_mtree(archive_); }
      inline int formatTar() { return archive_read_support_format_tar(archive_); }
      inline int formatXar() { return archive_read_support_format_xar(archive_); }
      inline int formatZip() { return archive_read_support_format_zip(archive_); }

    private:
      static int openCb(struct archive *, void *_client_data);
      static ssize_t readCb(struct archive *,
                            void *_client_data, const void **_buffer);
      static int closeCb(struct archive *, void *_client_data);

      void close() override { archive_read_close(archive_); }

      struct ::archive *archive_;
      stream::Stream::Ptr stream_;
      stream::Buffer::Ptr buffer_;
    };
  }
}
<|endoftext|>


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

#include "Archive.h"

#include "lib/7z/7zCrc.h"

// gcc only offers a full c++11 implementation with >= v5.1
// codecvt for unicode conversions is not always available
// thus use iconv in such cases
#include <features.h>
#if __GNUC_PREREQ(5,1)
#include <codecvt>
#else
#include <iconv.h>
#endif

#include <string>
#include <locale>
#include <stdexcept>
#include <memory>

namespace lib33u
{
namespace util
{
namespace sz
{
struct DefaultAlloc : public ISzAlloc
{
    DefaultAlloc()
    {
        Alloc = SzAlloc;
        Free = SzFree;
    }
};

struct TempAlloc : public ISzAlloc
{
    TempAlloc()
    {
        Alloc = SzAllocTemp;
        Free = SzFreeTemp;
    }
};

int SzCrcGenerateTableOnce()
{
    CrcGenerateTable();
    return 0;
}

Archive::Data::Data( const std::string& fn )
{
    // static int x = SzCrcGenerateTableOnce();

    auto wres = InFile_Open( &archive_stream_.file, fn.c_str() );
    if( wres )
    {
        throw std::runtime_error( "Unable to open archive file" );
    }

    FileInStream_CreateVTable( &archive_stream_ );

    LookToRead_CreateVTable( &look_stream_, False );
    look_stream_.realStream = &archive_stream_.s;
    LookToRead_Init( &look_stream_ );

    SzArEx_Init( &db_ );

    DefaultAlloc default_alloc_;
    TempAlloc temp_alloc_;

    auto sres = SzArEx_Open(&db_, &look_stream_.s,
                            &default_alloc_, &temp_alloc_);
    if( sres )
    {
        throw std::runtime_error( "Failed to open archive" );
    }

    struct ArchiveBuffer
    {
        UInt32 block_index_ = 0xFFFFFFFF;
        Byte* out_buffer_ = nullptr;
        size_t out_buffer_size_ = 0;

        ~ArchiveBuffer()
        {
            DefaultAlloc default_alloc;
            IAlloc_Free( &default_alloc, out_buffer_ );
        }
    };

#ifdef __linux__
    typedef std::u16string utf16string;
#else
    typedef std::wstring utf16string;
#endif

    utf16string utf16name;
    auto buffer = std::make_shared<ArchiveBuffer>();

    for( unsigned i = 0; i < db_.NumFiles; ++i )
    {
        size_t len = SzArEx_GetFileNameUtf16( &db_, i, nullptr );

        utf16name.resize(len);

        SzArEx_GetFileNameUtf16( &db_, i, (UInt16*)utf16name.data() );

#if __GNUC_PREREQ(5,1)

        std::wstring_convert<std::codecvt_utf8_utf16<utf16string::value_type>,
                             utf16string::value_type> conversion;
        std::string utf8name = conversion.to_bytes( utf16name );

#else

        iconv_t ico = iconv_open("UTF8", "UTF16");

        size_t out_size = 1024;

        char buf [out_size];

        char* tmp = buf;
        const char16_t* tmp16 = utf16name.data();

        size_t in_size = len*2;

        size_t ret = iconv(ico, (char**)&tmp16, &in_size, &tmp, &out_size);

        std::string utf8name(buf);

        iconv_close(ico);

#endif

        while( utf8name.back() == '\0' )
            utf8name.pop_back();

        size_t offset = 0;
        size_t outSizeProcessed = 0;

        sres = SzArEx_Extract(&db_, &look_stream_.s, i,
                              &buffer->block_index_,
                              &buffer->out_buffer_,
                              &buffer->out_buffer_size_,
                              &offset,
                              &outSizeProcessed,
                              &default_alloc_,
                              &temp_alloc_ );

        // file_index_.try_emplace( utf8name, std::shared_ptr<uint8_t>( buffer, buffer->out_buffer_ + offset ), outSizeProcessed );
        file_index_.emplace(utf8name,
                            Entry(std::shared_ptr<uint8_t>(buffer, buffer->out_buffer_ + offset),
                                  outSizeProcessed ));
    }
}

Archive::Entry Archive::Data::read (const std::string& fn) const
{
    auto it = file_index_.find(fn);
    if (it == file_index_.end())
    {
        throw std::runtime_error("Entry not found");
    }
    return it->second;
}

Archive::Archive (const std::string& fn)
    : data { std::unique_ptr<Data>(new Data(fn)) }
 {
 }

Archive Archive::open (const std::string& fn)
{
    return Archive( fn );
}

Archive::Entry Archive::read (const std::string& fn) const
{
    return data->read( fn );
}
} /* namespace sz */
} /* namespace util */
} /* namespace lib33u */
<commit_msg>Fix segfault in firmware-update for 33u cameras<commit_after>/*
 * Copyright 2017 The Imaging Source Europe GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Archive.h"

#include "lib/7z/7zCrc.h"

// gcc only offers a full c++11 implementation with >= v5.1
// codecvt for unicode conversions is not always available
// thus use iconv in such cases
#include <features.h>
#if __GNUC_PREREQ(5,1)
#include <codecvt>
#else
#include <iconv.h>
#endif

#include <string>
#include <locale>
#include <stdexcept>
#include <memory>

namespace lib33u
{
namespace util
{
namespace sz
{
struct DefaultAlloc : public ISzAlloc
{
    DefaultAlloc()
    {
        Alloc = SzAlloc;
        Free = SzFree;
    }
};

struct TempAlloc : public ISzAlloc
{
    TempAlloc()
    {
        Alloc = SzAllocTemp;
        Free = SzFreeTemp;
    }
};

int SzCrcGenerateTableOnce()
{
    CrcGenerateTable();
    return 0;
}

Archive::Data::Data( const std::string& fn )
{
    SzCrcGenerateTableOnce();

    auto wres = InFile_Open( &archive_stream_.file, fn.c_str() );
    if( wres )
    {
        throw std::runtime_error( "Unable to open archive file" );
    }

    FileInStream_CreateVTable( &archive_stream_ );

    LookToRead_CreateVTable( &look_stream_, False );
    look_stream_.realStream = &archive_stream_.s;
    LookToRead_Init( &look_stream_ );

    SzArEx_Init( &db_ );

    DefaultAlloc default_alloc_;
    TempAlloc temp_alloc_;

    auto sres = SzArEx_Open(&db_, &look_stream_.s,
                            &default_alloc_, &temp_alloc_);
    if( sres )
    {
        throw std::runtime_error( "Failed to open archive" );
    }

    struct ArchiveBuffer
    {
        UInt32 block_index_ = 0xFFFFFFFF;
        Byte* out_buffer_ = nullptr;
        size_t out_buffer_size_ = 0;

        ~ArchiveBuffer()
        {
            DefaultAlloc default_alloc;
            IAlloc_Free( &default_alloc, out_buffer_ );
        }
    };

#ifdef __linux__
    typedef std::u16string utf16string;
#else
    typedef std::wstring utf16string;
#endif

    utf16string utf16name;
    auto buffer = std::make_shared<ArchiveBuffer>();

    for( unsigned i = 0; i < db_.NumFiles; ++i )
    {
        size_t len = SzArEx_GetFileNameUtf16( &db_, i, nullptr );

        utf16name.resize(len);

        SzArEx_GetFileNameUtf16( &db_, i, (UInt16*)utf16name.data() );

#if __GNUC_PREREQ(5,1)

        std::wstring_convert<std::codecvt_utf8_utf16<utf16string::value_type>,
                             utf16string::value_type> conversion;
        std::string utf8name = conversion.to_bytes( utf16name );

#else

        iconv_t ico = iconv_open("UTF8", "UTF16");

        size_t out_size = 1024;

        char buf [out_size];

        char* tmp = buf;
        const char16_t* tmp16 = utf16name.data();

        size_t in_size = len*2;

        size_t ret = iconv(ico, (char**)&tmp16, &in_size, &tmp, &out_size);

        std::string utf8name(buf);

        iconv_close(ico);

#endif

        while( utf8name.back() == '\0' )
            utf8name.pop_back();

        size_t offset = 0;
        size_t outSizeProcessed = 0;

        sres = SzArEx_Extract(&db_, &look_stream_.s, i,
                              &buffer->block_index_,
                              &buffer->out_buffer_,
                              &buffer->out_buffer_size_,
                              &offset,
                              &outSizeProcessed,
                              &default_alloc_,
                              &temp_alloc_ );

        // file_index_.try_emplace( utf8name, std::shared_ptr<uint8_t>( buffer, buffer->out_buffer_ + offset ), outSizeProcessed );
        file_index_.emplace(utf8name,
                            Entry(std::shared_ptr<uint8_t>(buffer, buffer->out_buffer_ + offset),
                                  outSizeProcessed ));
    }
}

Archive::Entry Archive::Data::read (const std::string& fn) const
{
    auto it = file_index_.find(fn);
    if (it == file_index_.end())
    {
        throw std::runtime_error("Entry not found");
    }
    return it->second;
}

Archive::Archive (const std::string& fn)
    : data { std::unique_ptr<Data>(new Data(fn)) }
 {
 }

Archive Archive::open (const std::string& fn)
{
    return Archive( fn );
}

Archive::Entry Archive::read (const std::string& fn) const
{
    return data->read( fn );
}
} /* namespace sz */
} /* namespace util */
} /* namespace lib33u */
<|endoftext|>


<commit_before>#include "boid.h"

/**
 * @brief Create a new boid
 *
 * Creates a new QQmlComponent using the main QQmlApplicationEngine of the program and
 * the Boid.qml file.
 * After the component is created and ready, the QObject is created and parented to the
 * canvas object.
 * Lastly we set the position randomly, but staying within the boundaries.
 */
Boid::Boid() {
    component = new QQmlComponent(getEngine(), QUrl(QStringLiteral("qrc:/Boid.qml")));
    if(component->status() == component->Ready) {
        object = component->create(getEngine()->rootContext());
        object->setProperty("parent", QVariant::fromValue(getCanvas()));
        QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
    }
    else
        qDebug() << component->errorString();

    setY(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasHeight() - 100));
    setX(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasWidth() - 100));

    lastVel = Vector2();
}

Boid::~Boid() {
    delete component;
    delete object;
}

/**
 * @brief Boid logic
 */
void Boid::update(){
    Vector2 v1 = Vector2();
    Vector2 v2 = Vector2();
    Vector2 v3 = Vector2();
    Vector2 v4 = Vector2();
    Vector2 center = Vector2();

    // Rule1: move to local center of mass ( center becomes average of surrounding boids)
    for(int i = 0; i < 3; i++){
        center = center + neighbours[i].position2;
    }
    center /= 3;

    v1 = center - position;

    // Rule2: Avoidance : if distance to next boid smaller than threshold T boid changes course.
    center = Vector2();
    for(int i = 0; i < 3; i++){
        if ((neighbours[i].position2 - position).getSqrMagnitude() < (getSize() + 10.0) * (getSize() + 10.0)){
            center = center - (neighbours[i].position2 - position);
        }
    }
    v2 = center;

    // Rule3: Match velocity to surrounding Boids
    for(int i = 0; i < 3; i++){
        v3 = v3 + neighbours[i].velocity2;
    }
    v3 = v3/3;

    // Rule 4: Follow mouse position
    Vector2 mp = getMousePosition();
    if(!(mp == Vector2(0, 0))) {
        if((mp - position).getSqrMagnitude() > 7500)
            v4 = mp - position;
    }

    // Rule 5: Stray away from the boundaries
    Vector2 v5 = Vector2();

    if(position.getX() < 80)
        v5.setX(1);
    else if(position.getX() >= getCanvasWidth() - 80)
        v5.setX(-1);

    if(position.getY() <  80)
        v5.setY(1);
    else if(position.getY() >= getCanvasHeight() - 80){
        v5.setY(-1);
    }

    //Replace position with mouse position and look through the force-parameter with the mouse
    double power = 0.0;
    double power2 = 0.0;
    if(position.getX() < 80)
        power = 100 - position.getX();
    else if(position.getX() >= getCanvasWidth() - 80)
        power = 100 + position.getX() - getCanvasWidth() ;
    else if(position.getY() < 80)
        power2 = 100 - position.getY();
    else if(position.getY() >= getCanvasHeight() - 80)
        power2 = 100 + position.getY() - getCanvasHeight();

    double force = 10*exp((power+ power2) *0.05);

    //qDebug << force;

    velocity = Vector2::lerp(lastVel,
                             velocity + v1.normalize()*getFlockingFactor() + v2.normalize()*getAvoidanceFactor() +
                             v3.normalize()*getVelocityMatchFactor() + v4.normalize()*getTargetFactor() + v5 * force,
                             0.016f);

    lastVel = velocity;
}
<commit_msg>Tweak threshold and function.<commit_after>#include "boid.h"

/**
 * @brief Create a new boid
 *
 * Creates a new QQmlComponent using the main QQmlApplicationEngine of the program and
 * the Boid.qml file.
 * After the component is created and ready, the QObject is created and parented to the
 * canvas object.
 * Lastly we set the position randomly, but staying within the boundaries.
 */
Boid::Boid() {
    component = new QQmlComponent(getEngine(), QUrl(QStringLiteral("qrc:/Boid.qml")));
    if(component->status() == component->Ready) {
        object = component->create(getEngine()->rootContext());
        object->setProperty("parent", QVariant::fromValue(getCanvas()));
        QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
    }
    else
        qDebug() << component->errorString();

    setY(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasHeight() - 100));
    setX(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasWidth() - 100));

    lastVel = Vector2();
}

Boid::~Boid() {
    delete component;
    delete object;
}

/**
 * @brief Boid logic
 */
void Boid::update(){
    Vector2 v1 = Vector2();
    Vector2 v2 = Vector2();
    Vector2 v3 = Vector2();
    Vector2 v4 = Vector2();
    Vector2 center = Vector2();

    // Rule1: move to local center of mass ( center becomes average of surrounding boids)
    for(int i = 0; i < 3; i++){
        center = center + neighbours[i].position2;
    }
    center /= 3;

    v1 = center - position;

    // Rule2: Avoidance : if distance to next boid smaller than threshold T boid changes course.
    center = Vector2();
    for(int i = 0; i < 3; i++){
        if ((neighbours[i].position2 - position).getSqrMagnitude() < (getSize() + 10.0) * (getSize() + 10.0)){
            center = center - (neighbours[i].position2 - position);
        }
    }
    v2 = center;

    // Rule3: Match velocity to surrounding Boids
    for(int i = 0; i < 3; i++){
        v3 = v3 + neighbours[i].velocity2;
    }
    v3 = v3/3;

    // Rule 4: Follow mouse position
    Vector2 mp = getMousePosition();
    if(!(mp == Vector2(0, 0))) {
        if((mp - position).getSqrMagnitude() > 7500)
            v4 = mp - position;
    }

    // Rule 5: Stray away from the boundaries
    Vector2 v5 = Vector2();

    if(position.getX() < 80)
        v5.setX(1);
    else if(position.getX() >= getCanvasWidth() - 80)
        v5.setX(-1);

    if(position.getY() <  80)
        v5.setY(1);
    else if(position.getY() >= getCanvasHeight() - 80){
        v5.setY(-1);
    }

    //Replace position with mouse position and look through the force-parameter with the mouse
    double power = 0.0;
    double power2 = 0.0;
    if(position.getX() < 150)
        power = 150 - position.getX();
    else if(position.getX() >= getCanvasWidth() - 150)
        power = 150 + position.getX() - getCanvasWidth() ;
    else if(position.getY() < 150)
        power2 = 150 - position.getY();
    else if(position.getY() >= getCanvasHeight() - 150)
        power2 = 150 + position.getY() - getCanvasHeight();

    double force = 5.0 * ((power + power2));

    //qDebug << force;

    velocity = Vector2::lerp(lastVel,
                             velocity + v1.normalize()*getFlockingFactor() + v2.normalize()*getAvoidanceFactor() +
                             v3.normalize()*getVelocityMatchFactor() + v4.normalize()*getTargetFactor() + v5 * force,
                             0.016f);

    lastVel = velocity;
}
<|endoftext|>


<commit_before>#include "aquila/source/generator/SineGenerator.h"
#include <SFML/System.hpp>
#include <SFML/Audio.hpp>
#include <algorithm>
#include <iostream>

void convertSourceToBuffer(const Aquila::SignalSource& source, sf::SoundBuffer& buffer)
{
    sf::Int16* samples = new sf::Int16[source.getSamplesCount()];
    std::copy(source.begin(), source.end(), samples);
    buffer.LoadFromSamples(samples,
                           source.getSamplesCount(),
                           1,
                           static_cast<unsigned int>(source.getSampleFrequency()));
    delete [] samples;
}

int main(int argc, char** argv)
{
    const Aquila::FrequencyType SAMPLE_FREQUENCY = 44100;
    Aquila::SineGenerator generator(SAMPLE_FREQUENCY);
    generator.setFrequency(440).setAmplitude(8192).generate(2 * SAMPLE_FREQUENCY);

    sf::SoundBuffer buffer;
    convertSourceToBuffer(generator, buffer);

    sf::Sound sound;
    sound.SetBuffer(buffer);
    sound.Play();
    while (sound.GetStatus() == sf::Sound::Playing)
    {
        sf::Sleep(0.1f);
    }

    return 0;
}
<commit_msg>In the sfml_generator example, one can now choose signal type and frequency.<commit_after>#include "aquila/source/generator/SineGenerator.h"
#include "aquila/source/generator/SquareGenerator.h"
#include "aquila/source/generator/PinkNoiseGenerator.h"
#include "aquila/source/generator/WhiteNoiseGenerator.h"
#include <SFML/System.hpp>
#include <SFML/Audio.hpp>
#include <algorithm>
#include <iostream>

void convertSourceToBuffer(const Aquila::SignalSource& source,
                           sf::SoundBuffer& buffer)
{
    sf::Int16* samples = new sf::Int16[source.getSamplesCount()];
    std::copy(source.begin(), source.end(), samples);
    buffer.LoadFromSamples(samples,
                           source.getSamplesCount(),
                           1,
                           static_cast<unsigned int>(source.getSampleFrequency()));
    delete [] samples;
}

void handleGeneratorOptions(Aquila::Generator* generator)
{
    Aquila::FrequencyType frequency, maxFrequency = generator->getSampleFrequency() / 2;
    std::cout << "\nSignal frequency in Hz: \n"
                 "Enter a number (0-" << maxFrequency << "): ";
    std::cin >> frequency;
    if (frequency < 0 || frequency > maxFrequency)
    {
        frequency = 1000;
    }
    generator->setFrequency(frequency);
}

Aquila::Generator* createGenerator(unsigned int whichGenerator,
                                   Aquila::FrequencyType sampleFrequency)
{
    Aquila::Generator* generator;
    switch (whichGenerator)
    {
    case 1:
        generator = new Aquila::SineGenerator(sampleFrequency);
        handleGeneratorOptions(generator);
        break;
    case 2:
        generator = new Aquila::SquareGenerator(sampleFrequency);
        handleGeneratorOptions(generator);
        break;
    case 3:
        generator = new Aquila::PinkNoiseGenerator(sampleFrequency);
        break;
    case 4:
        generator = new Aquila::WhiteNoiseGenerator(sampleFrequency);
        break;
    default:
        generator = new Aquila::SineGenerator(sampleFrequency);
        handleGeneratorOptions(generator);
        break;
    }
    generator->setAmplitude(8192);
    return generator;
}

int main(int argc, char** argv)
{
    std::cout << "Choose which kind of signal to play: \n"
                 "\t 1: Sine wave \n"
                 "\t 2: Square wave \n"
                 "\t 3: Pink noise \n"
                 "\t 4: White noise \n"
                 "Enter a number (1-4): ";
    unsigned int whichGenerator = 1;
    std::cin >> whichGenerator;
    const Aquila::FrequencyType SAMPLE_FREQUENCY = 44100;
    Aquila::Generator* generator = createGenerator(whichGenerator, SAMPLE_FREQUENCY);

    generator->generate(5 * SAMPLE_FREQUENCY);
    sf::SoundBuffer buffer;
    convertSourceToBuffer(*generator, buffer);
    sf::Sound sound;
    sound.SetBuffer(buffer);
    sound.Play();
    std::cout << "Playing..." << std::endl;
    while (sound.GetStatus() == sf::Sound::Playing)
    {
        std::cout << ".";
        sf::Sleep(0.1f);
    }
    std::cout << "\nFinished." << std::endl;

    delete generator;

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Multipart cleanup of T3000 - 7<commit_after><|endoftext|>


<commit_before>/**
 * @file Vector.hpp
 *
 * Vector class.
 *
 * @author James Goppert <james.goppert@gmail.com>
 */

#pragma once
#include <Matrix.hpp>

namespace matrix
{

template <typename Type, size_t M, size_t N>
class Matrix;

template<typename Type, size_t M>
class Vector : public Matrix<Type, M, 1>
{
public:
    virtual ~Vector() {};

    Vector() : Matrix<Type, M, 1>()
    {
    }

    Vector(const Vector<Type, M> & other) :
        Matrix<Type, M, 1>(other)
    {
    }

    Vector(const Matrix<Type, M, 1> & other) :
        Matrix<Type, M, 1>(other)
    {
    }

    inline Type operator()(size_t i) const
    {
        const Matrix<Type, M, 1> &v = *this;
        return v(i, 0);
    }

    inline Type &operator()(size_t i)
    {
        Matrix<Type, M, 1> &v = *this;
        return v(i, 0);
    }

    Type dot(const Vector & b) const {
        const Vector &a(*this);
        Type r = 0;
        for (int i = 0; i<M; i++) {
            r += a(i)*b(i);
        }
        return r;
    }

    Type norm() const {
        const Vector &a(*this);
        return Type(sqrt(a.dot(a)));
    }

    inline void normalize() {
        (*this) /= norm();
    }

    /**
     * Vector Operations
     */

    Vector<Type, M> operator+(const Vector<Type, M> &other) const
    {
        Vector<Type, M> res;
        const Vector<Type, M> &self = *this;

        for (size_t i = 0; i < M; i++) {
            res(i) = self(i) + other(i);
        }

        return res;
    }

    Vector<Type, M> operator-(const Vector<Type, M> &other) const
    {
        Vector<Type, M> res;
        const Vector<Type, M> &self = *this;

        for (size_t i = 0; i < M; i++) {
            res(i) = self(i) - other(i);
        }

        return res;
    }

    void operator+=(const Vector<Type, M> &other)
    {
        Vector<Type, M> &self = *this;
        self = self + other;
    }

    void operator-=(const Vector<Type, M> &other)
    {
        Vector<Type, M> &self = *this;
        self = self - other;
    }

    /**
     * Scalar Operations
     */

    Vector<Type, M> operator*(Type scalar) const
    {
        Vector<Type, M> res;
        const Vector<Type, M> &self = *this;

        for (size_t i = 0; i < M; i++) {
            res(i) = self(i) * scalar;
        }

        return res;
    }

    Vector<Type, M> operator/(Type scalar) const
    {
        return (*this)*(1.0/scalar);
    }

    Vector<Type, M> operator+(Type scalar) const
    {
        Vector<Type, M> res;
        const Vector<Type, M> &self = *this;

        for (size_t i = 0; i < M; i++) {
            res(i) = self(i) + scalar;
        }

        return res;
    }

    void operator*=(Type scalar)
    {
        Vector<Type, M> &self = *this;

        for (size_t i = 0; i < M; i++) {
            self(i) = self(i) * scalar;
        }
    }

    void operator/=(Type scalar)
    {
        Vector<Type, M> &self = *this;
        self = self * (1.0f / scalar);
    }

};

}; // namespace matrix

/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<commit_msg>Travis fix.<commit_after>/**
 * @file Vector.hpp
 *
 * Vector class.
 *
 * @author James Goppert <james.goppert@gmail.com>
 */

#pragma once
#include <Matrix.hpp>

namespace matrix
{

template <typename Type, size_t M, size_t N>
class Matrix;

template<typename Type, size_t M>
class Vector : public Matrix<Type, M, 1>
{
public:
    virtual ~Vector() {};

    Vector() : Matrix<Type, M, 1>()
    {
    }

    Vector(const Vector<Type, M> & other) :
        Matrix<Type, M, 1>(other)
    {
    }

    Vector(const Matrix<Type, M, 1> & other) :
        Matrix<Type, M, 1>(other)
    {
    }

    inline Type operator()(size_t i) const
    {
        const Matrix<Type, M, 1> &v = *this;
        return v(i, 0);
    }

    inline Type &operator()(size_t i)
    {
        Matrix<Type, M, 1> &v = *this;
        return v(i, 0);
    }

    Type dot(const Vector & b) const {
        const Vector &a(*this);
        Type r = 0;
        for (int i = 0; i<M; i++) {
            r += a(i)*b(i);
        }
        return r;
    }

    Type norm() const {
        const Vector &a(*this);
        return Type(sqrt(a.dot(a)));
    }

    inline void normalize() {
        (*this) /= norm();
    }

    /**
     * Vector Operations
     */

    Vector<Type, M> operator+(const Vector<Type, M> &other) const
    {
        Vector<Type, M> res;
        const Vector<Type, M> &self = *this;

        for (size_t i = 0; i < M; i++) {
            res(i) = self(i) + other(i);
        }

        return res;
    }

    Vector<Type, M> operator-(const Vector<Type, M> &other) const
    {
        Vector<Type, M> res;
        const Vector<Type, M> &self = *this;

        for (size_t i = 0; i < M; i++) {
            res(i) = self(i) - other(i);
        }

        return res;
    }

    void operator+=(const Vector<Type, M> &other)
    {
        Vector<Type, M> &self = *this;
        self = self + other;
    }

    void operator-=(const Vector<Type, M> &other)
    {
        Vector<Type, M> &self = *this;
        self = self - other;
    }

    /**
     * Scalar Operations
     */

    Vector<Type, M> operator*(Type scalar) const
    {
        Vector<Type, M> res;
        const Vector<Type, M> &self = *this;

        for (size_t i = 0; i < M; i++) {
            res(i) = self(i) * scalar;
        }

        return res;
    }

    Vector<Type, M> operator/(Type scalar) const
    {
        return (*this)*(Type(1.0)/scalar);
    }

    Vector<Type, M> operator+(Type scalar) const
    {
        Vector<Type, M> res;
        const Vector<Type, M> &self = *this;

        for (size_t i = 0; i < M; i++) {
            res(i) = self(i) + scalar;
        }

        return res;
    }

    void operator*=(Type scalar)
    {
        Vector<Type, M> &self = *this;

        for (size_t i = 0; i < M; i++) {
            self(i) = self(i) * scalar;
        }
    }

    void operator/=(Type scalar)
    {
        Vector<Type, M> &self = *this;
        self = self * (1.0f / scalar);
    }

};

}; // namespace matrix

/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: taskmisc.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:58:57 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#define _TASKBAR_CXX

#ifndef _TOOLS_LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif

#include <taskbar.hxx>

// =======================================================================

TaskButtonBar::TaskButtonBar( Window* pParent, WinBits nWinStyle ) :
    ToolBox( pParent, nWinStyle | WB_3DLOOK )
{
    SetAlign( WINDOWALIGN_BOTTOM );
    SetButtonType( BUTTON_SYMBOLTEXT );
}

// -----------------------------------------------------------------------

TaskButtonBar::~TaskButtonBar()
{
}

// -----------------------------------------------------------------------

void TaskButtonBar::RequestHelp( const HelpEvent& rHEvt )
{
    ToolBox::RequestHelp( rHEvt );
}

// =======================================================================

WindowArrange::WindowArrange()
{
    mpWinList = new List;
}

// -----------------------------------------------------------------------

WindowArrange::~WindowArrange()
{
    delete mpWinList;
}

// -----------------------------------------------------------------------

static USHORT ImplCeilSqareRoot( USHORT nVal )
{
    USHORT i;

    // Ueberlauf verhindern
    if ( nVal > 0xFE * 0xFE )
        return 0xFE;

    for ( i=0; i*i < nVal; i++ )
        {}

    return i;
}

// -----------------------------------------------------------------------

static void ImplPosSizeWindow( Window* pWindow,
                               long nX, long nY, long nWidth, long nHeight )
{
    if ( nWidth < 32 )
        nWidth = 32;
    if ( nHeight < 24 )
        nHeight = 24;
    pWindow->SetPosSizePixel( nX, nY, nWidth, nHeight );
}

// -----------------------------------------------------------------------

void WindowArrange::ImplTile( const Rectangle& rRect )
{
    USHORT nCount = (USHORT)mpWinList->Count();
    if ( nCount < 3 )
    {
        ImplVert( rRect );
        return;
    }

    USHORT      i;
    USHORT      j;
    USHORT      nCols;
    USHORT      nRows;
    USHORT      nActRows;
    USHORT      nOffset;
    long        nOverWidth;
    long        nOverHeight;
    Window*     pWindow;
    long        nX = rRect.Left();
    long        nY = rRect.Top();
    long        nWidth = rRect.GetWidth();
    long        nHeight = rRect.GetHeight();
    long        nRectY = nY;
    long        nRectWidth = nWidth;
    long        nRectHeight = nHeight;
    long        nTempWidth;
    long        nTempHeight;

    nCols   = ImplCeilSqareRoot( nCount );
    nOffset = (nCols*nCols) - nCount;
    if ( nOffset >= nCols )
    {
        nRows    = nCols -1;
        nOffset -= nCols;
    }
    else
        nRows = nCols;

    nWidth /= nCols;
    if ( nWidth < 1 )
        nWidth = 1;
    nOverWidth = nRectWidth-(nWidth*nCols);

    pWindow = (Window*)mpWinList->First();
    for ( i = 0; i < nCols; i++ )
    {
        if ( i < nOffset )
            nActRows = nRows - 1;
        else
            nActRows = nRows;

        nTempWidth = nWidth;
        if ( nOverWidth > 0 )
        {
            nTempWidth++;
            nOverWidth--;
        }

        nHeight = nRectHeight / nActRows;
        if ( nHeight < 1 )
            nHeight = 1;
        nOverHeight = nRectHeight-(nHeight*nActRows);
        for ( j = 0; j < nActRows; j++ )
        {
            // Ueberhang verteilen
            nTempHeight = nHeight;
            if ( nOverHeight > 0 )
            {
                nTempHeight++;
                nOverHeight--;
            }
            ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nTempHeight );
            nY += nTempHeight;

            pWindow = (Window*)mpWinList->Next();
            if ( !pWindow )
                break;
        }

        nX += nWidth;
        nY = nRectY;

        if ( !pWindow )
            break;
    }
}

// -----------------------------------------------------------------------

void WindowArrange::ImplHorz( const Rectangle& rRect )
{
    long        nCount = (long)mpWinList->Count();
    long        nX = rRect.Left();
    long        nY = rRect.Top();
    long        nWidth = rRect.GetWidth();
    long        nHeight = rRect.GetHeight();
    long        nRectHeight = nHeight;
    long        nOver;
    long        nTempHeight;
    Window*     pWindow;

    nHeight /= nCount;
    if ( nHeight < 1 )
        nHeight = 1;
    nOver = nRectHeight - (nCount*nHeight);
    pWindow = (Window*)mpWinList->First();
    while ( pWindow )
    {
        nTempHeight = nHeight;
        if ( nOver > 0 )
        {
            nTempHeight++;
            nOver--;
        }
        ImplPosSizeWindow( pWindow, nX, nY, nWidth, nTempHeight );
        nY += nTempHeight;

        pWindow = (Window*)mpWinList->Next();
    }
}

// -----------------------------------------------------------------------

void WindowArrange::ImplVert( const Rectangle& rRect )
{
    long        nCount = (long)mpWinList->Count();
    long        nX = rRect.Left();
    long        nY = rRect.Top();
    long        nWidth = rRect.GetWidth();
    long        nHeight = rRect.GetHeight();
    long        nRectWidth = nWidth;
    long        nOver;
    long        nTempWidth;
    Window*     pWindow;

    nWidth /= nCount;
    if ( nWidth < 1 )
        nWidth = 1;
    nOver = nRectWidth - (nCount*nWidth);
    pWindow = (Window*)mpWinList->First();
    while ( pWindow )
    {
        nTempWidth = nWidth;
        if ( nOver > 0 )
        {
            nTempWidth++;
            nOver--;
        }
        ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nHeight );
        nX += nTempWidth;

        pWindow = (Window*)mpWinList->Next();
    }
}

// -----------------------------------------------------------------------

void WindowArrange::ImplCascade( const Rectangle& rRect )
{
    long        nX = rRect.Left();
    long        nY = rRect.Top();
    long        nWidth = rRect.GetWidth();
    long        nHeight = rRect.GetHeight();
    long        nRectWidth = nWidth;
    long        nRectHeight = nHeight;
    long        nOff;
    long        nCascadeWins;
    long        nLeftBorder;
    long        nTopBorder;
    long        nRightBorder;
    long        nBottomBorder;
    long        nStartOverWidth;
    long        nStartOverHeight;
    long        nOverWidth;
    long        nOverHeight;
    long        nTempX;
    long        nTempY;
    long        nTempWidth;
    long        nTempHeight;
    long        i;
    Window*     pWindow;
    Window*     pTempWindow;

    // Border-Fenster suchen um den Versatz zu ermitteln
    pTempWindow = (Window*)mpWinList->First();
    pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );
    while ( !nTopBorder )
    {
        Window* pBrdWin = pTempWindow->GetWindow( WINDOW_REALPARENT );
        if ( !pBrdWin || (pBrdWin->GetWindow( WINDOW_CLIENT ) != pTempWindow) )
            break;
        pTempWindow = pBrdWin;
        pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );
    }
    if ( !nTopBorder )
        nTopBorder = 22;
    nOff = nTopBorder;

    nCascadeWins = nRectHeight / 3 / nOff;
    if ( !nCascadeWins )
        nCascadeWins = 1;
    nWidth   -= nCascadeWins*nOff;
    nHeight  -= nCascadeWins*nOff;
    if ( nWidth < 1 )
        nWidth = 1;
    if ( nHeight < 1 )
        nHeight = 1;

    nStartOverWidth = nRectWidth-(nWidth+(nCascadeWins*nOff));
    nStartOverHeight = nRectHeight-(nHeight+(nCascadeWins*nOff));

    i = 0;
    pWindow = (Window*)mpWinList->First();
    while ( pWindow )
    {
        if ( !i )
        {
            nOverWidth = nStartOverWidth;
            nOverHeight = nStartOverHeight;
        }

        // Position
        nTempX = nX + (i*nOff);
        nTempY = nY + (i*nOff);

        // Ueberhang verteilen
        nTempWidth = nWidth;
        if ( nOverWidth > 0 )
        {
            nTempWidth++;
            nOverWidth--;
        }
        nTempHeight = nHeight;
        if ( nOverHeight > 0 )
        {
            nTempHeight++;
            nOverHeight--;
        }

        ImplPosSizeWindow( pWindow, nTempX, nTempY, nTempWidth, nTempHeight );

        if ( i < nCascadeWins )
            i++;
        else
            i = 0;

        pWindow = (Window*)mpWinList->Next();
    }
}

// -----------------------------------------------------------------------

void WindowArrange::Arrange( USHORT nType, const Rectangle& rRect )
{
    if ( !mpWinList->Count() )
        return;

    switch ( nType )
    {
        case WINDOWARRANGE_TILE:
            ImplTile( rRect );
            break;
        case WINDOWARRANGE_HORZ:
            ImplHorz( rRect );
            break;
        case WINDOWARRANGE_VERT:
            ImplVert( rRect );
            break;
        case WINDOWARRANGE_CASCADE:
            ImplCascade( rRect );
            break;
    }
}

<commit_msg>INTEGRATION: CWS ooo20040509 (1.1.1.1.588); FILE MERGED 2004/05/06 13:40:19 waratah 1.1.1.1.588.1: Initialise variables where they need it<commit_after>/*************************************************************************
 *
 *  $RCSfile: taskmisc.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-06-16 10:13:08 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#define _TASKBAR_CXX

#ifndef _TOOLS_LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif

#include <taskbar.hxx>

// =======================================================================

TaskButtonBar::TaskButtonBar( Window* pParent, WinBits nWinStyle ) :
    ToolBox( pParent, nWinStyle | WB_3DLOOK )
{
    SetAlign( WINDOWALIGN_BOTTOM );
    SetButtonType( BUTTON_SYMBOLTEXT );
}

// -----------------------------------------------------------------------

TaskButtonBar::~TaskButtonBar()
{
}

// -----------------------------------------------------------------------

void TaskButtonBar::RequestHelp( const HelpEvent& rHEvt )
{
    ToolBox::RequestHelp( rHEvt );
}

// =======================================================================

WindowArrange::WindowArrange()
{
    mpWinList = new List;
}

// -----------------------------------------------------------------------

WindowArrange::~WindowArrange()
{
    delete mpWinList;
}

// -----------------------------------------------------------------------

static USHORT ImplCeilSqareRoot( USHORT nVal )
{
    USHORT i;

    // Ueberlauf verhindern
    if ( nVal > 0xFE * 0xFE )
        return 0xFE;

    for ( i=0; i*i < nVal; i++ )
        {}

    return i;
}

// -----------------------------------------------------------------------

static void ImplPosSizeWindow( Window* pWindow,
                               long nX, long nY, long nWidth, long nHeight )
{
    if ( nWidth < 32 )
        nWidth = 32;
    if ( nHeight < 24 )
        nHeight = 24;
    pWindow->SetPosSizePixel( nX, nY, nWidth, nHeight );
}

// -----------------------------------------------------------------------

void WindowArrange::ImplTile( const Rectangle& rRect )
{
    USHORT nCount = (USHORT)mpWinList->Count();
    if ( nCount < 3 )
    {
        ImplVert( rRect );
        return;
    }

    USHORT      i;
    USHORT      j;
    USHORT      nCols;
    USHORT      nRows;
    USHORT      nActRows;
    USHORT      nOffset;
    long        nOverWidth;
    long        nOverHeight;
    Window*     pWindow;
    long        nX = rRect.Left();
    long        nY = rRect.Top();
    long        nWidth = rRect.GetWidth();
    long        nHeight = rRect.GetHeight();
    long        nRectY = nY;
    long        nRectWidth = nWidth;
    long        nRectHeight = nHeight;
    long        nTempWidth;
    long        nTempHeight;

    nCols   = ImplCeilSqareRoot( nCount );
    nOffset = (nCols*nCols) - nCount;
    if ( nOffset >= nCols )
    {
        nRows    = nCols -1;
        nOffset -= nCols;
    }
    else
        nRows = nCols;

    nWidth /= nCols;
    if ( nWidth < 1 )
        nWidth = 1;
    nOverWidth = nRectWidth-(nWidth*nCols);

    pWindow = (Window*)mpWinList->First();
    for ( i = 0; i < nCols; i++ )
    {
        if ( i < nOffset )
            nActRows = nRows - 1;
        else
            nActRows = nRows;

        nTempWidth = nWidth;
        if ( nOverWidth > 0 )
        {
            nTempWidth++;
            nOverWidth--;
        }

        nHeight = nRectHeight / nActRows;
        if ( nHeight < 1 )
            nHeight = 1;
        nOverHeight = nRectHeight-(nHeight*nActRows);
        for ( j = 0; j < nActRows; j++ )
        {
            // Ueberhang verteilen
            nTempHeight = nHeight;
            if ( nOverHeight > 0 )
            {
                nTempHeight++;
                nOverHeight--;
            }
            ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nTempHeight );
            nY += nTempHeight;

            pWindow = (Window*)mpWinList->Next();
            if ( !pWindow )
                break;
        }

        nX += nWidth;
        nY = nRectY;

        if ( !pWindow )
            break;
    }
}

// -----------------------------------------------------------------------

void WindowArrange::ImplHorz( const Rectangle& rRect )
{
    long        nCount = (long)mpWinList->Count();
    long        nX = rRect.Left();
    long        nY = rRect.Top();
    long        nWidth = rRect.GetWidth();
    long        nHeight = rRect.GetHeight();
    long        nRectHeight = nHeight;
    long        nOver;
    long        nTempHeight;
    Window*     pWindow;

    nHeight /= nCount;
    if ( nHeight < 1 )
        nHeight = 1;
    nOver = nRectHeight - (nCount*nHeight);
    pWindow = (Window*)mpWinList->First();
    while ( pWindow )
    {
        nTempHeight = nHeight;
        if ( nOver > 0 )
        {
            nTempHeight++;
            nOver--;
        }
        ImplPosSizeWindow( pWindow, nX, nY, nWidth, nTempHeight );
        nY += nTempHeight;

        pWindow = (Window*)mpWinList->Next();
    }
}

// -----------------------------------------------------------------------

void WindowArrange::ImplVert( const Rectangle& rRect )
{
    long        nCount = (long)mpWinList->Count();
    long        nX = rRect.Left();
    long        nY = rRect.Top();
    long        nWidth = rRect.GetWidth();
    long        nHeight = rRect.GetHeight();
    long        nRectWidth = nWidth;
    long        nOver;
    long        nTempWidth;
    Window*     pWindow;

    nWidth /= nCount;
    if ( nWidth < 1 )
        nWidth = 1;
    nOver = nRectWidth - (nCount*nWidth);
    pWindow = (Window*)mpWinList->First();
    while ( pWindow )
    {
        nTempWidth = nWidth;
        if ( nOver > 0 )
        {
            nTempWidth++;
            nOver--;
        }
        ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nHeight );
        nX += nTempWidth;

        pWindow = (Window*)mpWinList->Next();
    }
}

// -----------------------------------------------------------------------

void WindowArrange::ImplCascade( const Rectangle& rRect )
{
    long        nX = rRect.Left();
    long        nY = rRect.Top();
    long        nWidth = rRect.GetWidth();
    long        nHeight = rRect.GetHeight();
    long        nRectWidth = nWidth;
    long        nRectHeight = nHeight;
    long        nOff;
    long        nCascadeWins;
    long        nLeftBorder;
    long        nTopBorder;
    long        nRightBorder;
    long        nBottomBorder;
    long        nStartOverWidth;
    long        nStartOverHeight;
    long        nOverWidth = 0;
    long        nOverHeight = 0;
    long        nTempX;
    long        nTempY;
    long        nTempWidth;
    long        nTempHeight;
    long        i;
    Window*     pWindow;
    Window*     pTempWindow;

    // Border-Fenster suchen um den Versatz zu ermitteln
    pTempWindow = (Window*)mpWinList->First();
    pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );
    while ( !nTopBorder )
    {
        Window* pBrdWin = pTempWindow->GetWindow( WINDOW_REALPARENT );
        if ( !pBrdWin || (pBrdWin->GetWindow( WINDOW_CLIENT ) != pTempWindow) )
            break;
        pTempWindow = pBrdWin;
        pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );
    }
    if ( !nTopBorder )
        nTopBorder = 22;
    nOff = nTopBorder;

    nCascadeWins = nRectHeight / 3 / nOff;
    if ( !nCascadeWins )
        nCascadeWins = 1;
    nWidth   -= nCascadeWins*nOff;
    nHeight  -= nCascadeWins*nOff;
    if ( nWidth < 1 )
        nWidth = 1;
    if ( nHeight < 1 )
        nHeight = 1;

    nStartOverWidth = nRectWidth-(nWidth+(nCascadeWins*nOff));
    nStartOverHeight = nRectHeight-(nHeight+(nCascadeWins*nOff));

    i = 0;
    pWindow = (Window*)mpWinList->First();
    while ( pWindow )
    {
        if ( !i )
        {
            nOverWidth = nStartOverWidth;
            nOverHeight = nStartOverHeight;
        }

        // Position
        nTempX = nX + (i*nOff);
        nTempY = nY + (i*nOff);

        // Ueberhang verteilen
        nTempWidth = nWidth;
        if ( nOverWidth > 0 )
        {
            nTempWidth++;
            nOverWidth--;
        }
        nTempHeight = nHeight;
        if ( nOverHeight > 0 )
        {
            nTempHeight++;
            nOverHeight--;
        }

        ImplPosSizeWindow( pWindow, nTempX, nTempY, nTempWidth, nTempHeight );

        if ( i < nCascadeWins )
            i++;
        else
            i = 0;

        pWindow = (Window*)mpWinList->Next();
    }
}

// -----------------------------------------------------------------------

void WindowArrange::Arrange( USHORT nType, const Rectangle& rRect )
{
    if ( !mpWinList->Count() )
        return;

    switch ( nType )
    {
        case WINDOWARRANGE_TILE:
            ImplTile( rRect );
            break;
        case WINDOWARRANGE_HORZ:
            ImplHorz( rRect );
            break;
        case WINDOWARRANGE_VERT:
            ImplVert( rRect );
            break;
        case WINDOWARRANGE_CASCADE:
            ImplCascade( rRect );
            break;
    }
}

<|endoftext|>


<commit_before>/*
 * This file is part of ALVAR, A Library for Virtual and Augmented Reality.
 *
 * Copyright 2007-2012 VTT Technical Research Centre of Finland
 *
 * Contact: VTT Augmented Reality Team <alvar.info@vtt.fi>
 *          <http://www.vtt.fi/multimedia/alvar.html>
 *
 * ALVAR 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 ALVAR; if not, see
 * <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>.
 */

#include "CaptureFactory_private.h"

#include <stdlib.h>

namespace alvar {

void CaptureFactoryPrivate::setupPluginPaths()
{
    // application path and default plugin path
    const int bufferSize = 4096;
    char applicationBuffer[bufferSize];
    int count = readlink("/proc/self/exe", applicationBuffer, bufferSize);
    if (count != 0 && count < bufferSize) {
        std::string applicationPath(applicationBuffer, count);
        applicationPath = std::string(applicationPath, 0, applicationPath.find_last_of("/"));
        mPluginPaths.push_back(applicationPath);
        mPluginPaths.push_back(applicationPath + "/alvarplugins");
    }

    // ALVAR library path
    parseEnvironmentVariable(std::string("ALVAR_LIBRARY_PATH"));

    // ALVAR plugin path
    parseEnvironmentVariable(std::string("ALVAR_PLUGIN_PATH"));
}

void CaptureFactoryPrivate::parseEnvironmentVariable(const std::string &variable)
{
    // acquire environment variable
    char *buffer;
    std::string path("");
    buffer = getenv(variable.data());
    if (buffer) {
        path = std::string(buffer);
    }

    // tokenize paths
    char delimitor = ':';
    if (!path.empty()) {
        std::string::size_type start = 0;
        std::string::size_type end = 0;
        while ((end = path.find_first_of(delimitor, start)) != std::string::npos) {
            std::string tmp(path, start, end - start);
            if (!tmp.empty()) {
                mPluginPaths.push_back(tmp);
            }
            start = end + 1;
        }
        if (start != path.size()) {
            std::string tmp(path, start, std::string::npos);
            if (!tmp.empty()) {
                mPluginPaths.push_back(tmp);
            }
        }
    }
}

std::string CaptureFactoryPrivate::pluginPrefix()
{
    return std::string("lib");
}

std::string CaptureFactoryPrivate::pluginExtension()
{
    return std::string("so");
}

} // namespace alvar
<commit_msg>Add missing unistd include<commit_after>/*
 * This file is part of ALVAR, A Library for Virtual and Augmented Reality.
 *
 * Copyright 2007-2012 VTT Technical Research Centre of Finland
 *
 * Contact: VTT Augmented Reality Team <alvar.info@vtt.fi>
 *          <http://www.vtt.fi/multimedia/alvar.html>
 *
 * ALVAR 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 ALVAR; if not, see
 * <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>.
 */

#include "CaptureFactory_private.h"

#include <stdlib.h>
#include <unistd.h>

namespace alvar {

void CaptureFactoryPrivate::setupPluginPaths()
{
    // application path and default plugin path
    const int bufferSize = 4096;
    char applicationBuffer[bufferSize];
    int count = readlink("/proc/self/exe", applicationBuffer, bufferSize);
    if (count != 0 && count < bufferSize) {
        std::string applicationPath(applicationBuffer, count);
        applicationPath = std::string(applicationPath, 0, applicationPath.find_last_of("/"));
        mPluginPaths.push_back(applicationPath);
        mPluginPaths.push_back(applicationPath + "/alvarplugins");
    }

    // ALVAR library path
    parseEnvironmentVariable(std::string("ALVAR_LIBRARY_PATH"));

    // ALVAR plugin path
    parseEnvironmentVariable(std::string("ALVAR_PLUGIN_PATH"));
}

void CaptureFactoryPrivate::parseEnvironmentVariable(const std::string &variable)
{
    // acquire environment variable
    char *buffer;
    std::string path("");
    buffer = getenv(variable.data());
    if (buffer) {
        path = std::string(buffer);
    }

    // tokenize paths
    char delimitor = ':';
    if (!path.empty()) {
        std::string::size_type start = 0;
        std::string::size_type end = 0;
        while ((end = path.find_first_of(delimitor, start)) != std::string::npos) {
            std::string tmp(path, start, end - start);
            if (!tmp.empty()) {
                mPluginPaths.push_back(tmp);
            }
            start = end + 1;
        }
        if (start != path.size()) {
            std::string tmp(path, start, std::string::npos);
            if (!tmp.empty()) {
                mPluginPaths.push_back(tmp);
            }
        }
    }
}

std::string CaptureFactoryPrivate::pluginPrefix()
{
    return std::string("lib");
}

std::string CaptureFactoryPrivate::pluginExtension()
{
    return std::string("so");
}

} // namespace alvar
<|endoftext|>


<commit_before>#include "ConfigController.h"

#include "GameController.h"

#include <QAction>
#include <QMenu>

extern "C" {
#include "platform/commandline.h"
}

using namespace QGBA;

ConfigOption::ConfigOption(QObject* parent)
	: QObject(parent)
{
}

void ConfigOption::connect(std::function<void(const QVariant&)> slot) {
	m_slot = slot;
}

QAction* ConfigOption::addValue(const QString& text, const QVariant& value, QMenu* parent) {
	QAction* action = new QAction(text, parent);
	action->setCheckable(true);
	QObject::connect(action, &QAction::triggered, [this, value]() {
		emit valueChanged(value);
	});
	parent->addAction(action);
	m_actions.append(qMakePair(action, value));
	return action;
}

QAction* ConfigOption::addValue(const QString& text, const char* value, QMenu* parent) {
	return addValue(text, QString(value), parent);
}

QAction* ConfigOption::addBoolean(const QString& text, QMenu* parent) {
	QAction* action = new QAction(text, parent);
	action->setCheckable(true);
	QObject::connect(action, &QAction::triggered, [this, action]() {
		emit valueChanged(action->isChecked());
	});
	parent->addAction(action);
	m_actions.append(qMakePair(action, true));
	return action;
}

void ConfigOption::setValue(bool value) {
	setValue(QVariant(value));
}

void ConfigOption::setValue(int value) {
	setValue(QVariant(value));
}

void ConfigOption::setValue(unsigned value) {
	setValue(QVariant(value));
}

void ConfigOption::setValue(const char* value) {
	setValue(QVariant(QString(value)));
}

void ConfigOption::setValue(const QVariant& value) {
	QPair<QAction*, QVariant> action;
	foreach(action, m_actions) {
		bool signalsEnabled = action.first->blockSignals(true);
		action.first->setChecked(value == action.second);
		action.first->blockSignals(signalsEnabled);
	}
	m_slot(value);
}

ConfigController::ConfigController(QObject* parent)
	: QObject(parent)
	, m_opts()
{
	GBAConfigInit(&m_config, PORT);

	m_opts.audioSync = GameController::AUDIO_SYNC;
	m_opts.videoSync = GameController::VIDEO_SYNC;
	m_opts.fpsTarget = 60;
	m_opts.audioBuffers = 768;
	GBAConfigLoadDefaults(&m_config, &m_opts);
	GBAConfigLoad(&m_config);
	GBAConfigMap(&m_config, &m_opts);
}

ConfigController::~ConfigController() {
	write();

	GBAConfigDeinit(&m_config);
	GBAConfigFreeOpts(&m_opts);
}

bool ConfigController::parseArguments(GBAArguments* args, int argc, char* argv[]) {
	return ::parseArguments(args, &m_config, argc, argv, 0);
}

ConfigOption* ConfigController::addOption(const char* key) {
	QString optionName(key);

	if (m_optionSet.contains(optionName)) {
		return m_optionSet[optionName];
	}
	ConfigOption* newOption = new ConfigOption(this);
	m_optionSet[optionName] = newOption;
	connect(newOption, &ConfigOption::valueChanged, [this, key](const QVariant& value) {
		setOption(key, value);
	});
	return newOption;
}

void ConfigController::updateOption(const char* key) {
	if (!key) {
		return;
	}

	QString optionName(key);

	if (!m_optionSet.contains(optionName)) {
		return;
	}
	m_optionSet[optionName]->setValue(GBAConfigGetValue(&m_config, key));
}

void ConfigController::setOption(const char* key, bool value) {
	setOption(key, (int) value);
	ConfigOption* option = m_optionSet[QString(key)];
	if (option) {
		option->setValue(value);
	}
}

void ConfigController::setOption(const char* key, int value) {
	GBAConfigSetIntValue(&m_config, key, value);
	ConfigOption* option = m_optionSet[QString(key)];
	if (option) {
		option->setValue(value);
	}
}

void ConfigController::setOption(const char* key, unsigned value) {
	GBAConfigSetUIntValue(&m_config, key, value);
	ConfigOption* option = m_optionSet[QString(key)];
	if (option) {
		option->setValue(value);
	}
}

void ConfigController::setOption(const char* key, const char* value) {
	GBAConfigSetValue(&m_config, key, value);
	ConfigOption* option = m_optionSet[QString(key)];
	if (option) {
		option->setValue(value);
	}
}

void ConfigController::setOption(const char* key, const QVariant& value) {
	QString stringValue(value.toString());
	setOption(key, stringValue.toLocal8Bit().constData());
}

void ConfigController::write() {
	GBAConfigSave(&m_config);
}
<commit_msg>Qt: Fix boolean setting loading<commit_after>#include "ConfigController.h"

#include "GameController.h"

#include <QAction>
#include <QMenu>

extern "C" {
#include "platform/commandline.h"
}

using namespace QGBA;

ConfigOption::ConfigOption(QObject* parent)
	: QObject(parent)
{
}

void ConfigOption::connect(std::function<void(const QVariant&)> slot) {
	m_slot = slot;
}

QAction* ConfigOption::addValue(const QString& text, const QVariant& value, QMenu* parent) {
	QAction* action = new QAction(text, parent);
	action->setCheckable(true);
	QObject::connect(action, &QAction::triggered, [this, value]() {
		emit valueChanged(value);
	});
	parent->addAction(action);
	m_actions.append(qMakePair(action, value));
	return action;
}

QAction* ConfigOption::addValue(const QString& text, const char* value, QMenu* parent) {
	return addValue(text, QString(value), parent);
}

QAction* ConfigOption::addBoolean(const QString& text, QMenu* parent) {
	QAction* action = new QAction(text, parent);
	action->setCheckable(true);
	QObject::connect(action, &QAction::triggered, [this, action]() {
		emit valueChanged(action->isChecked());
	});
	parent->addAction(action);
	m_actions.append(qMakePair(action, 1));
	return action;
}

void ConfigOption::setValue(bool value) {
	setValue(QVariant(value));
}

void ConfigOption::setValue(int value) {
	setValue(QVariant(value));
}

void ConfigOption::setValue(unsigned value) {
	setValue(QVariant(value));
}

void ConfigOption::setValue(const char* value) {
	setValue(QVariant(QString(value)));
}

void ConfigOption::setValue(const QVariant& value) {
	QPair<QAction*, QVariant> action;
	foreach(action, m_actions) {
		bool signalsEnabled = action.first->blockSignals(true);
		action.first->setChecked(value == action.second);
		action.first->blockSignals(signalsEnabled);
	}
	m_slot(value);
}

ConfigController::ConfigController(QObject* parent)
	: QObject(parent)
	, m_opts()
{
	GBAConfigInit(&m_config, PORT);

	m_opts.audioSync = GameController::AUDIO_SYNC;
	m_opts.videoSync = GameController::VIDEO_SYNC;
	m_opts.fpsTarget = 60;
	m_opts.audioBuffers = 768;
	GBAConfigLoadDefaults(&m_config, &m_opts);
	GBAConfigLoad(&m_config);
	GBAConfigMap(&m_config, &m_opts);
}

ConfigController::~ConfigController() {
	write();

	GBAConfigDeinit(&m_config);
	GBAConfigFreeOpts(&m_opts);
}

bool ConfigController::parseArguments(GBAArguments* args, int argc, char* argv[]) {
	return ::parseArguments(args, &m_config, argc, argv, 0);
}

ConfigOption* ConfigController::addOption(const char* key) {
	QString optionName(key);

	if (m_optionSet.contains(optionName)) {
		return m_optionSet[optionName];
	}
	ConfigOption* newOption = new ConfigOption(this);
	m_optionSet[optionName] = newOption;
	connect(newOption, &ConfigOption::valueChanged, [this, key](const QVariant& value) {
		setOption(key, value);
	});
	return newOption;
}

void ConfigController::updateOption(const char* key) {
	if (!key) {
		return;
	}

	QString optionName(key);

	if (!m_optionSet.contains(optionName)) {
		return;
	}
	m_optionSet[optionName]->setValue(GBAConfigGetValue(&m_config, key));
}

void ConfigController::setOption(const char* key, bool value) {
	GBAConfigSetIntValue(&m_config, key, value);
	ConfigOption* option = m_optionSet[QString(key)];
	if (option) {
		option->setValue(value);
	}
}

void ConfigController::setOption(const char* key, int value) {
	GBAConfigSetIntValue(&m_config, key, value);
	ConfigOption* option = m_optionSet[QString(key)];
	if (option) {
		option->setValue(value);
	}
}

void ConfigController::setOption(const char* key, unsigned value) {
	GBAConfigSetUIntValue(&m_config, key, value);
	ConfigOption* option = m_optionSet[QString(key)];
	if (option) {
		option->setValue(value);
	}
}

void ConfigController::setOption(const char* key, const char* value) {
	GBAConfigSetValue(&m_config, key, value);
	ConfigOption* option = m_optionSet[QString(key)];
	if (option) {
		option->setValue(value);
	}
}

void ConfigController::setOption(const char* key, const QVariant& value) {
	if (value.type() == QVariant::Bool) {
		setOption(key, value.toBool());
		return;
	}
	QString stringValue(value.toString());
	setOption(key, stringValue.toLocal8Bit().constData());
}

void ConfigController::write() {
	GBAConfigSave(&m_config);
}
<|endoftext|>