<commit_before>/* Copyright (C) 2005-2008 Damien Stehle.
   Copyright (C) 2007 David Cade.
   Copyright (C) 2011 Xavier Pujol.

   This file is part of fplll. fplll 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.

   fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */

/* Template source file */

#include "hlll.h"
#include "util.h"

FPLLL_BEGIN_NAMESPACE

template <class ZT, class FT> void HLLLReduction<ZT, FT>::lll()
{
  int k     = 1;
  int k_max = 0;
  FT s;
  FT tmp;
  FT sum;
  FT delta_      = delta;  // TODO: not exactly the good value
  int start_time = cputime();
  long expo_k1_k1, expo_k_k1, expo_k_k;

  m.update_R(0);

  if (verbose)
    print_params();

  while (k < m.get_d())
  {
    if (k > k_max)
    {
      if (verbose)
      {
        cerr << "Discovering vector " << k + 1 << "/" << m.get_d()
             << " cputime=" << cputime() - start_time << endl;
      }
      k_max = k;
    }

    size_reduction(k);

    m.get_R(s, k, k - 1, expo_k_k1);
    s.mul(s, s);  // s = R(k, k - 1)^2
    m.get_R(tmp, k, k, expo_k_k);
    tmp.mul(tmp, tmp);  // tmp = R(k, k)^2
    s.add(tmp, s);      // s = R(k, k - 1)^2 + R(k, k)^2
    m.get_R(tmp, k - 1, k - 1, expo_k1_k1);
    tmp.mul(tmp, tmp);
    tmp.mul(delta_, tmp);  // tmp = delta_ * R(k - 1, k - 1)^2

    if (expo_k1_k1 > -1)
      s.mul_2si(s, 2 * (expo_k_k - expo_k1_k1));
    if (tmp <= s)
      k++;
    else
    {
      m.swap(k - 1, k);
      k = max(k - 1, 1);
    }
  }
}

template <class ZT, class FT> void HLLLReduction<ZT, FT>::size_reduction(int kappa)
{
  vector<FT> xf(kappa);
  FT ftmp0, ftmp1;
  long expo0 = -1;
  long expo1 = -1;
  int min_index;

  do
  {
    min_index = 0;
    m.update_R(kappa, kappa);

    for (int i = kappa - 1; i >= 0; i--)
    {
      m.get_R(ftmp1, kappa, i, expo0);  // expo0 = row_expo[kappa]
      m.get_R(ftmp0, i, i, expo1);      // expo1 = row_expo[i]

      ftmp1.div(ftmp1, ftmp0);  // x[i] = R(kappa, i) / R(i, i)
      /* If T = mpfr or dpe, enable_row_expo must be false and then, expo0 - expo1 == 0 (required by
       * rnd_we with this types) */
      ftmp1.rnd_we(ftmp1, expo0 - expo1);
      xf[i].neg(ftmp1);

      if (ftmp1.cmp(0.0) != 0)
      {
        for (int j = 0; j < i; j++)
        {
          m.get_R(ftmp1, i, j, expo0);      // expo0 = row_expo[i]
          ftmp1.mul(xf[i], ftmp1);          // ftmp1 = x[i] * R(i, j)
          m.get_R(ftmp0, kappa, j, expo0);  // expo0 = row_expo[kappa]
          ftmp0.add(ftmp0, ftmp1);          // ftmp0 = R(kappa, j) + x[i] * R(i, j)
          m.set_R(ftmp0, kappa, j);
        }
        min_index = max(min_index, i + 1);
      }
    }

    m.norm_square_b_row(ftmp1, kappa, expo0);  // ftmp1 = ||b[kappa]||^2
    m.addmul_b_rows(kappa, xf);
    m.norm_square_b_row(ftmp0, kappa, expo1);  // ftmp0 = ||b[kappa]||^2
    ftmp1.mul(sr, ftmp1);                      // ftmp1 = 2^(-cd) * ftmp1

    if (expo1 > -1)
      ftmp0.mul_2si(ftmp0, expo1 - expo0);
  } while (ftmp0.cmp(ftmp1) <= 0);

  if (min_index == 0)
    m.update_R_last(kappa);
  else
    m.update_R(kappa);
}

// Works only there is no row_expo.
template <class ZT, class FT>
bool is_hlll_reduced(MatHouseholder<ZT, FT> &m, double delta, double eta)
{
  FT ftmp0;
  FT ftmp1;
  FT delta_ = delta;
  m.update_R();
  long expo;

  for (int i = 0; i < m.get_d(); i++)
  {
    for (int j = 0; j < i; j++)
    {
      m.get_R(ftmp0, i, j, expo);
      m.get_R(ftmp1, j, j, expo);
      ftmp1.div(ftmp0, ftmp1);
      ftmp1.abs(ftmp1);
      if (ftmp1.cmp(0.5) > 0)
        return false;
    }
  }
  for (int i = 1; i < m.get_d(); i++)
  {
    m.norm_square_b_row(ftmp0, i, expo);  // ftmp0 = ||b[i]||^2
    m.norm_square_R_row(ftmp1, i, i - 1, expo);
    ftmp1.sub(ftmp0, ftmp1);  // ftmp1 = ||b[i]||^2 - sum_{i = 0}^{i < i - 1}R[i][i]^2
    m.get_R(ftmp0, i - 1, i - 1, expo);
    ftmp0.mul(ftmp0, ftmp0);
    ftmp0.mul(delta_, ftmp0);  // ftmp0 = delta_ * R(i - 1, i - 1)^2

    if (ftmp0.cmp(ftmp1) > 0)
      return false;
  }
  return true;
}

/** instantiate functions **/

template class HLLLReduction<Z_NR<long>, FP_NR<double>>;
template class HLLLReduction<Z_NR<double>, FP_NR<double>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<double>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<double>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<double>>(MatHouseholder<Z_NR<long>, FP_NR<double>> &m,
                                           double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<double>>(MatHouseholder<Z_NR<double>, FP_NR<double>> &m,
                                             double delta, double eta);

#ifdef FPLLL_WITH_LONG_DOUBLE
template class HLLLReduction<Z_NR<long>, FP_NR<long double>>;
template class HLLLReduction<Z_NR<double>, FP_NR<long double>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<long double>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<long double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<long double>> &m,
                                                 double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<long double>>(MatHouseholder<Z_NR<long>, FP_NR<long double>> &m,
                                                double delta, double eta);
template bool is_hlll_reduced<Z_NR<double>, FP_NR<long double>>(
    MatHouseholder<Z_NR<double>, FP_NR<long double>> &m, double delta, double eta);
#endif

#ifdef FPLLL_WITH_QD
template class HLLLReduction<Z_NR<long>, FP_NR<dd_real>>;
template class HLLLReduction<Z_NR<double>, FP_NR<dd_real>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dd_real>>;

template class HLLLReduction<Z_NR<long>, FP_NR<qd_real>>;
template class HLLLReduction<Z_NR<double>, FP_NR<qd_real>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<qd_real>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<qd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<qd_real>> &m,
                                             double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<qd_real>>(MatHouseholder<Z_NR<long>, FP_NR<qd_real>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<qd_real>>(MatHouseholder<Z_NR<double>, FP_NR<qd_real>> &m,
                                              double delta, double eta);
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dd_real>> &m,
                                             double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<dd_real>>(MatHouseholder<Z_NR<long>, FP_NR<dd_real>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<dd_real>>(MatHouseholder<Z_NR<double>, FP_NR<dd_real>> &m,
                                              double delta, double eta);
#endif

#ifdef FPLLL_WITH_DPE
template class HLLLReduction<Z_NR<long>, FP_NR<dpe_t>>;
template class HLLLReduction<Z_NR<double>, FP_NR<dpe_t>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dpe_t>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dpe_t>> &m,
                                           double delta, double eta);
template bool is_hlll_reduced<Z_NR<long>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<long>, FP_NR<dpe_t>> &m,
                                                        double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<double>, FP_NR<dpe_t>> &m,
                                            double delta, double eta);
#endif

template class HLLLReduction<Z_NR<long>, FP_NR<mpfr_t>>;
template class HLLLReduction<Z_NR<double>, FP_NR<mpfr_t>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<mpfr_t>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<mpfr_t>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<long>, FP_NR<mpfr_t>> &m,
                                           double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<double>, FP_NR<mpfr_t>> &m,
                                             double delta, double eta);

FPLLL_END_NAMESPACE
<commit_msg>Rename variable.<commit_after>/* Copyright (C) 2005-2008 Damien Stehle.
   Copyright (C) 2007 David Cade.
   Copyright (C) 2011 Xavier Pujol.

   This file is part of fplll. fplll 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.

   fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */

/* Template source file */

#include "hlll.h"
#include "util.h"

FPLLL_BEGIN_NAMESPACE

template <class ZT, class FT> void HLLLReduction<ZT, FT>::lll()
{
  int k     = 1;
  int k_max = 0;
  FT s;
  FT tmp;
  FT sum;
  FT delta_      = delta;  // TODO: not exactly the good value
  int start_time = cputime();
  long expo_k1_k1, expo_k_k1, expo_k_k;

  m.update_R(0);

  if (verbose)
    print_params();

  while (k < m.get_d())
  {
    if (k > k_max)
    {
      if (verbose)
      {
        cerr << "Discovering vector " << k + 1 << "/" << m.get_d()
             << " cputime=" << cputime() - start_time << endl;
      }
      k_max = k;
    }

    size_reduction(k);

    m.get_R(s, k, k - 1, expo_k_k1);
    s.mul(s, s);  // s = R(k, k - 1)^2
    m.get_R(tmp, k, k, expo_k_k);
    tmp.mul(tmp, tmp);  // tmp = R(k, k)^2
    s.add(tmp, s);      // s = R(k, k - 1)^2 + R(k, k)^2
    m.get_R(tmp, k - 1, k - 1, expo_k1_k1);
    tmp.mul(tmp, tmp);
    tmp.mul(delta_, tmp);  // tmp = delta_ * R(k - 1, k - 1)^2

    if (expo_k1_k1 > -1)
      s.mul_2si(s, 2 * (expo_k_k - expo_k1_k1));
    if (tmp <= s)
      k++;
    else
    {
      m.swap(k - 1, k);
      k = max(k - 1, 1);
    }
  }
}

template <class ZT, class FT> void HLLLReduction<ZT, FT>::size_reduction(int kappa)
{
  vector<FT> xf(kappa);
  FT ftmp0, ftmp1;
  long expo0 = -1;
  long expo1 = -1;
  // for all i > max_index, xf[i] == 0.
  int max_index;

  do
  {
    max_index = -1;
    m.update_R(kappa, kappa);

    for (int i = kappa - 1; i >= 0; i--)
    {
      m.get_R(ftmp1, kappa, i, expo0);  // expo0 = row_expo[kappa]
      m.get_R(ftmp0, i, i, expo1);      // expo1 = row_expo[i]

      ftmp1.div(ftmp1, ftmp0);  // x[i] = R(kappa, i) / R(i, i)
      /* If T = mpfr or dpe, enable_row_expo must be false and then, expo0 - expo1 == 0 (required by
       * rnd_we with this types) */
      ftmp1.rnd_we(ftmp1, expo0 - expo1);
      xf[i].neg(ftmp1);

      if (ftmp1.cmp(0.0) != 0)
      {
        for (int j = 0; j < i; j++)
        {
          m.get_R(ftmp1, i, j, expo0);      // expo0 = row_expo[i]
          ftmp1.mul(xf[i], ftmp1);          // ftmp1 = x[i] * R(i, j)
          m.get_R(ftmp0, kappa, j, expo0);  // expo0 = row_expo[kappa]
          ftmp0.add(ftmp0, ftmp1);          // ftmp0 = R(kappa, j) + x[i] * R(i, j)
          m.set_R(ftmp0, kappa, j);
        }
        max_index = max(max_index, i);
      }
    }

    m.norm_square_b_row(ftmp1, kappa, expo0);  // ftmp1 = ||b[kappa]||^2
    m.addmul_b_rows(kappa, xf);
    m.norm_square_b_row(ftmp0, kappa, expo1);  // ftmp0 = ||b[kappa]||^2
    ftmp1.mul(sr, ftmp1);                      // ftmp1 = 2^(-cd) * ftmp1

    if (expo1 > -1)
      ftmp0.mul_2si(ftmp0, expo1 - expo0);
  } while (ftmp0.cmp(ftmp1) <= 0);

  if (max_index == -1)
    m.update_R_last(kappa);
  else
    m.update_R(kappa);
}

// Works only there is no row_expo.
template <class ZT, class FT>
bool is_hlll_reduced(MatHouseholder<ZT, FT> &m, double delta, double eta)
{
  FT ftmp0;
  FT ftmp1;
  FT delta_ = delta;
  m.update_R();
  long expo;

  for (int i = 0; i < m.get_d(); i++)
  {
    for (int j = 0; j < i; j++)
    {
      m.get_R(ftmp0, i, j, expo);
      m.get_R(ftmp1, j, j, expo);
      ftmp1.div(ftmp0, ftmp1);
      ftmp1.abs(ftmp1);
      if (ftmp1.cmp(0.5) > 0)
        return false;
    }
  }
  for (int i = 1; i < m.get_d(); i++)
  {
    m.norm_square_b_row(ftmp0, i, expo);  // ftmp0 = ||b[i]||^2
    m.norm_square_R_row(ftmp1, i, i - 1, expo);
    ftmp1.sub(ftmp0, ftmp1);  // ftmp1 = ||b[i]||^2 - sum_{i = 0}^{i < i - 1}R[i][i]^2
    m.get_R(ftmp0, i - 1, i - 1, expo);
    ftmp0.mul(ftmp0, ftmp0);
    ftmp0.mul(delta_, ftmp0);  // ftmp0 = delta_ * R(i - 1, i - 1)^2

    if (ftmp0.cmp(ftmp1) > 0)
      return false;
  }
  return true;
}

/** instantiate functions **/

template class HLLLReduction<Z_NR<long>, FP_NR<double>>;
template class HLLLReduction<Z_NR<double>, FP_NR<double>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<double>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<double>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<double>>(MatHouseholder<Z_NR<long>, FP_NR<double>> &m,
                                           double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<double>>(MatHouseholder<Z_NR<double>, FP_NR<double>> &m,
                                             double delta, double eta);

#ifdef FPLLL_WITH_LONG_DOUBLE
template class HLLLReduction<Z_NR<long>, FP_NR<long double>>;
template class HLLLReduction<Z_NR<double>, FP_NR<long double>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<long double>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<long double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<long double>> &m,
                                                 double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<long double>>(MatHouseholder<Z_NR<long>, FP_NR<long double>> &m,
                                                double delta, double eta);
template bool is_hlll_reduced<Z_NR<double>, FP_NR<long double>>(
    MatHouseholder<Z_NR<double>, FP_NR<long double>> &m, double delta, double eta);
#endif

#ifdef FPLLL_WITH_QD
template class HLLLReduction<Z_NR<long>, FP_NR<dd_real>>;
template class HLLLReduction<Z_NR<double>, FP_NR<dd_real>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dd_real>>;

template class HLLLReduction<Z_NR<long>, FP_NR<qd_real>>;
template class HLLLReduction<Z_NR<double>, FP_NR<qd_real>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<qd_real>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<qd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<qd_real>> &m,
                                             double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<qd_real>>(MatHouseholder<Z_NR<long>, FP_NR<qd_real>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<qd_real>>(MatHouseholder<Z_NR<double>, FP_NR<qd_real>> &m,
                                              double delta, double eta);
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dd_real>> &m,
                                             double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<dd_real>>(MatHouseholder<Z_NR<long>, FP_NR<dd_real>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<dd_real>>(MatHouseholder<Z_NR<double>, FP_NR<dd_real>> &m,
                                              double delta, double eta);
#endif

#ifdef FPLLL_WITH_DPE
template class HLLLReduction<Z_NR<long>, FP_NR<dpe_t>>;
template class HLLLReduction<Z_NR<double>, FP_NR<dpe_t>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dpe_t>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dpe_t>> &m,
                                           double delta, double eta);
template bool is_hlll_reduced<Z_NR<long>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<long>, FP_NR<dpe_t>> &m,
                                                        double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<double>, FP_NR<dpe_t>> &m,
                                            double delta, double eta);
#endif

template class HLLLReduction<Z_NR<long>, FP_NR<mpfr_t>>;
template class HLLLReduction<Z_NR<double>, FP_NR<mpfr_t>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<mpfr_t>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<mpfr_t>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<long>, FP_NR<mpfr_t>> &m,
                                           double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<double>, FP_NR<mpfr_t>> &m,
                                             double delta, double eta);

FPLLL_END_NAMESPACE
<|endoftext|>


<commit_before>#include "pch.h"
#include "zip_package.h"
#include "memory_stream.h"

ZipPackage::ZipPackage(struct zip * zipFile)
{
    _zipFile.reset(zipFile, zip_close);
}

ZipPackage::~ZipPackage()
{
}

ZipPackage * ZipPackage::create(const char * zipFile)
{
    int err = 0;
    zip * res = zip_open(zipFile, 0, &err);

    return res == NULL ? nullptr : new ZipPackage(res);
}

gameplay::Stream * ZipPackage::open(const char * path, size_t streamMode)
{
    if (streamMode != gameplay::FileSystem::READ)
        return NULL;

    std::string fullPath = gameplay::FileSystem::resolvePath(path);

    //Search for the file of given name
    struct zip_stat st;
    zip_stat_init(&st);
    if (zip_stat(_zipFile.get(), fullPath.c_str(), 0, &st) != 0)
    {
        GP_WARN("Can't open file %s", path);
        return NULL;
    }

    //Alloc memory for its uncompressed contents
    size_t fileSize = static_cast<size_t>(st.size);
    std::unique_ptr< uint8_t[] >contents(new uint8_t[fileSize]);

    //Read the compressed file
    zip_file *f = zip_fopen(_zipFile.get(), fullPath.c_str(), 0);
    if (!f)
    {
        GP_WARN("Can't open file %s", path);
        return NULL;
    }
    zip_fread(f, contents.get(), fileSize);
    zip_fclose(f);

    return MemoryStream::create(contents, fileSize);
}

bool ZipPackage::fileExists(const char * path)
{
    std::string fullPath = gameplay::FileSystem::resolvePath(path);

    struct zip_stat st;
    zip_stat_init(&st);
    return zip_stat(_zipFile.get(), fullPath.c_str(), 0, &st) == 0;
}<commit_msg>removed warnings in ZipPackage when file couldn't be opened<commit_after>#include "pch.h"
#include "zip_package.h"
#include "memory_stream.h"

ZipPackage::ZipPackage(struct zip * zipFile)
{
    _zipFile.reset(zipFile, zip_close);
}

ZipPackage::~ZipPackage()
{
}

ZipPackage * ZipPackage::create(const char * zipFile)
{
    int err = 0;
    zip * res = zip_open(zipFile, 0, &err);

    return res == NULL ? nullptr : new ZipPackage(res);
}

gameplay::Stream * ZipPackage::open(const char * path, size_t streamMode)
{
    if (streamMode != gameplay::FileSystem::READ)
        return NULL;

    std::string fullPath = gameplay::FileSystem::resolvePath(path);

    //Search for the file of given name
    struct zip_stat st;
    zip_stat_init(&st);
    if (zip_stat(_zipFile.get(), fullPath.c_str(), 0, &st) != 0)
        return NULL;

    //Alloc memory for its uncompressed contents
    size_t fileSize = static_cast<size_t>(st.size);
    std::unique_ptr< uint8_t[] >contents(new uint8_t[fileSize]);

    //Read the compressed file
    zip_file *f = zip_fopen(_zipFile.get(), fullPath.c_str(), 0);
    if (!f)
        return NULL;

    zip_fread(f, contents.get(), fileSize);
    zip_fclose(f);

    return MemoryStream::create(contents, fileSize);
}

bool ZipPackage::fileExists(const char * path)
{
    std::string fullPath = gameplay::FileSystem::resolvePath(path);

    struct zip_stat st;
    zip_stat_init(&st);
    return zip_stat(_zipFile.get(), fullPath.c_str(), 0, &st) == 0;
}<|endoftext|>


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

#include <jni.h>

#include <realm/string_data.hpp>
#include <realm/unicode.hpp>

#include "io_realm_log_LogLevel.h"
#include "mem_usage.hpp"
#include "util.hpp"

using std::string;

//#define USE_VLD
#if defined(_MSC_VER) && defined(_DEBUG) && defined(USE_VLD)
    #include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif

// used by logging
int trace_level = 0;
jclass realmlog_class;
jmethodID log_trace;
jmethodID log_debug;
jmethodID log_info;
jmethodID log_warn;
jmethodID log_error;
jmethodID log_fatal;

const string TABLE_PREFIX("class_");

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*)
{
    JNIEnv* env;
    if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR;
    }
    else {
        g_vm = vm;
        // Loading classes and constructors for later use - used by box typed fields and a few methods' return value
        java_lang_long        = GetClass(env, "java/lang/Long");
        java_lang_long_init   = env->GetMethodID(java_lang_long, "<init>", "(J)V");
        java_lang_float       = GetClass(env, "java/lang/Float");
        java_lang_float_init  = env->GetMethodID(java_lang_float, "<init>", "(F)V");
        java_lang_double      = GetClass(env, "java/lang/Double");
        java_lang_double_init = env->GetMethodID(java_lang_double, "<init>", "(D)V");
        sync_manager          = GetClass(env, "io/realm/SyncManager");
        realmlog_class        = GetClass(env, "io/realm/log/RealmLog");
        log_trace             = env->GetStaticMethodID(realmlog_class, "trace", "(Ljava/lang/String;[Ljava/lang/Object;)V");
        log_debug             = env->GetStaticMethodID(realmlog_class, "debug", "(Ljava/lang/String;[Ljava/lang/Object;)V");
        log_info              = env->GetStaticMethodID(realmlog_class, "info", "(Ljava/lang/String;[Ljava/lang/Object;)V");
        log_warn              = env->GetStaticMethodID(realmlog_class, "warn", "(Ljava/lang/String;[Ljava/lang/Object;)V");
        log_error             = env->GetStaticMethodID(realmlog_class, "error", "(Ljava/lang/String;[Ljava/lang/Object;)V");
        log_fatal             = env->GetStaticMethodID(realmlog_class, "fatal", "(Ljava/lang/String;[Ljava/lang/Object;)V");
    }

    return JNI_VERSION_1_6;
}

JNIEXPORT void JNI_OnUnload(JavaVM* vm, void*)
{
    JNIEnv* env;
    if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
        return;
    }
    else {
        env->DeleteGlobalRef(java_lang_long);
        env->DeleteGlobalRef(java_lang_float);
        env->DeleteGlobalRef(java_lang_double);
    }
}

JNIEXPORT void JNICALL Java_io_realm_internal_Util_nativeSetDebugLevel(JNIEnv*, jclass, jint level)
{
    /**
     * level should match one of the levels defined in LogLevel.java
     * ALL = 1
     * TRACE = 2
     * DEBUG = 3
     * INFO = 4
     * WARN = 5
     * ERROR = 6
     * FATAL = 7
     * OFF = 8
     */
    trace_level = level;
}

JNIEXPORT jlong JNICALL Java_io_realm_internal_Util_nativeGetMemUsage(JNIEnv*, jclass)
{
    return GetMemUsage();
}

JNIEXPORT jstring JNICALL Java_io_realm_internal_Util_nativeGetTablePrefix(
    JNIEnv* env, jclass)
{
    realm::StringData sd(TABLE_PREFIX);
    return to_jstring(env, sd);
}
<commit_msg>Remove dup & uselss file<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include<limits>

using namespace std;

typedef unsigned long long int ulli;

class bigInt
{
private:
	vector<int> val;
	int end;
	bigInt karatsuba(bigInt &lhs, bigInt &rhs);
	void partialCopy(bigInt &tar, const bigInt &rhs, int beg, int fin);
	bigInt operator*(int rhs);
public:
	bigInt();
	explicit bigInt(ulli a);
	void set(ulli a);
	bigInt operator+(bigInt &rhs);
	bigInt operator-(bigInt &rhs);
	bigInt &operator=(bigInt &rhs);
	bigInt operator*(bigInt &rhs);
	friend ostream &operator<<(ostream & out, const bigInt &rhs);
	void doubleMe();
	ulli getVal();
};

ostream &operator<<(ostream & out, const bigInt &rhs)
{
	for(int i = rhs.end; i >= 0 && rhs.val[i] >= 0; --i)
	{
		out<<rhs.val[i];
	}
	return out;
}

bigInt::bigInt():val(1000, 0), end(-1)
{

}

bigInt::bigInt(ulli a):val(1000, 0), end(-1)
{
	set(a);

}

void bigInt::set(ulli a)
{
	end = -1;
	int rem = 0;
	ulli div = a;
	while(div > 0)
	{
		rem = div % 10;
		div /= 10;
		++end;
		val[end] = rem;
	}
}

bigInt & bigInt::operator=(bigInt &rhs)
{
	this->end = rhs.end;
	for(int i = 0; i <= end; ++i)
	{
		val[i] = rhs.val[i];
	}
	return *this;
}

bigInt bigInt::operator+(bigInt &rhs)
{
	bigInt nVal;
	int mx = max(end, rhs.end);
	int over = 0;
	int temp = 0;
	nVal.end = mx;
	for(int i = 0; i <= mx; ++i )
	{
		temp = val[i] + rhs.val[i] + over;
		over = temp / 10;
		nVal.val[i] = temp % 10;
	}
	if(over != 0)
	{
		nVal.end++;
		nVal.val[nVal.end] = over;
	}
	return nVal;
}

void bigInt::doubleMe()
{
	bigInt rhs = karatsuba(*this, *this);
	end = rhs.end;
	for(int i = 0; i <= end; ++i)
	{
		val[i] = rhs.val[i];
	}
}

	bigInt bigInt::karatsuba(bigInt &lhs, bigInt &rhs)
	{

		bigInt t1, t2;
		t1.end = 0;
		t2.end = 0;
		int over = 0;
		int i, j;
		for(i = 0; i <= end; ++i)
		{
			t1.end = 0;
			for(j = 0; j <= rhs.end; ++j)
			{
				int a = val[i] * rhs.val[j];
				a += over;
				over = a / 10;
				a %= 10;
				t1.val[j] = a;
			}
			t1.end = j - 1;
			if(over != 0)
			{
				t1.val[j] = over;
				t1.end++;
			}
			t1 * i;
			bigInt s = t2 + t1;
			t2 = s;
		}
		return t2;
		//AB * CD = (B*D) + [(A+B)(C+D) - B*D - A*C]*10^n + A*C*10^2n
		/*if(lhs.end <= 10 || rhs.end <= 10)
		{
			return bigInt(lhs.getVal() * rhs.getVal());
		}
		int mx = max(lhs.end, rhs.end);
		int mid = mx / 2;
		bigInt low1, low2, high1, high2;
		partialCopy(low1, lhs, 0, mid);
		partialCopy(low2, rhs, 0, mid);
		partialCopy(high1, lhs, mid + 1, lhs.end);
		partialCopy(high1, lhs, mid + 1, rhs.end);
		bigInt bd = karatsuba(low1, low2);
		bigInt ac = karatsuba(high1, high2);
		bigInt sum1 = low1 + high1;
		bigInt sum2 = low2 + high2;
		bigInt abcd = karatsuba(sum1, sum2);
		bigInt middle = (abcd - bd - ac);
		middle*mid;
		ac * (2 * mid);
		return bd +  middle + ac; //integer multiplications actually are like 10 ^ mid...*/
	}

	bigInt bigInt::operator*(bigInt &rhs)
	{
		return karatsuba(*this, rhs);
	}

bigInt bigInt::operator*(int rhs) //this will only recive powers of 10
{
	end += rhs;
	while(rhs > 0)
	{
		val.insert(val.begin(), 0);
		rhs--;
	}
	return *this;
}

void bigInt::partialCopy(bigInt &tar, const bigInt &rhs, int beg, int fin)
{
	if(fin >= beg)
	{
		int end = fin - beg;
		for(int i = 0; i <= end; ++i, ++beg)
		{
			tar.val[i] = rhs.val[beg];
		}
	}
}

ulli bigInt::getVal()
{
	ulli val = 0;
	if(end <= 20)
	{
		for(int i = 0; i <= end; ++i)
		{
			val += this->val[i] * pow(10, i);
		}
	}
	return val;
}

bigInt bigInt::operator-(bigInt &rhs)
{
	bigInt nV;
	if(end < rhs.end)
		return bigInt(0);
	for(int i = 0; i <= end; ++i)
	{
		if(val[i] < rhs.val[i])
		{
			if( i+1 > end)
				return bigInt(0);
			val[i] += 10;
			val[i + 1]--;
		}
		nV.val[i] = val[i] - rhs.val[i];
	}
	int e = end;
	while(e >= 0)
	{
		if(nV.val[e] != 0)
		{
			nV.end = e;
			break;
		}
		--e;
	}
	return nV;
}

int main()
{
	bigInt b1(9);
	bigInt b2(3);
	cout<<b1<<" + "<<b2<<" = "<<b1 + b2<<endl;
	cout<<b1<<" - "<<b2<<" = "<<b1 - b2<<endl;
	/*cout<<b1<<" * 1"<<" = "<<b1 * 1<<endl;
	cout<<b1<<endl;
	b1.set(9);*/
	cout<<b1<<" * "<<b2<<" = "<<b1 * b2<<endl;
	cout<<b1.getVal()<<endl;
	b1.set(numeric_limits<ulli>::max());
	cout<<b1<<endl;
	cout<<b1<<" + "<<b2<<" = "<<b1 + b2<<endl;
	cout<<b1<<" * "<<b2<<" = "<<b1 * b2<<endl;
	b2.set(15);
	b2.doubleMe();
	cout<<b2<<endl;

}<commit_msg>Indentation fix<commit_after>#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include<limits>

using namespace std;

typedef unsigned long long int ulli;

class bigInt
{
private:
	vector<int> val;
	int end;
	bigInt karatsuba(bigInt &lhs, bigInt &rhs);
	void partialCopy(bigInt &tar, const bigInt &rhs, int beg, int fin);
	bigInt operator*(int rhs);
public:
	bigInt();
	explicit bigInt(ulli a);
	void set(ulli a);
	bigInt operator+(bigInt &rhs);
	bigInt operator-(bigInt &rhs);
	bigInt &operator=(bigInt &rhs);
	bigInt operator*(bigInt &rhs);
	friend ostream &operator<<(ostream & out, const bigInt &rhs);
	void doubleMe();
	ulli getVal();
};

ostream &operator<<(ostream & out, const bigInt &rhs)
{
	for(int i = rhs.end; i >= 0 && rhs.val[i] >= 0; --i)
	{
		out<<rhs.val[i];
	}
	return out;
}

bigInt::bigInt():val(1000, 0), end(-1)
{

}

bigInt::bigInt(ulli a):val(1000, 0), end(-1)
{
	set(a);

}

void bigInt::set(ulli a)
{
	end = -1;
	int rem = 0;
	ulli div = a;
	while(div > 0)
	{
		rem = div % 10;
		div /= 10;
		++end;
		val[end] = rem;
	}
}

bigInt & bigInt::operator=(bigInt &rhs)
{
	this->end = rhs.end;
	for(int i = 0; i <= end; ++i)
	{
		val[i] = rhs.val[i];
	}
	return *this;
}

bigInt bigInt::operator+(bigInt &rhs)
{
	bigInt nVal;
	int mx = max(end, rhs.end);
	int over = 0;
	int temp = 0;
	nVal.end = mx;
	for(int i = 0; i <= mx; ++i )
	{
		temp = val[i] + rhs.val[i] + over;
		over = temp / 10;
		nVal.val[i] = temp % 10;
	}
	if(over != 0)
	{
		nVal.end++;
		nVal.val[nVal.end] = over;
	}
	return nVal;
}

void bigInt::doubleMe()
{
	bigInt rhs = karatsuba(*this, *this);
	end = rhs.end;
	for(int i = 0; i <= end; ++i)
	{
		val[i] = rhs.val[i];
	}
}

bigInt bigInt::karatsuba(bigInt &lhs, bigInt &rhs)
{

	bigInt t1, t2;
	t1.end = 0;
	t2.end = 0;
	int over = 0;
	int i, j;
	for(i = 0; i <= end; ++i)
	{
		t1.end = 0;
		for(j = 0; j <= rhs.end; ++j)
		{
			int a = val[i] * rhs.val[j];
			a += over;
			over = a / 10;
			a %= 10;
			t1.val[j] = a;
		}
		t1.end = j - 1;
		if(over != 0)
		{
			t1.val[j] = over;
			t1.end++;
		}
		t1 * i;
		bigInt s = t2 + t1;
		t2 = s;
	}
	return t2;
	//AB * CD = (B*D) + [(A+B)(C+D) - B*D - A*C]*10^n + A*C*10^2n
	/*if(lhs.end <= 10 || rhs.end <= 10)
	{
		return bigInt(lhs.getVal() * rhs.getVal());
	}
	int mx = max(lhs.end, rhs.end);
	int mid = mx / 2;
	bigInt low1, low2, high1, high2;
	partialCopy(low1, lhs, 0, mid);
	partialCopy(low2, rhs, 0, mid);
	partialCopy(high1, lhs, mid + 1, lhs.end);
	partialCopy(high1, lhs, mid + 1, rhs.end);
	bigInt bd = karatsuba(low1, low2);
	bigInt ac = karatsuba(high1, high2);
	bigInt sum1 = low1 + high1;
	bigInt sum2 = low2 + high2;
	bigInt abcd = karatsuba(sum1, sum2);
	bigInt middle = (abcd - bd - ac);
	middle*mid;
	ac * (2 * mid);
	return bd +  middle + ac; //integer multiplications actually are like 10 ^ mid...*/
}

bigInt bigInt::operator*(bigInt &rhs)
{
	return karatsuba(*this, rhs);
}

bigInt bigInt::operator*(int rhs) //this will only recive powers of 10
{
	end += rhs;
	while(rhs > 0)
	{
		val.insert(val.begin(), 0);
		rhs--;
	}
	return *this;
}

void bigInt::partialCopy(bigInt &tar, const bigInt &rhs, int beg, int fin)
{
	if(fin >= beg)
	{
		int end = fin - beg;
		for(int i = 0; i <= end; ++i, ++beg)
		{
			tar.val[i] = rhs.val[beg];
		}
	}
}

ulli bigInt::getVal()
{
	ulli val = 0;
	if(end <= 20)
	{
		for(int i = 0; i <= end; ++i)
		{
			val += this->val[i] * pow(10, i);
		}
	}
	return val;
}

bigInt bigInt::operator-(bigInt &rhs)
{
	bigInt nV;
	if(end < rhs.end)
		return bigInt(0);
	for(int i = 0; i <= end; ++i)
	{
		if(val[i] < rhs.val[i])
		{
			if( i+1 > end)
				return bigInt(0);
			val[i] += 10;
			val[i + 1]--;
		}
		nV.val[i] = val[i] - rhs.val[i];
	}
	int e = end;
	while(e >= 0)
	{
		if(nV.val[e] != 0)
		{
			nV.end = e;
			break;
		}
		--e;
	}
	return nV;
}

int main()
{
	bigInt b1(9);
	bigInt b2(3);
	cout<<b1<<" + "<<b2<<" = "<<b1 + b2<<endl;
	cout<<b1<<" - "<<b2<<" = "<<b1 - b2<<endl;
	/*cout<<b1<<" * 1"<<" = "<<b1 * 1<<endl;
	cout<<b1<<endl;
	b1.set(9);*/
	cout<<b1<<" * "<<b2<<" = "<<b1 * b2<<endl;
	cout<<b1.getVal()<<endl;
	b1.set(numeric_limits<ulli>::max());
	cout<<b1<<endl;
	cout<<b1<<" + "<<b2<<" = "<<b1 + b2<<endl;
	cout<<b1<<" * "<<b2<<" = "<<b1 * b2<<endl;
	b2.set(15);
	b2.doubleMe();
	cout<<b2<<endl;

}<|endoftext|>


<commit_before>/* -*- c-basic-offset: 2 -*- */
/* Copyright(C) 2011-2015 Brazil

  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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "file-impl.hpp"

#include <sys/types.h>
#include <sys/stat.h>

#ifdef WIN32
# ifdef min
#  undef min
# endif  // min
# ifdef max
#  undef max
# endif  // max
#else  // WIN32
# include <fcntl.h>
# include <sys/mman.h>
# include <unistd.h>
#endif  // WIN32

#include <algorithm>
#include <limits>

#ifdef WIN32
# define GRN_IO_FILE_CREATE_MODE (GENERIC_READ | GENERIC_WRITE)
#else /* WIN32 */
# define GRN_IO_FILE_CREATE_MODE 0644
#endif /* WIN32 */

namespace grn {
namespace dat {

#ifdef WIN32

FileImpl::FileImpl()
    : ptr_(NULL),
      size_(0),
      file_(INVALID_HANDLE_VALUE),
      map_(INVALID_HANDLE_VALUE),
      addr_(NULL) {}

FileImpl::~FileImpl() {
  if (addr_ != NULL) {
    ::UnmapViewOfFile(addr_);
  }

  if (map_ != INVALID_HANDLE_VALUE) {
    ::CloseHandle(map_);
  }

  if (file_ != INVALID_HANDLE_VALUE) {
    ::CloseHandle(file_);
  }
}

#else  // WIN32

FileImpl::FileImpl()
    : ptr_(NULL),
      size_(0),
      fd_(-1),
      addr_(MAP_FAILED),
      length_(0) {}

FileImpl::~FileImpl() {
  if (addr_ != MAP_FAILED) {
    ::munmap(addr_, length_);
  }

  if (fd_ != -1) {
    ::close(fd_);
  }
}

#endif  // WIN32

void FileImpl::create(const char *path, UInt64 size) {
  GRN_DAT_THROW_IF(PARAM_ERROR, size == 0);
  GRN_DAT_THROW_IF(PARAM_ERROR,
      size > static_cast<UInt64>(std::numeric_limits< ::size_t>::max()));

  FileImpl new_impl;
  new_impl.create_(path, size);
  new_impl.swap(this);
}

void FileImpl::open(const char *path) {
  GRN_DAT_THROW_IF(PARAM_ERROR, path == NULL);
  GRN_DAT_THROW_IF(PARAM_ERROR, path[0] == '\0');

  FileImpl new_impl;
  new_impl.open_(path);
  new_impl.swap(this);
}

void FileImpl::close() {
  FileImpl new_impl;
  new_impl.swap(this);
}

#ifdef WIN32

void FileImpl::swap(FileImpl *rhs) {
  std::swap(ptr_, rhs->ptr_);
  std::swap(size_, rhs->size_);
  std::swap(file_, rhs->file_);
  std::swap(map_, rhs->map_);
  std::swap(addr_, rhs->addr_);
}

void FileImpl::flush() {
  if (!addr_) {
    return;
  }

  BOOL succeeded = ::FlushViewOfFile(addr_, size_);
  GRN_DAT_THROW_IF(IO_ERROR, !succeeded);

  SYSTEMTIME system_time;
  GetSystemTime(&system_time);
  FILETIME file_time;
  succeeded = SystemTimeToFileTime(&system_time, &file_time);
  GRN_DAT_THROW_IF(IO_ERROR, !succeeded);

  succeeded = SetFileTime(file_, NULL, NULL, &file_time);
  GRN_DAT_THROW_IF(IO_ERROR, !succeeded);
}

void FileImpl::create_(const char *path, UInt64 size) {
  if ((path != NULL) && (path[0] != '\0')) {
    file_ = ::CreateFileA(path, GRN_IO_FILE_CREATE_MODE,
                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                          NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    GRN_DAT_THROW_IF(IO_ERROR, file_ == INVALID_HANDLE_VALUE);

    const LONG size_low = static_cast<LONG>(size & 0xFFFFFFFFU);
    LONG size_high = static_cast<LONG>(size >> 32);
    const DWORD file_pos = ::SetFilePointer(file_, size_low, &size_high,
                                            FILE_BEGIN);
    GRN_DAT_THROW_IF(IO_ERROR, (file_pos == INVALID_SET_FILE_POINTER) &&
                               (::GetLastError() != 0));
    GRN_DAT_THROW_IF(IO_ERROR, ::SetEndOfFile(file_) == 0);

    map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE, 0, 0, NULL);
    GRN_DAT_THROW_IF(IO_ERROR, map_ == INVALID_HANDLE_VALUE);
  } else {
    const DWORD size_low = static_cast<DWORD>(size & 0xFFFFFFFFU);
    const DWORD size_high = static_cast<DWORD>(size >> 32);

    map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE,
                               size_high, size_low, NULL);
    GRN_DAT_THROW_IF(IO_ERROR, map_ == INVALID_HANDLE_VALUE);
  }

  addr_ = ::MapViewOfFile(map_, FILE_MAP_WRITE, 0, 0, 0);
  GRN_DAT_THROW_IF(IO_ERROR, addr_ == NULL);

  ptr_ = addr_;
  size_ = static_cast< ::size_t>(size);
}

void FileImpl::open_(const char *path) {
#ifdef _MSC_VER
  struct __stat64 st;
  GRN_DAT_THROW_IF(IO_ERROR, ::_stat64(path, &st) == -1);
#else  // _MSC_VER
  struct _stat st;
  GRN_DAT_THROW_IF(IO_ERROR, ::_stat(path, &st) == -1);
#endif  // _MSC_VER
  GRN_DAT_THROW_IF(IO_ERROR, st.st_size == 0);
  GRN_DAT_THROW_IF(IO_ERROR,
      static_cast<UInt64>(st.st_size) > std::numeric_limits< ::size_t>::max());

  file_ = ::CreateFileA(path, GRN_IO_FILE_CREATE_MODE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  GRN_DAT_THROW_IF(IO_ERROR, file_ == NULL);

  map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE, 0, 0, NULL);
  GRN_DAT_THROW_IF(IO_ERROR, map_ == NULL);

  addr_ = ::MapViewOfFile(map_, FILE_MAP_WRITE, 0, 0, 0);
  GRN_DAT_THROW_IF(IO_ERROR, addr_ == NULL);

  ptr_ = addr_;
  size_ = static_cast< ::size_t>(st.st_size);
}

#else  // WIN32

void FileImpl::swap(FileImpl *rhs) {
  std::swap(ptr_, rhs->ptr_);
  std::swap(size_, rhs->size_);
  std::swap(fd_, rhs->fd_);
  std::swap(addr_, rhs->addr_);
  std::swap(length_, rhs->length_);
}

void FileImpl::flush() {
  if (!addr_) {
    return;
  }

  int result = ::msync(addr_, length_, MS_SYNC);
  GRN_DAT_THROW_IF(IO_ERROR, result != 0);
}

void FileImpl::create_(const char *path, UInt64 size) {
  GRN_DAT_THROW_IF(PARAM_ERROR,
      size > static_cast<UInt64>(std::numeric_limits< ::off_t>::max()));

  if ((path != NULL) && (path[0] != '\0')) {
    fd_ = ::open(path, O_RDWR | O_CREAT | O_TRUNC, GRN_IO_FILE_CREATE_MODE);
    GRN_DAT_THROW_IF(IO_ERROR, fd_ == -1);

    const ::off_t file_size = static_cast< ::off_t>(size);
    GRN_DAT_THROW_IF(IO_ERROR, ::ftruncate(fd_, file_size) == -1);
  }

#ifdef MAP_ANONYMOUS
  const int flags = (fd_ == -1) ? (MAP_PRIVATE | MAP_ANONYMOUS) : MAP_SHARED;
#else  // MAP_ANONYMOUS
  const int flags = (fd_ == -1) ? (MAP_PRIVATE | MAP_ANON) : MAP_SHARED;
#endif  // MAP_ANONYMOUS

  length_ = static_cast< ::size_t>(size);
#ifdef USE_MAP_HUGETLB
  addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE,
                 flags | MAP_HUGETLB, fd_, 0);
#endif  // USE_MAP_HUGETLB
  if (addr_ == MAP_FAILED) {
    addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE, flags, fd_, 0);
    GRN_DAT_THROW_IF(IO_ERROR, addr_ == MAP_FAILED);
  }

  ptr_ = addr_;
  size_ = length_;
}

void FileImpl::open_(const char *path) {
  struct stat st;
  GRN_DAT_THROW_IF(IO_ERROR, ::stat(path, &st) == -1);
  GRN_DAT_THROW_IF(IO_ERROR, (st.st_mode & S_IFMT) != S_IFREG);
  GRN_DAT_THROW_IF(IO_ERROR, st.st_size == 0);
  GRN_DAT_THROW_IF(IO_ERROR,
      static_cast<UInt64>(st.st_size) > std::numeric_limits< ::size_t>::max());

  fd_ = ::open(path, O_RDWR);
  GRN_DAT_THROW_IF(IO_ERROR, fd_ == -1);

  length_ = static_cast<std::size_t>(st.st_size);
  addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
  GRN_DAT_THROW_IF(IO_ERROR, addr_ == MAP_FAILED);

  ptr_ = addr_;
  size_ = length_;
}

#endif  // WIN32

}  // namespace dat
}  // namespace grn
<commit_msg>windows: add missing cast<commit_after>/* -*- c-basic-offset: 2 -*- */
/* Copyright(C) 2011-2015 Brazil

  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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "file-impl.hpp"

#include <sys/types.h>
#include <sys/stat.h>

#ifdef WIN32
# ifdef min
#  undef min
# endif  // min
# ifdef max
#  undef max
# endif  // max
#else  // WIN32
# include <fcntl.h>
# include <sys/mman.h>
# include <unistd.h>
#endif  // WIN32

#include <algorithm>
#include <limits>

#ifdef WIN32
# define GRN_IO_FILE_CREATE_MODE (GENERIC_READ | GENERIC_WRITE)
#else /* WIN32 */
# define GRN_IO_FILE_CREATE_MODE 0644
#endif /* WIN32 */

namespace grn {
namespace dat {

#ifdef WIN32

FileImpl::FileImpl()
    : ptr_(NULL),
      size_(0),
      file_(INVALID_HANDLE_VALUE),
      map_(INVALID_HANDLE_VALUE),
      addr_(NULL) {}

FileImpl::~FileImpl() {
  if (addr_ != NULL) {
    ::UnmapViewOfFile(addr_);
  }

  if (map_ != INVALID_HANDLE_VALUE) {
    ::CloseHandle(map_);
  }

  if (file_ != INVALID_HANDLE_VALUE) {
    ::CloseHandle(file_);
  }
}

#else  // WIN32

FileImpl::FileImpl()
    : ptr_(NULL),
      size_(0),
      fd_(-1),
      addr_(MAP_FAILED),
      length_(0) {}

FileImpl::~FileImpl() {
  if (addr_ != MAP_FAILED) {
    ::munmap(addr_, length_);
  }

  if (fd_ != -1) {
    ::close(fd_);
  }
}

#endif  // WIN32

void FileImpl::create(const char *path, UInt64 size) {
  GRN_DAT_THROW_IF(PARAM_ERROR, size == 0);
  GRN_DAT_THROW_IF(PARAM_ERROR,
      size > static_cast<UInt64>(std::numeric_limits< ::size_t>::max()));

  FileImpl new_impl;
  new_impl.create_(path, size);
  new_impl.swap(this);
}

void FileImpl::open(const char *path) {
  GRN_DAT_THROW_IF(PARAM_ERROR, path == NULL);
  GRN_DAT_THROW_IF(PARAM_ERROR, path[0] == '\0');

  FileImpl new_impl;
  new_impl.open_(path);
  new_impl.swap(this);
}

void FileImpl::close() {
  FileImpl new_impl;
  new_impl.swap(this);
}

#ifdef WIN32

void FileImpl::swap(FileImpl *rhs) {
  std::swap(ptr_, rhs->ptr_);
  std::swap(size_, rhs->size_);
  std::swap(file_, rhs->file_);
  std::swap(map_, rhs->map_);
  std::swap(addr_, rhs->addr_);
}

void FileImpl::flush() {
  if (!addr_) {
    return;
  }

  BOOL succeeded = ::FlushViewOfFile(addr_, static_cast<SIZE_T>(size_));
  GRN_DAT_THROW_IF(IO_ERROR, !succeeded);

  SYSTEMTIME system_time;
  GetSystemTime(&system_time);
  FILETIME file_time;
  succeeded = SystemTimeToFileTime(&system_time, &file_time);
  GRN_DAT_THROW_IF(IO_ERROR, !succeeded);

  succeeded = SetFileTime(file_, NULL, NULL, &file_time);
  GRN_DAT_THROW_IF(IO_ERROR, !succeeded);
}

void FileImpl::create_(const char *path, UInt64 size) {
  if ((path != NULL) && (path[0] != '\0')) {
    file_ = ::CreateFileA(path, GRN_IO_FILE_CREATE_MODE,
                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                          NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    GRN_DAT_THROW_IF(IO_ERROR, file_ == INVALID_HANDLE_VALUE);

    const LONG size_low = static_cast<LONG>(size & 0xFFFFFFFFU);
    LONG size_high = static_cast<LONG>(size >> 32);
    const DWORD file_pos = ::SetFilePointer(file_, size_low, &size_high,
                                            FILE_BEGIN);
    GRN_DAT_THROW_IF(IO_ERROR, (file_pos == INVALID_SET_FILE_POINTER) &&
                               (::GetLastError() != 0));
    GRN_DAT_THROW_IF(IO_ERROR, ::SetEndOfFile(file_) == 0);

    map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE, 0, 0, NULL);
    GRN_DAT_THROW_IF(IO_ERROR, map_ == INVALID_HANDLE_VALUE);
  } else {
    const DWORD size_low = static_cast<DWORD>(size & 0xFFFFFFFFU);
    const DWORD size_high = static_cast<DWORD>(size >> 32);

    map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE,
                               size_high, size_low, NULL);
    GRN_DAT_THROW_IF(IO_ERROR, map_ == INVALID_HANDLE_VALUE);
  }

  addr_ = ::MapViewOfFile(map_, FILE_MAP_WRITE, 0, 0, 0);
  GRN_DAT_THROW_IF(IO_ERROR, addr_ == NULL);

  ptr_ = addr_;
  size_ = static_cast< ::size_t>(size);
}

void FileImpl::open_(const char *path) {
#ifdef _MSC_VER
  struct __stat64 st;
  GRN_DAT_THROW_IF(IO_ERROR, ::_stat64(path, &st) == -1);
#else  // _MSC_VER
  struct _stat st;
  GRN_DAT_THROW_IF(IO_ERROR, ::_stat(path, &st) == -1);
#endif  // _MSC_VER
  GRN_DAT_THROW_IF(IO_ERROR, st.st_size == 0);
  GRN_DAT_THROW_IF(IO_ERROR,
      static_cast<UInt64>(st.st_size) > std::numeric_limits< ::size_t>::max());

  file_ = ::CreateFileA(path, GRN_IO_FILE_CREATE_MODE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  GRN_DAT_THROW_IF(IO_ERROR, file_ == NULL);

  map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE, 0, 0, NULL);
  GRN_DAT_THROW_IF(IO_ERROR, map_ == NULL);

  addr_ = ::MapViewOfFile(map_, FILE_MAP_WRITE, 0, 0, 0);
  GRN_DAT_THROW_IF(IO_ERROR, addr_ == NULL);

  ptr_ = addr_;
  size_ = static_cast< ::size_t>(st.st_size);
}

#else  // WIN32

void FileImpl::swap(FileImpl *rhs) {
  std::swap(ptr_, rhs->ptr_);
  std::swap(size_, rhs->size_);
  std::swap(fd_, rhs->fd_);
  std::swap(addr_, rhs->addr_);
  std::swap(length_, rhs->length_);
}

void FileImpl::flush() {
  if (!addr_) {
    return;
  }

  int result = ::msync(addr_, length_, MS_SYNC);
  GRN_DAT_THROW_IF(IO_ERROR, result != 0);
}

void FileImpl::create_(const char *path, UInt64 size) {
  GRN_DAT_THROW_IF(PARAM_ERROR,
      size > static_cast<UInt64>(std::numeric_limits< ::off_t>::max()));

  if ((path != NULL) && (path[0] != '\0')) {
    fd_ = ::open(path, O_RDWR | O_CREAT | O_TRUNC, GRN_IO_FILE_CREATE_MODE);
    GRN_DAT_THROW_IF(IO_ERROR, fd_ == -1);

    const ::off_t file_size = static_cast< ::off_t>(size);
    GRN_DAT_THROW_IF(IO_ERROR, ::ftruncate(fd_, file_size) == -1);
  }

#ifdef MAP_ANONYMOUS
  const int flags = (fd_ == -1) ? (MAP_PRIVATE | MAP_ANONYMOUS) : MAP_SHARED;
#else  // MAP_ANONYMOUS
  const int flags = (fd_ == -1) ? (MAP_PRIVATE | MAP_ANON) : MAP_SHARED;
#endif  // MAP_ANONYMOUS

  length_ = static_cast< ::size_t>(size);
#ifdef USE_MAP_HUGETLB
  addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE,
                 flags | MAP_HUGETLB, fd_, 0);
#endif  // USE_MAP_HUGETLB
  if (addr_ == MAP_FAILED) {
    addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE, flags, fd_, 0);
    GRN_DAT_THROW_IF(IO_ERROR, addr_ == MAP_FAILED);
  }

  ptr_ = addr_;
  size_ = length_;
}

void FileImpl::open_(const char *path) {
  struct stat st;
  GRN_DAT_THROW_IF(IO_ERROR, ::stat(path, &st) == -1);
  GRN_DAT_THROW_IF(IO_ERROR, (st.st_mode & S_IFMT) != S_IFREG);
  GRN_DAT_THROW_IF(IO_ERROR, st.st_size == 0);
  GRN_DAT_THROW_IF(IO_ERROR,
      static_cast<UInt64>(st.st_size) > std::numeric_limits< ::size_t>::max());

  fd_ = ::open(path, O_RDWR);
  GRN_DAT_THROW_IF(IO_ERROR, fd_ == -1);

  length_ = static_cast<std::size_t>(st.st_size);
  addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
  GRN_DAT_THROW_IF(IO_ERROR, addr_ == MAP_FAILED);

  ptr_ = addr_;
  size_ = length_;
}

#endif  // WIN32

}  // namespace dat
}  // namespace grn
<|endoftext|>


<commit_before>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes
#include "libmesh_config.h"

#ifdef LIBMESH_HAVE_PETSC

// Local includes
#include "petsc_matrix.h"
#include "dof_map.h"
#include "dense_matrix.h"
#include "petsc_vector.h"

//-----------------------------------------------------------------------
// PetscMatrix members
template <typename T>
void PetscMatrix<T>::init (const unsigned int m,
			   const unsigned int n,
			   const unsigned int m_l,
			   const unsigned int n_l,
			   const unsigned int nnz,
			   const unsigned int noz)
{
  // We allow 0x0 matrices now
  //if ((m==0) || (n==0))
  //  return;

  // Clear initialized matrices
  if (this->initialized())
    this->clear();

  this->_is_initialized = true;

  int ierr     = 0;
  int m_global = static_cast<int>(m);
  int n_global = static_cast<int>(n);
  int m_local  = static_cast<int>(m_l);
  int n_local  = static_cast<int>(n_l);
  int n_nz     = static_cast<int>(nnz);
  int n_oz     = static_cast<int>(noz);

  // create a sequential matrix on one processor
  if (libMesh::n_processors() == 1)
    {
      libmesh_assert ((m_l == m) && (n_l == n));

      // Create matrix.  Revisit later to do preallocation and make more efficient
      ierr = MatCreateSeqAIJ (libMesh::COMM_WORLD, n_global, n_global,
			      n_nz, PETSC_NULL, &_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatSetFromOptions (_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  else
    {
      parallel_only();

      ierr = MatCreateMPIAIJ (libMesh::COMM_WORLD, m_local, n_local, m_global, n_global,
			      n_nz, PETSC_NULL, n_oz, PETSC_NULL, &_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatSetFromOptions (_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  this->zero ();
}

template <typename T>
void PetscMatrix<T>::init ()
{
  libmesh_assert (this->_dof_map != NULL);

  // Clear initialized matrices
  if (this->initialized())
    this->clear();

  this->_is_initialized = true;

  int proc_id = 0;

  MPI_Comm_rank (libMesh::COMM_WORLD, &proc_id);

  const unsigned int m   = this->_dof_map->n_dofs();
  const unsigned int n   = m;
  const unsigned int n_l = this->_dof_map->n_dofs_on_processor(proc_id);
  const unsigned int m_l = n_l;

  const std::vector<unsigned int>& n_nz = this->_dof_map->get_n_nz();
  const std::vector<unsigned int>& n_oz = this->_dof_map->get_n_oz();

  // Make sure the sparsity pattern isn't empty unless the matrix is 0x0
  libmesh_assert (n_nz.size() == n_l);
  libmesh_assert (n_oz.size() == n_l);

  // We allow 0x0 matrices now
  //if (m==0)
  //  return;

  int ierr     = 0;
  int m_global = static_cast<int>(m);
  int n_global = static_cast<int>(n);
  int m_local  = static_cast<int>(m_l);
  int n_local  = static_cast<int>(n_l);

  // create a sequential matrix on one processor
  if (libMesh::n_processors() == 1)
    {
      libmesh_assert ((m_l == m) && (n_l == n));
      if (n_nz.empty())
        ierr = MatCreateSeqAIJ (libMesh::COMM_WORLD, n_global, n_global,
			        PETSC_NULL, (int*) PETSC_NULL, &_mat);
      else
        ierr = MatCreateSeqAIJ (libMesh::COMM_WORLD, n_global, n_global,
			        PETSC_NULL, (int*) &n_nz[0], &_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatSetFromOptions (_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  else
    {
      parallel_only();

      if (n_nz.empty())
        ierr = MatCreateMPIAIJ (libMesh::COMM_WORLD,
			        m_local, n_local,
			        m_global, n_global,
			        PETSC_NULL, (int*) PETSC_NULL,
			        PETSC_NULL, (int*) PETSC_NULL, &_mat);
      else
        ierr = MatCreateMPIAIJ (libMesh::COMM_WORLD,
			        m_local, n_local,
			        m_global, n_global,
			        PETSC_NULL, (int*) &n_nz[0],
			        PETSC_NULL, (int*) &n_oz[0], &_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatSetFromOptions (_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  this->zero();
}

template <typename T>
void PetscMatrix<T>::zero ()
{
  libmesh_assert (this->initialized());

  semiparallel_only();

  int ierr=0;

  ierr = MatZeroEntries(_mat);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);
}

template <typename T>
void PetscMatrix<T>::zero_rows (std::vector<int> & rows, T diag_value)
{
  libmesh_assert (this->initialized());

  semiparallel_only();

  int ierr=0;

  if(!rows.empty())
    ierr = MatZeroRows(_mat, rows.size(), &rows[0], diag_value);
  else
    ierr = MatZeroRows(_mat, 0, PETSC_NULL, diag_value);

  CHKERRABORT(libMesh::COMM_WORLD,ierr);
}

template <typename T>
void PetscMatrix<T>::clear ()
{
  int ierr=0;

  if ((this->initialized()) && (this->_destroy_mat_on_exit))
    {
      semiparallel_only();

      ierr = MatDestroy (_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      this->_is_initialized = false;
    }
}

template <typename T>
Real PetscMatrix<T>::l1_norm () const
{
  libmesh_assert (this->initialized());

  semiparallel_only();

  int ierr=0;
  PetscReal petsc_value;
  Real value;

  libmesh_assert (this->closed());

  ierr = MatNorm(_mat, NORM_1, &petsc_value);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  value = static_cast<Real>(petsc_value);

  return value;
}

template <typename T>
Real PetscMatrix<T>::linfty_norm () const
{
  libmesh_assert (this->initialized());

  semiparallel_only();

  int ierr=0;
  PetscReal petsc_value;
  Real value;

  libmesh_assert (this->closed());

  ierr = MatNorm(_mat, NORM_INFINITY, &petsc_value);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  value = static_cast<Real>(petsc_value);

  return value;
}

template <typename T>
void PetscMatrix<T>::print_matlab (const std::string name) const
{
  libmesh_assert (this->initialized());

  semiparallel_only();

  // libmesh_assert (this->closed());
  this->close();

  int ierr=0;
  PetscViewer petsc_viewer;

  ierr = PetscViewerCreate (libMesh::COMM_WORLD,
			    &petsc_viewer);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  /**
   * Create an ASCII file containing the matrix
   * if a filename was provided.
   */
  if (name != "NULL")
    {
      ierr = PetscViewerASCIIOpen( libMesh::COMM_WORLD,
				   name.c_str(),
				   &petsc_viewer);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = PetscViewerSetFormat (petsc_viewer,
				   PETSC_VIEWER_ASCII_MATLAB);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatView (_mat, petsc_viewer);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  /**
   * Otherwise the matrix will be dumped to the screen.
   */
  else
    {
      ierr = PetscViewerSetFormat (PETSC_VIEWER_STDOUT_WORLD,
				   PETSC_VIEWER_ASCII_MATLAB);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatView (_mat, PETSC_VIEWER_STDOUT_WORLD);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  /**
   * Destroy the viewer.
   */
  ierr = PetscViewerDestroy (petsc_viewer);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);
}

template <typename T>
void PetscMatrix<T>::add_matrix(const DenseMatrix<T>& dm,
				const std::vector<unsigned int>& rows,
				const std::vector<unsigned int>& cols)
{
  libmesh_assert (this->initialized());

  const unsigned int m = dm.m();
  const unsigned int n = dm.n();

  libmesh_assert (rows.size() == m);
  libmesh_assert (cols.size() == n);

  int ierr=0;

  // These casts are required for PETSc <= 2.1.5
  ierr = MatSetValues(_mat,
		      m, (int*) &rows[0],
		      n, (int*) &cols[0],
		      (PetscScalar*) &dm.get_values()[0],
		      ADD_VALUES);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);
}

template <typename T>
void PetscMatrix<T>::_get_submatrix(SparseMatrix<T>& submatrix,
				    const std::vector<unsigned int> &rows,
				    const std::vector<unsigned int> &cols,
				    const bool reuse_submatrix) const
{
  // Can only extract submatrices from closed matrices
  this->close();

  // Make sure the SparseMatrix passed in is really a PetscMatrix
  PetscMatrix<T>* petsc_submatrix = libmesh_cast_ptr<PetscMatrix<T>*>(&submatrix);

  // If we're not reusing submatrix and submatrix is already initialized
  // then we need to clear it, otherwise we get a memory leak.
  if( !reuse_submatrix && submatrix.initialized() )
    submatrix.clear();

  // Construct row and column index sets.
  int ierr=0;
  IS isrow, iscol;

  ierr = ISCreateGeneral(libMesh::COMM_WORLD,
			 rows.size(),
			 (int*) &rows[0],
			 &isrow); CHKERRABORT(libMesh::COMM_WORLD,ierr);

  ierr = ISCreateGeneral(libMesh::COMM_WORLD,
			 cols.size(),
			 (int*) &cols[0],
			 &iscol); CHKERRABORT(libMesh::COMM_WORLD,ierr);

  // Extract submatrix
#if !PETSC_VERSION_LESS_THAN(3,0,1) || !PETSC_VERSION_RELEASE
  ierr = MatGetSubMatrix(_mat,
			 isrow,
			 iscol,
			 (reuse_submatrix ? MAT_REUSE_MATRIX : MAT_INITIAL_MATRIX),
			 &(petsc_submatrix->_mat));  CHKERRABORT(libMesh::COMM_WORLD,ierr);
#else
  ierr = MatGetSubMatrix(_mat,
			 isrow,
			 iscol,
			 PETSC_DECIDE,
			 (reuse_submatrix ? MAT_REUSE_MATRIX : MAT_INITIAL_MATRIX),
			 &(petsc_submatrix->_mat));  CHKERRABORT(libMesh::COMM_WORLD,ierr);
#endif

  // Specify that the new submatrix is initialized and close it.
  petsc_submatrix->_is_initialized = true;
  petsc_submatrix->close();

  // Clean up PETSc data structures
  ierr = ISDestroy(isrow); CHKERRABORT(libMesh::COMM_WORLD,ierr);
  ierr = ISDestroy(iscol); CHKERRABORT(libMesh::COMM_WORLD,ierr);
}

template <typename T>
void PetscMatrix<T>::get_diagonal (NumericVector<T>& dest) const
{
  // Make sure the NumericVector passed in is really a PetscVector
  PetscVector<T>& petsc_dest = libmesh_cast_ref<PetscVector<T>&>(dest);

  // Call PETSc function.

#if PETSC_VERSION_LESS_THAN(2,3,1)

  libMesh::out << "This method has been developed with PETSc 2.3.1.  "
	        << "No one has made it backwards compatible with older "
	        << "versions of PETSc so far; however, it might work "
	        << "without any change with some older version." << std::endl;
  libmesh_error();

#else

  // Needs a const_cast since PETSc does not work with const.
  int ierr =
    MatGetDiagonal(const_cast<PetscMatrix<T>*>(this)->mat(),petsc_dest.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr);

#endif

}

template <typename T>
void PetscMatrix<T>::get_transpose (SparseMatrix<T>& dest) const
{
  // Make sure the SparseMatrix passed in is really a PetscMatrix
  PetscMatrix<T>& petsc_dest = libmesh_cast_ref<PetscMatrix<T>&>(dest);

  // If we aren't reusing the matrix then need to clear dest,
  // otherwise we get a memory leak
  if(&petsc_dest != this)
    dest.clear();

  int ierr;
#if PETSC_VERSION_LESS_THAN(3,0,0)
  if (&petsc_dest == this)
    ierr = MatTranspose(_mat,PETSC_NULL);
  else
    ierr = MatTranspose(_mat,&petsc_dest._mat);
  CHKERRABORT(libMesh::COMM_WORLD,ierr);
#else
  // FIXME - we can probably use MAT_REUSE_MATRIX in more situations
  if (&petsc_dest == this)
    ierr = MatTranspose(_mat,MAT_REUSE_MATRIX,&petsc_dest._mat);
  else
    ierr = MatTranspose(_mat,MAT_INITIAL_MATRIX,&petsc_dest._mat);
  CHKERRABORT(libMesh::COMM_WORLD,ierr);
#endif

  // Specify that the transposed matrix is initialized and close it.
  petsc_dest._is_initialized = true;
  petsc_dest.close();
}

//------------------------------------------------------------------
// Explicit instantiations
template class PetscMatrix<Number>;

#endif // #ifdef LIBMESH_HAVE_PETSC
<commit_msg>Use libMesh::processor_id() for rank<commit_after>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes
#include "libmesh_config.h"

#ifdef LIBMESH_HAVE_PETSC

// Local includes
#include "petsc_matrix.h"
#include "dof_map.h"
#include "dense_matrix.h"
#include "petsc_vector.h"

//-----------------------------------------------------------------------
// PetscMatrix members
template <typename T>
void PetscMatrix<T>::init (const unsigned int m,
			   const unsigned int n,
			   const unsigned int m_l,
			   const unsigned int n_l,
			   const unsigned int nnz,
			   const unsigned int noz)
{
  // We allow 0x0 matrices now
  //if ((m==0) || (n==0))
  //  return;

  // Clear initialized matrices
  if (this->initialized())
    this->clear();

  this->_is_initialized = true;

  int ierr     = 0;
  int m_global = static_cast<int>(m);
  int n_global = static_cast<int>(n);
  int m_local  = static_cast<int>(m_l);
  int n_local  = static_cast<int>(n_l);
  int n_nz     = static_cast<int>(nnz);
  int n_oz     = static_cast<int>(noz);

  // create a sequential matrix on one processor
  if (libMesh::n_processors() == 1)
    {
      libmesh_assert ((m_l == m) && (n_l == n));

      // Create matrix.  Revisit later to do preallocation and make more efficient
      ierr = MatCreateSeqAIJ (libMesh::COMM_WORLD, n_global, n_global,
			      n_nz, PETSC_NULL, &_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatSetFromOptions (_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  else
    {
      parallel_only();

      ierr = MatCreateMPIAIJ (libMesh::COMM_WORLD, m_local, n_local, m_global, n_global,
			      n_nz, PETSC_NULL, n_oz, PETSC_NULL, &_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatSetFromOptions (_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  this->zero ();
}

template <typename T>
void PetscMatrix<T>::init ()
{
  libmesh_assert (this->_dof_map != NULL);

  // Clear initialized matrices
  if (this->initialized())
    this->clear();

  this->_is_initialized = true;

  const unsigned int m   = this->_dof_map->n_dofs();
  const unsigned int n   = m;
  const unsigned int n_l = this->_dof_map->n_dofs_on_processor(libMesh::processor_id());
  const unsigned int m_l = n_l;

  const std::vector<unsigned int>& n_nz = this->_dof_map->get_n_nz();
  const std::vector<unsigned int>& n_oz = this->_dof_map->get_n_oz();

  // Make sure the sparsity pattern isn't empty unless the matrix is 0x0
  libmesh_assert (n_nz.size() == n_l);
  libmesh_assert (n_oz.size() == n_l);

  // We allow 0x0 matrices now
  //if (m==0)
  //  return;

  int ierr     = 0;
  int m_global = static_cast<int>(m);
  int n_global = static_cast<int>(n);
  int m_local  = static_cast<int>(m_l);
  int n_local  = static_cast<int>(n_l);

  // create a sequential matrix on one processor
  if (libMesh::n_processors() == 1)
    {
      libmesh_assert ((m_l == m) && (n_l == n));
      if (n_nz.empty())
        ierr = MatCreateSeqAIJ (libMesh::COMM_WORLD, n_global, n_global,
			        PETSC_NULL, (int*) PETSC_NULL, &_mat);
      else
        ierr = MatCreateSeqAIJ (libMesh::COMM_WORLD, n_global, n_global,
			        PETSC_NULL, (int*) &n_nz[0], &_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatSetFromOptions (_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  else
    {
      parallel_only();

      if (n_nz.empty())
        ierr = MatCreateMPIAIJ (libMesh::COMM_WORLD,
			        m_local, n_local,
			        m_global, n_global,
			        PETSC_NULL, (int*) PETSC_NULL,
			        PETSC_NULL, (int*) PETSC_NULL, &_mat);
      else
        ierr = MatCreateMPIAIJ (libMesh::COMM_WORLD,
			        m_local, n_local,
			        m_global, n_global,
			        PETSC_NULL, (int*) &n_nz[0],
			        PETSC_NULL, (int*) &n_oz[0], &_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatSetFromOptions (_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  this->zero();
}

template <typename T>
void PetscMatrix<T>::zero ()
{
  libmesh_assert (this->initialized());

  semiparallel_only();

  int ierr=0;

  ierr = MatZeroEntries(_mat);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);
}

template <typename T>
void PetscMatrix<T>::zero_rows (std::vector<int> & rows, T diag_value)
{
  libmesh_assert (this->initialized());

  semiparallel_only();

  int ierr=0;

  if(!rows.empty())
    ierr = MatZeroRows(_mat, rows.size(), &rows[0], diag_value);
  else
    ierr = MatZeroRows(_mat, 0, PETSC_NULL, diag_value);

  CHKERRABORT(libMesh::COMM_WORLD,ierr);
}

template <typename T>
void PetscMatrix<T>::clear ()
{
  int ierr=0;

  if ((this->initialized()) && (this->_destroy_mat_on_exit))
    {
      semiparallel_only();

      ierr = MatDestroy (_mat);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      this->_is_initialized = false;
    }
}

template <typename T>
Real PetscMatrix<T>::l1_norm () const
{
  libmesh_assert (this->initialized());

  semiparallel_only();

  int ierr=0;
  PetscReal petsc_value;
  Real value;

  libmesh_assert (this->closed());

  ierr = MatNorm(_mat, NORM_1, &petsc_value);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  value = static_cast<Real>(petsc_value);

  return value;
}

template <typename T>
Real PetscMatrix<T>::linfty_norm () const
{
  libmesh_assert (this->initialized());

  semiparallel_only();

  int ierr=0;
  PetscReal petsc_value;
  Real value;

  libmesh_assert (this->closed());

  ierr = MatNorm(_mat, NORM_INFINITY, &petsc_value);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  value = static_cast<Real>(petsc_value);

  return value;
}

template <typename T>
void PetscMatrix<T>::print_matlab (const std::string name) const
{
  libmesh_assert (this->initialized());

  semiparallel_only();

  // libmesh_assert (this->closed());
  this->close();

  int ierr=0;
  PetscViewer petsc_viewer;

  ierr = PetscViewerCreate (libMesh::COMM_WORLD,
			    &petsc_viewer);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  /**
   * Create an ASCII file containing the matrix
   * if a filename was provided.
   */
  if (name != "NULL")
    {
      ierr = PetscViewerASCIIOpen( libMesh::COMM_WORLD,
				   name.c_str(),
				   &petsc_viewer);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = PetscViewerSetFormat (petsc_viewer,
				   PETSC_VIEWER_ASCII_MATLAB);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatView (_mat, petsc_viewer);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  /**
   * Otherwise the matrix will be dumped to the screen.
   */
  else
    {
      ierr = PetscViewerSetFormat (PETSC_VIEWER_STDOUT_WORLD,
				   PETSC_VIEWER_ASCII_MATLAB);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = MatView (_mat, PETSC_VIEWER_STDOUT_WORLD);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }

  /**
   * Destroy the viewer.
   */
  ierr = PetscViewerDestroy (petsc_viewer);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);
}

template <typename T>
void PetscMatrix<T>::add_matrix(const DenseMatrix<T>& dm,
				const std::vector<unsigned int>& rows,
				const std::vector<unsigned int>& cols)
{
  libmesh_assert (this->initialized());

  const unsigned int m = dm.m();
  const unsigned int n = dm.n();

  libmesh_assert (rows.size() == m);
  libmesh_assert (cols.size() == n);

  int ierr=0;

  // These casts are required for PETSc <= 2.1.5
  ierr = MatSetValues(_mat,
		      m, (int*) &rows[0],
		      n, (int*) &cols[0],
		      (PetscScalar*) &dm.get_values()[0],
		      ADD_VALUES);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);
}

template <typename T>
void PetscMatrix<T>::_get_submatrix(SparseMatrix<T>& submatrix,
				    const std::vector<unsigned int> &rows,
				    const std::vector<unsigned int> &cols,
				    const bool reuse_submatrix) const
{
  // Can only extract submatrices from closed matrices
  this->close();

  // Make sure the SparseMatrix passed in is really a PetscMatrix
  PetscMatrix<T>* petsc_submatrix = libmesh_cast_ptr<PetscMatrix<T>*>(&submatrix);

  // If we're not reusing submatrix and submatrix is already initialized
  // then we need to clear it, otherwise we get a memory leak.
  if( !reuse_submatrix && submatrix.initialized() )
    submatrix.clear();

  // Construct row and column index sets.
  int ierr=0;
  IS isrow, iscol;

  ierr = ISCreateGeneral(libMesh::COMM_WORLD,
			 rows.size(),
			 (int*) &rows[0],
			 &isrow); CHKERRABORT(libMesh::COMM_WORLD,ierr);

  ierr = ISCreateGeneral(libMesh::COMM_WORLD,
			 cols.size(),
			 (int*) &cols[0],
			 &iscol); CHKERRABORT(libMesh::COMM_WORLD,ierr);

  // Extract submatrix
#if !PETSC_VERSION_LESS_THAN(3,0,1) || !PETSC_VERSION_RELEASE
  ierr = MatGetSubMatrix(_mat,
			 isrow,
			 iscol,
			 (reuse_submatrix ? MAT_REUSE_MATRIX : MAT_INITIAL_MATRIX),
			 &(petsc_submatrix->_mat));  CHKERRABORT(libMesh::COMM_WORLD,ierr);
#else
  ierr = MatGetSubMatrix(_mat,
			 isrow,
			 iscol,
			 PETSC_DECIDE,
			 (reuse_submatrix ? MAT_REUSE_MATRIX : MAT_INITIAL_MATRIX),
			 &(petsc_submatrix->_mat));  CHKERRABORT(libMesh::COMM_WORLD,ierr);
#endif

  // Specify that the new submatrix is initialized and close it.
  petsc_submatrix->_is_initialized = true;
  petsc_submatrix->close();

  // Clean up PETSc data structures
  ierr = ISDestroy(isrow); CHKERRABORT(libMesh::COMM_WORLD,ierr);
  ierr = ISDestroy(iscol); CHKERRABORT(libMesh::COMM_WORLD,ierr);
}

template <typename T>
void PetscMatrix<T>::get_diagonal (NumericVector<T>& dest) const
{
  // Make sure the NumericVector passed in is really a PetscVector
  PetscVector<T>& petsc_dest = libmesh_cast_ref<PetscVector<T>&>(dest);

  // Call PETSc function.

#if PETSC_VERSION_LESS_THAN(2,3,1)

  libMesh::out << "This method has been developed with PETSc 2.3.1.  "
	        << "No one has made it backwards compatible with older "
	        << "versions of PETSc so far; however, it might work "
	        << "without any change with some older version." << std::endl;
  libmesh_error();

#else

  // Needs a const_cast since PETSc does not work with const.
  int ierr =
    MatGetDiagonal(const_cast<PetscMatrix<T>*>(this)->mat(),petsc_dest.vec()); CHKERRABORT(libMesh::COMM_WORLD,ierr);

#endif

}

template <typename T>
void PetscMatrix<T>::get_transpose (SparseMatrix<T>& dest) const
{
  // Make sure the SparseMatrix passed in is really a PetscMatrix
  PetscMatrix<T>& petsc_dest = libmesh_cast_ref<PetscMatrix<T>&>(dest);

  // If we aren't reusing the matrix then need to clear dest,
  // otherwise we get a memory leak
  if(&petsc_dest != this)
    dest.clear();

  int ierr;
#if PETSC_VERSION_LESS_THAN(3,0,0)
  if (&petsc_dest == this)
    ierr = MatTranspose(_mat,PETSC_NULL);
  else
    ierr = MatTranspose(_mat,&petsc_dest._mat);
  CHKERRABORT(libMesh::COMM_WORLD,ierr);
#else
  // FIXME - we can probably use MAT_REUSE_MATRIX in more situations
  if (&petsc_dest == this)
    ierr = MatTranspose(_mat,MAT_REUSE_MATRIX,&petsc_dest._mat);
  else
    ierr = MatTranspose(_mat,MAT_INITIAL_MATRIX,&petsc_dest._mat);
  CHKERRABORT(libMesh::COMM_WORLD,ierr);
#endif

  // Specify that the transposed matrix is initialized and close it.
  petsc_dest._is_initialized = true;
  petsc_dest.close();
}

//------------------------------------------------------------------
// Explicit instantiations
template class PetscMatrix<Number>;

#endif // #ifdef LIBMESH_HAVE_PETSC
<|endoftext|>


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

#include <iostream>
#include <pcl/io/ensenso_grabber.h>
#include <pcl/visualization/cloud_viewer.h>

using namespace std::chrono_literals;

/** @brief Convenience typedef */
typedef pcl::visualization::CloudViewer CloudViewer;

/** @brief Convenience typedef for XYZ point clouds */
typedef pcl::PointCloud<pcl::PointXYZ> PointCloudXYZ;

/** @brief CloudViewer pointer */
boost::shared_ptr<CloudViewer> viewer_ptr;

/** @brief PCL Ensenso object pointer */
pcl::EnsensoGrabber::Ptr ensenso_ptr;

/** @brief Process and/or display Ensenso grabber clouds
 * @param[in] cloud Ensenso cloud */
void
grabberCallback (const PointCloudXYZ::Ptr& cloud)
{
  if (!viewer_ptr->wasStopped ())
    viewer_ptr->showCloud (cloud);
}

/** @brief Main function
 * @return Exit status */
int
main (void)
{
  viewer_ptr.reset (new CloudViewer ("Ensenso 3D cloud viewer"));
  ensenso_ptr.reset (new pcl::EnsensoGrabber);
  ensenso_ptr->openTcpPort ();
  ensenso_ptr->openDevice ();

  boost::function<void
  (const PointCloudXYZ::Ptr&)> f = boost::bind (&grabberCallback, _1);
  ensenso_ptr->registerCallback (f);
  ensenso_ptr->start ();

  while (!viewer_ptr->wasStopped ())
  {
    std::this_thread::sleep_for(1s);
    std::cout << "FPS: " << ensenso_ptr->getFramesPerSecond () << std::endl;
  }

  ensenso_ptr->closeDevice ();
  return (0);
}

<commit_msg>Add missing includes in ensenso_viewer.cpp<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2014-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  Author: Victor Lamoine (victor.lamoine@gmail.com)
 */

#include <chrono>
#include <iostream>
#include <thread>

#include <pcl/io/ensenso_grabber.h>
#include <pcl/visualization/cloud_viewer.h>

using namespace std::chrono_literals;

/** @brief Convenience typedef */
typedef pcl::visualization::CloudViewer CloudViewer;

/** @brief Convenience typedef for XYZ point clouds */
typedef pcl::PointCloud<pcl::PointXYZ> PointCloudXYZ;

/** @brief CloudViewer pointer */
boost::shared_ptr<CloudViewer> viewer_ptr;

/** @brief PCL Ensenso object pointer */
pcl::EnsensoGrabber::Ptr ensenso_ptr;

/** @brief Process and/or display Ensenso grabber clouds
 * @param[in] cloud Ensenso cloud */
void
grabberCallback (const PointCloudXYZ::Ptr& cloud)
{
  if (!viewer_ptr->wasStopped ())
    viewer_ptr->showCloud (cloud);
}

/** @brief Main function
 * @return Exit status */
int
main (void)
{
  viewer_ptr.reset (new CloudViewer ("Ensenso 3D cloud viewer"));
  ensenso_ptr.reset (new pcl::EnsensoGrabber);
  ensenso_ptr->openTcpPort ();
  ensenso_ptr->openDevice ();

  boost::function<void
  (const PointCloudXYZ::Ptr&)> f = boost::bind (&grabberCallback, _1);
  ensenso_ptr->registerCallback (f);
  ensenso_ptr->start ();

  while (!viewer_ptr->wasStopped ())
  {
    std::this_thread::sleep_for(1s);
    std::cout << "FPS: " << ensenso_ptr->getFramesPerSecond () << std::endl;
  }

  ensenso_ptr->closeDevice ();
  return (0);
}

<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2014 Intel Corporation                                    //
//                                                                          //
// 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 <map>
#include "glutdisplay.h"
#include "sys/filename.h"
#include "lexers/streamfilters.h"
#include "lexers/parsestream.h"
#include "transport/transport_host.h"

/* include GLUT for display */
#if defined(__MACOSX__)
#  include <OpenGL/gl.h>
#  include <GLUT/glut.h>
#  include <ApplicationServices/ApplicationServices.h>
#elif defined(__WIN32__)
#  include <windows.h>
#  include <GL/gl.h>
#  include <GL/glut.h>
#else
#  include <GL/gl.h>
#  include <GL/glut.h>
#endif

float g_debug = 0.5f;

namespace embree
{
  static const double g_time0 = getSeconds();

  /* camera */
  Camera g_camera;

  /* output settings */
  static size_t g_width = 512;
  static size_t g_height = 512;
  static bool g_display = true;

  /* fullscreen settings */
  static bool g_fullscreen = false;
  static size_t g_window_width = 512;
  static size_t g_window_height = 512;

  /* ID of created window */
  static int g_window = 0;

  /*************************************************************************************************/
  /*                                  Keyboard control                                             */
  /*************************************************************************************************/

  typedef void (* KeyBinding)(unsigned char key, int x, int y);

  static float g_speed = 1.0f;
  static std::map<unsigned char, KeyBinding> keyBindings;

  void mapKeyToFunction(unsigned char key, KeyBinding binding)
  {
    keyBindings[key] = binding;
  }

  void keyboardFunc(unsigned char key, int x, int y)
  {

    if (keyBindings.find(key) != keyBindings.end()) { keyBindings[key](key, x, y);  return; }

    key_pressed(key);

    switch (key)
    {
    case 'f' :
      if (g_fullscreen) {
        g_fullscreen = false;
        glutReshapeWindow(g_window_width,g_window_height);
      } else {
        g_fullscreen = true;
        g_window_width = g_width;
        g_window_height = g_height;
        glutFullScreen();
      }
      break;
    case 'c' : {
      std::cout << "-vp " << g_camera.from.x    << " " << g_camera.from.y    << " " << g_camera.from.z    << " " << std::endl
                << "-vi " << g_camera.to.x << " " << g_camera.to.y << " " << g_camera.to.z << " " << std::endl
                << "-vu " << g_camera.up.x     << " " << g_camera.up.y     << " " << g_camera.up.z     << " " << std::endl
                << "-fov " << g_camera.fov << std::endl;
      break;
    }
    case 'a' : g_camera.rotate(-0.02f,0.0f); break;
    case 'd' : g_camera.rotate(+0.02f,0.0f); break;
    case 'w' : g_camera.move(0.0f,0.0f,+g_speed); break;
    case 's' : g_camera.move(0.0f,0.0f,-g_speed); break;
    case ' ' : g_display = !g_display; break;

    case '+' : g_debug=clamp(g_debug+0.01f); PRINT(g_debug); break;
    case '-' : g_debug=clamp(g_debug-0.01f); PRINT(g_debug); break;

    case '\033': case 'q': case 'Q':
      cleanup();
      glutDestroyWindow(g_window);
      exit(0);
      break;
    }
  }

  void specialFunc(int key, int, int)
  {
    key_pressed(key);

    switch (key) {
    case GLUT_KEY_LEFT      : g_camera.rotate(-0.02f,0.0f); break;
    case GLUT_KEY_RIGHT     : g_camera.rotate(+0.02f,0.0f); break;
    case GLUT_KEY_UP        : g_camera.move(0.0f,0.0f,+g_speed); break;
    case GLUT_KEY_DOWN      : g_camera.move(0.0f,0.0f,-g_speed); break;
    case GLUT_KEY_PAGE_UP   : g_speed *= 1.2f; break;
    case GLUT_KEY_PAGE_DOWN : g_speed /= 1.2f; break;
    }
  }

  /*************************************************************************************************/
  /*                                   Mouse control                                               */
  /*************************************************************************************************/

  static int mouseMode = 0;
  static int clickX = 0, clickY = 0;
  static bool flip14 = false;

  void clickFunc(int button, int state, int x, int y)
  {
    if (state == GLUT_UP)
    {
      mouseMode = 0;
      if (button == GLUT_LEFT_BUTTON && glutGetModifiers() == GLUT_ACTIVE_SHIFT)
      {
        AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);
        Vec3fa p; bool hit = pick(x,y, pixel2world.l.vx, pixel2world.l.vy, pixel2world.l.vz, pixel2world.p, p);

        if (hit) {
          Vec3fa delta = p - g_camera.to;
          Vec3fa right = normalize(pixel2world.l.vx);
          Vec3fa up    = normalize(pixel2world.l.vy);
          g_camera.to = p;
          g_camera.from += dot(delta,right)*right + dot(delta,up)*up;
        }
      }
      else if (button == GLUT_LEFT_BUTTON && glutGetModifiers() == (GLUT_ACTIVE_CTRL | GLUT_ACTIVE_SHIFT))
      {
        AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);
        Vec3fa p; bool hit = pick(x,y, pixel2world.l.vx, pixel2world.l.vy, pixel2world.l.vz, pixel2world.p, p);
        if (hit) g_camera.to = p;
      }

    } else {
      clickX = x; clickY = y;
      int modifiers = glutGetModifiers();
      if      (button == GLUT_LEFT_BUTTON && modifiers == GLUT_ACTIVE_SHIFT) mouseMode = 1;
      else if (button == GLUT_MIDDLE_BUTTON) mouseMode = 2;
      else if (button == GLUT_RIGHT_BUTTON ) mouseMode = 3;
      else if (button == GLUT_LEFT_BUTTON  ) mouseMode = 4;

      if (flip14) {
        if (mouseMode == 4) mouseMode = 1;
        else if (mouseMode == 1) mouseMode = 4;
      }
    }
  }

  void motionFunc(int x, int y)
  {
    float dClickX = float(clickX - x), dClickY = float(clickY - y);
    clickX = x; clickY = y;

    switch (mouseMode) {
    case 1: g_camera.rotateOrbit(-0.005f*dClickX,0.005f*dClickY); break;
    case 2: break;
    case 3: g_camera.dolly(-dClickY); break;
    case 4: g_camera.rotate(-0.005f*dClickX,0.005f*dClickY); break;
    }
  }

  /*************************************************************************************************/
  /*                                   Window control                                              */
  /*************************************************************************************************/

  void displayFunc(void)
  {
    AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);

    /* render image using ISPC */
    double t0 = getSeconds();
    render(g_time0-t0,
           pixel2world.l.vx,
           pixel2world.l.vy,
           pixel2world.l.vz,
           pixel2world.p);
    double dt0 = getSeconds()-t0;

    if (g_display)
    {
      /* draw pixels to screen */
      int* pixels = map();
      glRasterPos2i(-1, 1);
      glPixelZoom(1.0f, -1.0f);
      glDrawPixels(g_width,g_height,GL_RGBA,GL_UNSIGNED_BYTE,pixels);
      glutSwapBuffers();
      unmap();
    }
    double dt1 = getSeconds()-t0;

    /* print frame rate */
    std::ostringstream stream;
    stream.setf(std::ios::fixed, std::ios::floatfield);
    stream.precision(2);
    stream << "render: ";
    stream << 1.0f/dt0 << " fps, ";
    stream << dt0*1000.0f << " ms, ";
    stream << "display: ";
    stream << 1.0f/dt1 << " fps, ";
    stream << dt1*1000.0f << " ms, ";
    stream << g_width << "x" << g_height << " pixels";
    std::cout << stream.str() << std::endl;
  }

  void reshapeFunc(int width, int height)
  {
    resize(width,height);
    glViewport(0, 0, width, height);
    g_width = width; g_height = height;
  }

  void idleFunc()
  {
    glutPostRedisplay();
  }

  void enterWindowRunLoop()
  {
    glutMainLoop();
  }

  /* initialize GLUT */
  void initWindowState(int& argc, char** argv, const std::string name, const size_t width, const size_t height, const bool fullscreen, const bool mouseMode)
  {
    g_width = width;
    g_height = height;
    resize(g_width,g_height);

    g_fullscreen = fullscreen;
    flip14 = mouseMode;
    glutInit(&argc, argv);
    glutInitWindowSize((GLsizei)g_width, (GLsizei)g_height);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutInitWindowPosition(0, 0);
    g_window = glutCreateWindow(name.c_str());
    if (g_fullscreen) glutFullScreen();
    glutDisplayFunc(displayFunc);
    glutIdleFunc(idleFunc);
    glutKeyboardFunc(keyboardFunc);
    glutSpecialFunc(specialFunc);
    glutMouseFunc(clickFunc);
    glutMotionFunc(motionFunc);
    glutReshapeFunc(reshapeFunc);
  }

}

<commit_msg>flipping camera in tutorials instead of flipping image using OpenGL, resolves some weird OpenGL related crash on some machines<commit_after>// ======================================================================== //
// Copyright 2009-2014 Intel Corporation                                    //
//                                                                          //
// 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 <map>
#include "glutdisplay.h"
#include "sys/filename.h"
#include "lexers/streamfilters.h"
#include "lexers/parsestream.h"
#include "transport/transport_host.h"

/* include GLUT for display */
#if defined(__MACOSX__)
#  include <OpenGL/gl.h>
#  include <GLUT/glut.h>
#  include <ApplicationServices/ApplicationServices.h>
#elif defined(__WIN32__)
#  include <windows.h>
#  include <GL/gl.h>
#  include <GL/glut.h>
#else
#  include <GL/gl.h>
#  include <GL/glut.h>
#endif

float g_debug = 0.5f;

namespace embree
{
  static const double g_time0 = getSeconds();

  /* camera */
  Camera g_camera;

  /* output settings */
  static size_t g_width = 512;
  static size_t g_height = 512;
  static bool g_display = true;

  /* fullscreen settings */
  static bool g_fullscreen = false;
  static size_t g_window_width = 512;
  static size_t g_window_height = 512;

  /* ID of created window */
  static int g_window = 0;

  /*************************************************************************************************/
  /*                                  Keyboard control                                             */
  /*************************************************************************************************/

  typedef void (* KeyBinding)(unsigned char key, int x, int y);

  static float g_speed = 1.0f;
  static std::map<unsigned char, KeyBinding> keyBindings;

  void mapKeyToFunction(unsigned char key, KeyBinding binding)
  {
    keyBindings[key] = binding;
  }

  void keyboardFunc(unsigned char key, int x, int y)
  {

    if (keyBindings.find(key) != keyBindings.end()) { keyBindings[key](key, x, y);  return; }

    key_pressed(key);

    switch (key)
    {
    case 'f' :
      if (g_fullscreen) {
        g_fullscreen = false;
        glutReshapeWindow(g_window_width,g_window_height);
      } else {
        g_fullscreen = true;
        g_window_width = g_width;
        g_window_height = g_height;
        glutFullScreen();
      }
      break;
    case 'c' : {
      std::cout << "-vp " << g_camera.from.x    << " " << g_camera.from.y    << " " << g_camera.from.z    << " " << std::endl
                << "-vi " << g_camera.to.x << " " << g_camera.to.y << " " << g_camera.to.z << " " << std::endl
                << "-vu " << g_camera.up.x     << " " << g_camera.up.y     << " " << g_camera.up.z     << " " << std::endl
                << "-fov " << g_camera.fov << std::endl;
      break;
    }
    case 'a' : g_camera.rotate(-0.02f,0.0f); break;
    case 'd' : g_camera.rotate(+0.02f,0.0f); break;
    case 'w' : g_camera.move(0.0f,0.0f,+g_speed); break;
    case 's' : g_camera.move(0.0f,0.0f,-g_speed); break;
    case ' ' : g_display = !g_display; break;

    case '+' : g_debug=clamp(g_debug+0.01f); PRINT(g_debug); break;
    case '-' : g_debug=clamp(g_debug-0.01f); PRINT(g_debug); break;

    case '\033': case 'q': case 'Q':
      cleanup();
      glutDestroyWindow(g_window);
      exit(0);
      break;
    }
  }

  void specialFunc(int key, int, int)
  {
    key_pressed(key);

    switch (key) {
    case GLUT_KEY_LEFT      : g_camera.rotate(-0.02f,0.0f); break;
    case GLUT_KEY_RIGHT     : g_camera.rotate(+0.02f,0.0f); break;
    case GLUT_KEY_UP        : g_camera.move(0.0f,0.0f,+g_speed); break;
    case GLUT_KEY_DOWN      : g_camera.move(0.0f,0.0f,-g_speed); break;
    case GLUT_KEY_PAGE_UP   : g_speed *= 1.2f; break;
    case GLUT_KEY_PAGE_DOWN : g_speed /= 1.2f; break;
    }
  }

  /*************************************************************************************************/
  /*                                   Mouse control                                               */
  /*************************************************************************************************/

  static int mouseMode = 0;
  static int clickX = 0, clickY = 0;
  static bool flip14 = false;

  void clickFunc(int button, int state, int x, int y)
  {
    if (state == GLUT_UP)
    {
      mouseMode = 0;
      if (button == GLUT_LEFT_BUTTON && glutGetModifiers() == GLUT_ACTIVE_SHIFT)
      {
        AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);
        Vec3fa p; bool hit = pick(x,y, pixel2world.l.vx, pixel2world.l.vy, pixel2world.l.vz, pixel2world.p, p);

        if (hit) {
          Vec3fa delta = p - g_camera.to;
          Vec3fa right = normalize(pixel2world.l.vx);
          Vec3fa up    = normalize(pixel2world.l.vy);
          g_camera.to = p;
          g_camera.from += dot(delta,right)*right + dot(delta,up)*up;
        }
      }
      else if (button == GLUT_LEFT_BUTTON && glutGetModifiers() == (GLUT_ACTIVE_CTRL | GLUT_ACTIVE_SHIFT))
      {
        AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);
        Vec3fa p; bool hit = pick(x,y, pixel2world.l.vx, pixel2world.l.vy, pixel2world.l.vz, pixel2world.p, p);
        if (hit) g_camera.to = p;
      }

    } else {
      clickX = x; clickY = y;
      int modifiers = glutGetModifiers();
      if      (button == GLUT_LEFT_BUTTON && modifiers == GLUT_ACTIVE_SHIFT) mouseMode = 1;
      else if (button == GLUT_MIDDLE_BUTTON) mouseMode = 2;
      else if (button == GLUT_RIGHT_BUTTON ) mouseMode = 3;
      else if (button == GLUT_LEFT_BUTTON  ) mouseMode = 4;

      if (flip14) {
        if (mouseMode == 4) mouseMode = 1;
        else if (mouseMode == 1) mouseMode = 4;
      }
    }
  }

  void motionFunc(int x, int y)
  {
    float dClickX = float(clickX - x), dClickY = float(clickY - y);
    clickX = x; clickY = y;

    switch (mouseMode) {
    case 1: g_camera.rotateOrbit(-0.005f*dClickX,0.005f*dClickY); break;
    case 2: break;
    case 3: g_camera.dolly(-dClickY); break;
    case 4: g_camera.rotate(-0.005f*dClickX,0.005f*dClickY); break;
    }
  }

  /*************************************************************************************************/
  /*                                   Window control                                              */
  /*************************************************************************************************/

  void displayFunc(void)
  {
    AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);

    /* render image using ISPC */
    double t0 = getSeconds();
    render(g_time0-t0,
           pixel2world.l.vx,
           -pixel2world.l.vy,
           pixel2world.l.vz+g_height*pixel2world.l.vy,
           pixel2world.p);

    double dt0 = getSeconds()-t0;

    if (g_display)
    {
      /* draw pixels to screen */
      int* pixels = map();
      //glRasterPos2i(-1, 1);
      //glPixelZoom(1.0f, -1.0f);
      glDrawPixels(g_width,g_height,GL_RGBA,GL_UNSIGNED_BYTE,pixels);
      glutSwapBuffers();
      unmap();
    }
    double dt1 = getSeconds()-t0;

    /* print frame rate */
    std::ostringstream stream;
    stream.setf(std::ios::fixed, std::ios::floatfield);
    stream.precision(2);
    stream << "render: ";
    stream << 1.0f/dt0 << " fps, ";
    stream << dt0*1000.0f << " ms, ";
    stream << "display: ";
    stream << 1.0f/dt1 << " fps, ";
    stream << dt1*1000.0f << " ms, ";
    stream << g_width << "x" << g_height << " pixels";
    std::cout << stream.str() << std::endl;
  }

  void reshapeFunc(int width, int height)
  {
    resize(width,height);
    glViewport(0, 0, width, height);
    g_width = width; g_height = height;
  }

  void idleFunc()
  {
    glutPostRedisplay();
  }

  void enterWindowRunLoop()
  {
    glutMainLoop();
  }

  /* initialize GLUT */
  void initWindowState(int& argc, char** argv, const std::string name, const size_t width, const size_t height, const bool fullscreen, const bool mouseMode)
  {
    g_width = width;
    g_height = height;
    resize(g_width,g_height);

    g_fullscreen = fullscreen;
    flip14 = mouseMode;
    glutInit(&argc, argv);
    glutInitWindowSize((GLsizei)g_width, (GLsizei)g_height);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutInitWindowPosition(0, 0);
    g_window = glutCreateWindow(name.c_str());
    if (g_fullscreen) glutFullScreen();
    glutDisplayFunc(displayFunc);
    glutIdleFunc(idleFunc);
    glutKeyboardFunc(keyboardFunc);
    glutSpecialFunc(specialFunc);
    glutMouseFunc(clickFunc);
    glutMotionFunc(motionFunc);
    glutReshapeFunc(reshapeFunc);
  }

}

<|endoftext|>