<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, 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 Willow Garage, Inc. 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.
 *
 * $Id$
 *
 */

#ifndef PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_
#define PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_

#include <pcl/features/intensity_gradient.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void
pcl::IntensityGradientEstimation <PointInT, PointNT, PointOutT, IntensitySelectorT>::computePointIntensityGradient (
  const pcl::PointCloud <PointInT> &cloud, const std::vector <int> &indices,
  const Eigen::Vector3f &point, float mean_intensity, const Eigen::Vector3f &normal, Eigen::Vector3f &gradient)
{
  if (indices.size () < 3)
  {
    gradient[0] = gradient[1] = gradient[2] = std::numeric_limits<float>::quiet_NaN ();
    return;
  }

  Eigen::Matrix3f A = Eigen::Matrix3f::Zero ();
  Eigen::Vector3f b = Eigen::Vector3f::Zero ();

  for (size_t i_point = 0; i_point < indices.size (); ++i_point)
  {
    PointInT p = cloud.points[indices[i_point]];
    if (!pcl_isfinite (p.x) ||
        !pcl_isfinite (p.y) ||
        !pcl_isfinite (p.z) ||
        !pcl_isfinite (intensity_ (p)))
      continue;

    p.x -= point[0];
    p.y -= point[1];
    p.z -= point[2];
    intensity_.demean (p, mean_intensity);

    A (0, 0) += p.x * p.x;
    A (0, 1) += p.x * p.y;
    A (0, 2) += p.x * p.z;

    A (1, 1) += p.y * p.y;
    A (1, 2) += p.y * p.z;

    A (2, 2) += p.z * p.z;

    b[0] += p.x * intensity_ (p);
    b[1] += p.y * intensity_ (p);
    b[2] += p.z * intensity_ (p);
  }
  // Fill in the lower triangle of A
  A (1, 0) = A (0, 1);
  A (2, 0) = A (0, 2);
  A (2, 1) = A (1, 2);

//*
  Eigen::Vector3f x = A.colPivHouseholderQr ().solve (b);
/*/

  Eigen::Vector3f eigen_values;
  Eigen::Matrix3f eigen_vectors;
  eigen33 (A, eigen_vectors, eigen_values);

  b = eigen_vectors.transpose () * b;

  if ( eigen_values (0) != 0)
    b (0) /= eigen_values (0);
  else
    b (0) = 0;

  if ( eigen_values (1) != 0)
    b (1) /= eigen_values (1);
  else
    b (1) = 0;

  if ( eigen_values (2) != 0)
    b (2) /= eigen_values (2);
  else
    b (2) = 0;

  Eigen::Vector3f x = eigen_vectors * b;

//  if (A.col (0).squaredNorm () != 0)
//    x [0] /= A.col (0).squaredNorm ();
//  b -= x [0] * A.col (0);
//
//
//  if (A.col (1).squaredNorm ()  != 0)
//    x [1] /= A.col (1).squaredNorm ();
//  b -= x[1] * A.col (1);
//
//  x [2] = b.dot (A.col (2));
//  if (A.col (2).squaredNorm () != 0)
//    x[2] /= A.col (2).squaredNorm ();
  // Fit a hyperplane to the data

//*/
//  std::cout << A << "\n*\n" << bb << "\n=\n" << x << "\nvs.\n" << x2 << "\n\n";
//  std::cout << A * x << "\nvs.\n" << A * x2 << "\n\n------\n";
  // Project the gradient vector, x, onto the tangent plane
  gradient = (Eigen::Matrix3f::Identity () - normal*normal.transpose ()) * x;
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void
pcl::IntensityGradientEstimation<PointInT, PointNT, PointOutT, IntensitySelectorT>::computeFeature (PointCloudOut &output)
{
  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);
  output.is_dense = true;

#ifdef HAVE_OPENMP
#ifdef __APPLE__
#pragma omp parallel for schedule(static, threads_)
#else
#pragma omp parallel for shared (output) private (nn_indices, nn_dists) num_threads(threads_)
#endif
#endif
  // Iterating over the entire index vector
  for (int idx = 0; idx < static_cast<int> (indices_->size ()); ++idx)
  {
    PointOutT &p_out = output.points[idx];

    if (!this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists))
    {
      p_out.gradient[0] = p_out.gradient[1] = p_out.gradient[2] = std::numeric_limits<float>::quiet_NaN ();
      output.is_dense = false;
      continue;
    }

    Eigen::Vector3f centroid;
    float mean_intensity = 0;
    // Initialize to 0
    centroid.setZero ();
    // If the data is dense, we don't need to check for NaN
    if (surface_->is_dense)
    {
      for (size_t i = 0; i < nn_indices.size (); ++i)
      {
        centroid += surface_->points[nn_indices[i]].getVector3fMap ();
        mean_intensity += intensity_ (surface_->points[nn_indices[i]]);
      }
      centroid /= static_cast<float> (nn_indices.size ());
      mean_intensity /= static_cast<float> (nn_indices.size ());
    }
    // NaN or Inf values could exist => check for them
    else
    {
      unsigned cp = 0;
      for (size_t i = 0; i < nn_indices.size (); ++i)
      {
        // Check if the point is invalid
        if (!isFinite ((*surface_) [nn_indices[i]]))
          continue;

        centroid += surface_->points [nn_indices[i]].getVector3fMap ();
        mean_intensity += intensity_ (surface_->points [nn_indices[i]]);
        ++cp;
      }
      centroid /= static_cast<float> (cp);
      mean_intensity /= static_cast<float> (cp);
    }

    Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[(*indices_) [idx]].normal);
    Eigen::Vector3f gradient;
    computePointIntensityGradient (*surface_, nn_indices, centroid, mean_intensity, normal, gradient);

    p_out.gradient[0] = gradient[0];
    p_out.gradient[1] = gradient[1];
    p_out.gradient[2] = gradient[2];
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT> void
pcl::IntensityGradientEstimation<PointInT, PointNT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output)
{
  // Resize the output dataset
  output.points.resize (indices_->size (), 3);

  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);

  output.is_dense = true;
  // Iterating over the entire index vector
  for (size_t idx = 0; idx < indices_->size (); ++idx)
  {
    if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0)
    {
      output.points.row (idx).setConstant (std::numeric_limits<float>::quiet_NaN ());
      output.is_dense = false;
      continue;
    }

    Eigen::Vector4f centroid;
    compute3DCentroid (*surface_, nn_indices, centroid);

    float mean_intensity = 0;
    unsigned valid_neighbor_count = 0;
    for (size_t nIdx = 0; nIdx < nn_indices.size (); ++nIdx)
    {
      const PointInT& p = (*surface_)[nn_indices[nIdx]];
      if (!pcl_isfinite (p.intensity))
        continue;

      mean_intensity += p.intensity;
      ++valid_neighbor_count;
    }

    mean_intensity /= static_cast<float> (valid_neighbor_count);

    Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[idx].normal);
    Eigen::Vector3f gradient;
    this->computePointIntensityGradient (*surface_, nn_indices, centroid.head<3> (), mean_intensity, normal, gradient);

    output.points (idx, 0) = gradient[0];
    output.points (idx, 1) = gradient[1];
    output.points (idx, 2) = gradient[2];
  }
}

#define PCL_INSTANTIATE_IntensityGradientEstimation(InT,NT,OutT) template class PCL_EXPORTS pcl::IntensityGradientEstimation<InT,NT,OutT>;

#endif    // PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_
<commit_msg>Fix: if the cloud is not dense search for neighbours could raise an excpetion<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, 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 Willow Garage, Inc. 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.
 *
 * $Id$
 *
 */

#ifndef PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_
#define PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_

#include <pcl/features/intensity_gradient.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void
pcl::IntensityGradientEstimation <PointInT, PointNT, PointOutT, IntensitySelectorT>::computePointIntensityGradient (
  const pcl::PointCloud <PointInT> &cloud, const std::vector <int> &indices,
  const Eigen::Vector3f &point, float mean_intensity, const Eigen::Vector3f &normal, Eigen::Vector3f &gradient)
{
  if (indices.size () < 3)
  {
    gradient[0] = gradient[1] = gradient[2] = std::numeric_limits<float>::quiet_NaN ();
    return;
  }

  Eigen::Matrix3f A = Eigen::Matrix3f::Zero ();
  Eigen::Vector3f b = Eigen::Vector3f::Zero ();

  for (size_t i_point = 0; i_point < indices.size (); ++i_point)
  {
    PointInT p = cloud.points[indices[i_point]];
    if (!pcl_isfinite (p.x) ||
        !pcl_isfinite (p.y) ||
        !pcl_isfinite (p.z) ||
        !pcl_isfinite (intensity_ (p)))
      continue;

    p.x -= point[0];
    p.y -= point[1];
    p.z -= point[2];
    intensity_.demean (p, mean_intensity);

    A (0, 0) += p.x * p.x;
    A (0, 1) += p.x * p.y;
    A (0, 2) += p.x * p.z;

    A (1, 1) += p.y * p.y;
    A (1, 2) += p.y * p.z;

    A (2, 2) += p.z * p.z;

    b[0] += p.x * intensity_ (p);
    b[1] += p.y * intensity_ (p);
    b[2] += p.z * intensity_ (p);
  }
  // Fill in the lower triangle of A
  A (1, 0) = A (0, 1);
  A (2, 0) = A (0, 2);
  A (2, 1) = A (1, 2);

//*
  Eigen::Vector3f x = A.colPivHouseholderQr ().solve (b);
/*/

  Eigen::Vector3f eigen_values;
  Eigen::Matrix3f eigen_vectors;
  eigen33 (A, eigen_vectors, eigen_values);

  b = eigen_vectors.transpose () * b;

  if ( eigen_values (0) != 0)
    b (0) /= eigen_values (0);
  else
    b (0) = 0;

  if ( eigen_values (1) != 0)
    b (1) /= eigen_values (1);
  else
    b (1) = 0;

  if ( eigen_values (2) != 0)
    b (2) /= eigen_values (2);
  else
    b (2) = 0;

  Eigen::Vector3f x = eigen_vectors * b;

//  if (A.col (0).squaredNorm () != 0)
//    x [0] /= A.col (0).squaredNorm ();
//  b -= x [0] * A.col (0);
//
//
//  if (A.col (1).squaredNorm ()  != 0)
//    x [1] /= A.col (1).squaredNorm ();
//  b -= x[1] * A.col (1);
//
//  x [2] = b.dot (A.col (2));
//  if (A.col (2).squaredNorm () != 0)
//    x[2] /= A.col (2).squaredNorm ();
  // Fit a hyperplane to the data

//*/
//  std::cout << A << "\n*\n" << bb << "\n=\n" << x << "\nvs.\n" << x2 << "\n\n";
//  std::cout << A * x << "\nvs.\n" << A * x2 << "\n\n------\n";
  // Project the gradient vector, x, onto the tangent plane
  gradient = (Eigen::Matrix3f::Identity () - normal*normal.transpose ()) * x;
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void
pcl::IntensityGradientEstimation<PointInT, PointNT, PointOutT, IntensitySelectorT>::computeFeature (PointCloudOut &output)
{
  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);
  output.is_dense = true;

  // If the data is dense, we don't need to check for NaN
  if (surface_->is_dense)
  {
#if defined (HAVE_OPENMP) && (defined(_WIN32) || ((__GNUC__ > 4) && (__GNUC_MINOR__ > 2)))
#pragma omp parallel for shared (output) private (nn_indices, nn_dists) num_threads(threads_)
#endif
    // Iterating over the entire index vector
    for (int idx = 0; idx < static_cast<int> (indices_->size ()); ++idx)
    {
      PointOutT &p_out = output.points[idx];

      if (!this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists))
      {
        p_out.gradient[0] = p_out.gradient[1] = p_out.gradient[2] = std::numeric_limits<float>::quiet_NaN ();
        output.is_dense = false;
        continue;
      }

      Eigen::Vector3f centroid;
      float mean_intensity = 0;
      // Initialize to 0
      centroid.setZero ();
      for (size_t i = 0; i < nn_indices.size (); ++i)
      {
        centroid += surface_->points[nn_indices[i]].getVector3fMap ();
        mean_intensity += intensity_ (surface_->points[nn_indices[i]]);
      }
      centroid /= static_cast<float> (nn_indices.size ());
      mean_intensity /= static_cast<float> (nn_indices.size ());

      Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[(*indices_) [idx]].normal);
      Eigen::Vector3f gradient;
      computePointIntensityGradient (*surface_, nn_indices, centroid, mean_intensity, normal, gradient);

      p_out.gradient[0] = gradient[0];
      p_out.gradient[1] = gradient[1];
      p_out.gradient[2] = gradient[2];
    }
  }
  else
  {
#if defined (HAVE_OPENMP) && (defined(_WIN32) || ((__GNUC__ > 4) && (__GNUC_MINOR__ > 2)))
#pragma omp parallel for shared (output) private (nn_indices, nn_dists) num_threads(threads_)
#endif
    // Iterating over the entire index vector
    for (int idx = 0; idx < static_cast<int> (indices_->size ()); ++idx)
    {
      PointOutT &p_out = output.points[idx];
      if (!isFinite ((*surface_) [(*indices_)[idx]]) ||
          !this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists))
      {
        p_out.gradient[0] = p_out.gradient[1] = p_out.gradient[2] = std::numeric_limits<float>::quiet_NaN ();
        output.is_dense = false;
        continue;
      }
      Eigen::Vector3f centroid;
      float mean_intensity = 0;
      // Initialize to 0
      centroid.setZero ();
      unsigned cp = 0;
      for (size_t i = 0; i < nn_indices.size (); ++i)
      {
        // Check if the point is invalid
        if (!isFinite ((*surface_) [nn_indices[i]]))
          continue;

        centroid += surface_->points [nn_indices[i]].getVector3fMap ();
        mean_intensity += intensity_ (surface_->points [nn_indices[i]]);
        ++cp;
      }
      centroid /= static_cast<float> (cp);
      mean_intensity /= static_cast<float> (cp);
      Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[(*indices_) [idx]].normal);
      Eigen::Vector3f gradient;
      computePointIntensityGradient (*surface_, nn_indices, centroid, mean_intensity, normal, gradient);

      p_out.gradient[0] = gradient[0];
      p_out.gradient[1] = gradient[1];
      p_out.gradient[2] = gradient[2];
    }
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT> void
pcl::IntensityGradientEstimation<PointInT, PointNT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output)
{
  // Resize the output dataset
  output.points.resize (indices_->size (), 3);

  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);

  output.is_dense = true;
  // Iterating over the entire index vector
  for (size_t idx = 0; idx < indices_->size (); ++idx)
  {
    if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0)
    {
      output.points.row (idx).setConstant (std::numeric_limits<float>::quiet_NaN ());
      output.is_dense = false;
      continue;
    }

    Eigen::Vector4f centroid;
    compute3DCentroid (*surface_, nn_indices, centroid);

    float mean_intensity = 0;
    unsigned valid_neighbor_count = 0;
    for (size_t nIdx = 0; nIdx < nn_indices.size (); ++nIdx)
    {
      const PointInT& p = (*surface_)[nn_indices[nIdx]];
      if (!pcl_isfinite (p.intensity))
        continue;

      mean_intensity += p.intensity;
      ++valid_neighbor_count;
    }

    mean_intensity /= static_cast<float> (valid_neighbor_count);

    Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[idx].normal);
    Eigen::Vector3f gradient;
    this->computePointIntensityGradient (*surface_, nn_indices, centroid.head<3> (), mean_intensity, normal, gradient);

    output.points (idx, 0) = gradient[0];
    output.points (idx, 1) = gradient[1];
    output.points (idx, 2) = gradient[2];
  }
}

#define PCL_INSTANTIATE_IntensityGradientEstimation(InT,NT,OutT) template class PCL_EXPORTS pcl::IntensityGradientEstimation<InT,NT,OutT>;

#endif    // PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#include "murmur3_partitioner.hh"
#include "utils/murmur_hash.hh"
#include "sstables/key.hh"
#include "utils/class_registrator.hh"

namespace dht {

inline
int64_t
murmur3_partitioner::normalize(int64_t in) {
    return in == std::numeric_limits<int64_t>::lowest()
            ? std::numeric_limits<int64_t>::max()
            : in;
}

token
murmur3_partitioner::get_token(bytes_view key) {
    if (key.empty()) {
        return minimum_token();
    }
    std::array<uint64_t, 2> hash;
    utils::murmur_hash::hash3_x64_128(key, 0, hash);
    return get_token(hash[0]);
}

token
murmur3_partitioner::get_token(uint64_t value) const {
    // We don't normalize() the value, since token includes an is-before-everything
    // indicator.
    // FIXME: will this require a repair when importing a database?
    auto t = net::hton(normalize(value));
    bytes b(bytes::initialized_later(), 8);
    std::copy_n(reinterpret_cast<int8_t*>(&t), 8, b.begin());
    return token{token::kind::key, std::move(b)};
}

token
murmur3_partitioner::get_token(const sstables::key_view& key) {
    return get_token(bytes_view(key));
}

token
murmur3_partitioner::get_token(const schema& s, partition_key_view key) {
    std::array<uint64_t, 2> hash;
    auto&& legacy = key.legacy_form(s);
    utils::murmur_hash::hash3_x64_128(legacy.begin(), legacy.size(), 0, hash);
    return get_token(hash[0]);
}

token murmur3_partitioner::get_random_token() {
    auto rand = dht::get_random_number<uint64_t>();
    return get_token(rand);
}

inline long long_token(const token& t) {

    if (t._data.size() != sizeof(long)) {
        throw runtime_exception(sprint("Invalid token. Should have size %ld, has size %ld\n", sizeof(long), t._data.size()));
    }

    auto ptr = t._data.begin();
    auto lp = unaligned_cast<const long *>(ptr);
    return net::ntoh(*lp);
}

sstring murmur3_partitioner::to_sstring(const token& t) const {
    return ::to_sstring(long_token(t));
}

int murmur3_partitioner::tri_compare(const token& t1, const token& t2) {
    long l1 = long_token(t1);
    long l2 = long_token(t2);

    if (l1 == l2) {
        return 0;
    } else {
        return l1 < l2 ? -1 : 1;
    }
}

token murmur3_partitioner::midpoint(const token& t1, const token& t2) const {
    auto l1 = long_token(t1);
    auto l2 = long_token(t2);
    // long_token is defined as signed, but the arithmetic works out the same
    // without invoking undefined behavior with a signed type.
    auto delta = (uint64_t(l2) - uint64_t(l1)) / 2;
    if (l1 > l2) {
        // wraparound
        delta += 0x8000'0000'0000'0000;
    }
    auto mid = uint64_t(l1) + delta;
    return get_token(mid);
}

std::map<token, float>
murmur3_partitioner::describe_ownership(const std::vector<token>& sorted_tokens) {
    abort();
}

data_type
murmur3_partitioner::get_token_validator() {
    return long_type;
}

unsigned
murmur3_partitioner::shard_of(const token& t) const {
    int64_t l = long_token(t);
    // treat l as a fraction between 0 and 1 and use 128-bit arithmetic to
    // divide that range evenly among shards:
    uint64_t adjusted = uint64_t(l) + uint64_t(std::numeric_limits<int64_t>::min());
    return (__int128(adjusted) * smp::count) >> 64;
}

using registry = class_registrator<i_partitioner, murmur3_partitioner>;
static registry registrator("org.apache.cassandra.dht.Murmur3Partitioner");
static registry registrator_short_name("Murmur3Partitioner");

}

<commit_msg>murmur3 partitioner: explicitly use int64_t instead of long<commit_after>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#include "murmur3_partitioner.hh"
#include "utils/murmur_hash.hh"
#include "sstables/key.hh"
#include "utils/class_registrator.hh"

namespace dht {

inline
int64_t
murmur3_partitioner::normalize(int64_t in) {
    return in == std::numeric_limits<int64_t>::lowest()
            ? std::numeric_limits<int64_t>::max()
            : in;
}

token
murmur3_partitioner::get_token(bytes_view key) {
    if (key.empty()) {
        return minimum_token();
    }
    std::array<uint64_t, 2> hash;
    utils::murmur_hash::hash3_x64_128(key, 0, hash);
    return get_token(hash[0]);
}

token
murmur3_partitioner::get_token(uint64_t value) const {
    // We don't normalize() the value, since token includes an is-before-everything
    // indicator.
    // FIXME: will this require a repair when importing a database?
    auto t = net::hton(normalize(value));
    bytes b(bytes::initialized_later(), 8);
    std::copy_n(reinterpret_cast<int8_t*>(&t), 8, b.begin());
    return token{token::kind::key, std::move(b)};
}

token
murmur3_partitioner::get_token(const sstables::key_view& key) {
    return get_token(bytes_view(key));
}

token
murmur3_partitioner::get_token(const schema& s, partition_key_view key) {
    std::array<uint64_t, 2> hash;
    auto&& legacy = key.legacy_form(s);
    utils::murmur_hash::hash3_x64_128(legacy.begin(), legacy.size(), 0, hash);
    return get_token(hash[0]);
}

token murmur3_partitioner::get_random_token() {
    auto rand = dht::get_random_number<uint64_t>();
    return get_token(rand);
}

inline int64_t long_token(const token& t) {

    if (t._data.size() != sizeof(int64_t)) {
        throw runtime_exception(sprint("Invalid token. Should have size %ld, has size %ld\n", sizeof(int64_t), t._data.size()));
    }

    auto ptr = t._data.begin();
    auto lp = unaligned_cast<const int64_t *>(ptr);
    return net::ntoh(*lp);
}

sstring murmur3_partitioner::to_sstring(const token& t) const {
    return ::to_sstring(long_token(t));
}

int murmur3_partitioner::tri_compare(const token& t1, const token& t2) {
    auto l1 = long_token(t1);
    auto l2 = long_token(t2);

    if (l1 == l2) {
        return 0;
    } else {
        return l1 < l2 ? -1 : 1;
    }
}

token murmur3_partitioner::midpoint(const token& t1, const token& t2) const {
    auto l1 = long_token(t1);
    auto l2 = long_token(t2);
    // long_token is defined as signed, but the arithmetic works out the same
    // without invoking undefined behavior with a signed type.
    auto delta = (uint64_t(l2) - uint64_t(l1)) / 2;
    if (l1 > l2) {
        // wraparound
        delta += 0x8000'0000'0000'0000;
    }
    auto mid = uint64_t(l1) + delta;
    return get_token(mid);
}

std::map<token, float>
murmur3_partitioner::describe_ownership(const std::vector<token>& sorted_tokens) {
    abort();
}

data_type
murmur3_partitioner::get_token_validator() {
    return long_type;
}

unsigned
murmur3_partitioner::shard_of(const token& t) const {
    int64_t l = long_token(t);
    // treat l as a fraction between 0 and 1 and use 128-bit arithmetic to
    // divide that range evenly among shards:
    uint64_t adjusted = uint64_t(l) + uint64_t(std::numeric_limits<int64_t>::min());
    return (__int128(adjusted) * smp::count) >> 64;
}

using registry = class_registrator<i_partitioner, murmur3_partitioner>;
static registry registrator("org.apache.cassandra.dht.Murmur3Partitioner");
static registry registrator_short_name("Murmur3Partitioner");

}

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <queue>
#include <iomanip>
#include <algorithm>
#include "job.h"

using namespace std;

void insertProcesses(vector<Job>& processes, vector<int>& ids, vector<int>& bursts, int size);
void FCFS(vector<Job> Jobs, int size);
void roundRobin(vector<Job>& original, int size);
bool sortJobs(Job job1, Job job2); //needed to sort for SJF
void SJF(vector<Job> Jobs, int size);

int main()
{
  string filename;

  cout << "Please Enter the name of the file you wish to read: ";
  cin >> filename;

  string text;
  ifstream infile(filename);
  vector<int> ids;
  vector<int> bursts;
  vector<Job> processes;

  if(infile.is_open())
	{
	while(infile.good())
	  {
		while(getline(infile, text))
		  {
			//Inserts before comma to ids vector and after to burst comma
			ids.push_back(stoi(text.substr(0,text.find(","))));
			bursts.push_back(stoi(text.substr(text.find(",") +1)));
		  }
	  }
	//total number of jobs
	int size = ids.size();

	//creates Job object vector to store information of both jobs and bursts
	insertProcesses(processes, ids, bursts, size);

	// First come First Server
	FCFS(processes, size);

	//Round Robin
	roundRobin(processes, size);

	//Shortest Job First
	SJF(processes, size);

	}
  //When a file can't be found
  else
	{
	  cerr << "Error Opening File" << endl;
	}
  infile.close();
  return 0;
}

void insertProcesses(vector<Job>& processes, vector<int>& ids, vector<int>& bursts, int size)
{
  for(int i = 0; i < size; i++)
	{
	  Job newJob(ids[i],bursts[i]);
	  processes.push_back(newJob);
	}
}

void FCFS(vector<Job> Jobs, int size) {
  Job *RRProcesses = new Job[size];
  queue<Job> jobQ;
  // copy jobs into a new array to not mutate existing array
  for(int i = 0; i < size; i++)
	{
	  RRProcesses[i] = Jobs[i];
	}
  //Queue up
  for(int i = 0; i < size; i++)
	{
	  jobQ.push(RRProcesses[i]);
	}
  Job* curJob;

  int totalTime = 0;
  int waitTime = 0;
  int totalWait;
  while(!jobQ.empty()) {
  	curJob = &jobQ.front(); //Always pull from front of queue with FCFS
  	totalTime += curJob->getBurst();
  	curJob->setTurnAround(totalTime);
  	totalWait += curJob->getWait(); // used for calculating average later
  	jobQ.pop();
  }

  cout << setprecision(3) << fixed << showpoint;
  double throughPut = 60/((double)totalTime/(double)size);
  cout << setw(30) << right << "FIRST COME FIRST SERVE" << endl;
  cout << "Total processing time: " << totalTime << " seconds." << endl;
  cout << "Average turn around time for Jobs: " << totalTime / size << endl;
  cout << "Overall throughput: " <<  throughPut <<  " processes per minute" << endl;
  cout << "Average wait time: " << totalWait / size << endl;
}

void roundRobin(vector<Job>& original, int size)
{
  Job *RRProcesses = new Job[size];
  queue<Job> jobQ;
  int timeQuantum = 1; //By default it's 1 from the assignment, but it can  be changed
  Job* ptr;  //Queue Pointer
  int n = 0; //Process Counter (Can also be considere total burst time).
  int m = 0; //Time Quantum Counter
  int remainingBurst; //round robin subtracts bursts
  int started[size + 1];//+1 because the job IDs start at 1 (if it starts at 0, we just have an extra box
  int totalTurnAround = 0; //Should count all the turnArounds for average and other uses.

  cout << setw(30) << right << "ROUND ROBIN" << endl;
  cout << "Enter a Time Quantum: ";
  cin >> timeQuantum;

  //Copy original vector so it doesn't get modified
  for(int i = 0; i < size; i++)
	{
	  RRProcesses[i] = original[i];
	}

  //Queue up
  for(int i = 0; i < size; i++)
	{
	  jobQ.push(RRProcesses[i]);
	}
  while(!jobQ.empty())
	{
	  m = 0; //reset
	  ptr = &jobQ.front();

	  //Used to decrease burst until m=timeQuantum and increments n to track time passed
	  while(m <= timeQuantum && ptr->getBurst() > 0)
		{
		  remainingBurst = ptr->getBurst();
		  ptr->setBurst(remainingBurst - 1);
		  m++;
		  n++;
		}

	  //if there's still burst time left
	  if(ptr->getBurst() > 0)
	  	{
	  	  jobQ.pop();
	  	  jobQ.push(*ptr);
	  	}
	  //when process hits 0 burst time
	  else
	  	{
	  	  //cout <<"P" << ptr->getID() << " ended on time " << n << endl;
		  ptr->setEndTime(n);
		  int turnA = ptr->getEndTime();
		  ptr->setTurnAround(turnA);
		  totalTurnAround += ptr->getTurnAround();
	  	  jobQ.pop();
	  	}

	}

  //output
  cout << setprecision(3) << fixed << showpoint;
  double throughPut = 60/((double)n/(double)size);
  cout << "Total processing time: " << n << endl;
  cout << "Average TurnAround Time: " << totalTurnAround/size << endl;
  cout << "Overall throughput: "  << throughPut << endl;
  cout << "Average Wait Time: " << (totalTurnAround - n)/size << endl;
}

bool sortJobs(Job job1, Job job2) {
  return (job1.getBurst() < job2.getBurst()); // Only swap if shorter, keeps sort stable.
}

void SJF(vector<Job> Jobs, int size) {
  Job *RRProcesses = new Job[size];
  queue<Job> jobQ;

  RRProcesses[0] = Jobs[0]; // First process will always run first in SJF rega \
  rdless of burst

	std::vector<Job> newJobsVector(Jobs);
  std::sort(newJobsVector.begin()+1, newJobsVector.end(), sortJobs); // Assume \
  all jobs come in at the same time

	for(int i = 1; i < size; i++)
	  {
		RRProcesses[i] = newJobsVector[i];
	  }
  //Queue up
  for(int i = 0; i < size; i++)
	{
	  jobQ.push(RRProcesses[i]);
	}

  Job* curJob;

  int totalTime = 0;
  int totalWait = 0;
  while(!jobQ.empty()) {
  	curJob = &jobQ.front(); // Now that the queue is sorted by length, we can do the shortest job first by pulling from the front of the queue.
  	totalTime += curJob->getBurst(); // Set time spent equal to the burst
  	curJob->setTurnAround(totalTime);
  	totalWait += curJob->getWait();
  	jobQ.pop();
  }

  cout << setprecision(3) << fixed << showpoint;
  double throughPut = 60/((double)totalTime/(double)size);
  cout << setw(30) << right << "SHORTEST JOB FIRST" << endl;
  cout << "Total processing time: " << totalTime << " seconds." << endl;
  cout << "Average wait time for Jobs: " << totalWait / size << endl;
  cout << "Average turn around time for Jobs: " << totalTime / size << endl;
  cout << "Overall throughput: " <<  throughPut  <<  " processes per minute" <<  endl;
}
<commit_msg>Changed all outputs to doubles<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <queue>
#include <iomanip>
#include <algorithm>
#include "job.h"

using namespace std;

void insertProcesses(vector<Job>& processes, vector<int>& ids, vector<int>& bursts, int size);
void FCFS(vector<Job> Jobs, int size);
void roundRobin(vector<Job>& original, int size);
bool sortJobs(Job job1, Job job2); //needed to sort for SJF
void SJF(vector<Job> Jobs, int size);

int main()
{
  string filename;

  cout << "Please Enter the name of the file you wish to read: ";
  cin >> filename;

  string text;
  ifstream infile(filename);
  vector<int> ids;
  vector<int> bursts;
  vector<Job> processes;

  if(infile.is_open())
	{
	while(infile.good())
	  {
		while(getline(infile, text))
		  {
			//Inserts before comma to ids vector and after to burst comma
			ids.push_back(stoi(text.substr(0,text.find(","))));
			bursts.push_back(stoi(text.substr(text.find(",") +1)));
		  }
	  }
	//total number of jobs
	int size = ids.size();

	//creates Job object vector to store information of both jobs and bursts
	insertProcesses(processes, ids, bursts, size);

	// First come First Server
	FCFS(processes, size);

	//Round Robin
	roundRobin(processes, size);

	//Shortest Job First
	SJF(processes, size);

	}
  //When a file can't be found
  else
	{
	  cerr << "Error Opening File" << endl;
	}
  infile.close();
  return 0;
}

void insertProcesses(vector<Job>& processes, vector<int>& ids, vector<int>& bursts, int size)
{
  for(int i = 0; i < size; i++)
	{
	  Job newJob(ids[i],bursts[i]);
	  processes.push_back(newJob);
	}
}

void FCFS(vector<Job> Jobs, int size) {
  Job *RRProcesses = new Job[size];
  queue<Job> jobQ;
  // copy jobs into a new array to not mutate existing array
  for(int i = 0; i < size; i++)
	{
	  RRProcesses[i] = Jobs[i];
	}
  //Queue up
  for(int i = 0; i < size; i++)
	{
	  jobQ.push(RRProcesses[i]);
	}
  Job* curJob;

  int totalTime = 0;
  int waitTime = 0;
  int totalWait;
  while(!jobQ.empty()) {
  	curJob = &jobQ.front(); //Always pull from front of queue with FCFS
  	totalTime += curJob->getBurst();
  	curJob->setTurnAround(totalTime);
  	totalWait += curJob->getWait(); // used for calculating average later
  	jobQ.pop();
  }

  cout << setprecision(3) << fixed << showpoint;
  double throughPut = 60/((double)totalTime/(double)size);
  double avgTurnAround = (double)totalTime/(double)size;
  double avgWait = (double)totalWait/(double)size;;
  cout << setw(30) << right << "FIRST COME FIRST SERVE" << endl;
  cout << "Total processing time: " << totalTime << " seconds." << endl;
  cout << "Average turn around time for Jobs: " << avgTurnAround << endl;
  cout << "Overall throughput: " <<  throughPut <<  " processes per minute" << endl;
  cout << "Average wait time: " << avgWait << endl;
}

void roundRobin(vector<Job>& original, int size)
{
  Job *RRProcesses = new Job[size];
  queue<Job> jobQ;
  int timeQuantum = 1; //By default it's 1 from the assignment, but it can  be changed
  Job* ptr;  //Queue Pointer
  int n = 0; //Process Counter (Can also be considere total burst time).
  int m = 0; //Time Quantum Counter
  int remainingBurst; //round robin subtracts bursts
  int started[size + 1];//+1 because the job IDs start at 1 (if it starts at 0, we just have an extra box
  int totalTurnAround = 0; //Should count all the turnArounds for average and other uses.

  cout << setw(30) << right << "ROUND ROBIN" << endl;
  cout << "Enter a Time Quantum: ";
  cin >> timeQuantum;

  //Copy original vector so it doesn't get modified
  for(int i = 0; i < size; i++)
	{
	  RRProcesses[i] = original[i];
	}

  //Queue up
  for(int i = 0; i < size; i++)
	{
	  jobQ.push(RRProcesses[i]);
	}
  while(!jobQ.empty())
	{
	  m = 0; //reset
	  ptr = &jobQ.front();

	  //Used to decrease burst until m=timeQuantum and increments n to track time passed
	  while(m <= timeQuantum && ptr->getBurst() > 0)
		{
		  remainingBurst = ptr->getBurst();
		  ptr->setBurst(remainingBurst - 1);
		  m++;
		  n++;
		}

	  //if there's still burst time left
	  if(ptr->getBurst() > 0)
	  	{
	  	  jobQ.pop();
	  	  jobQ.push(*ptr);
	  	}
	  //when process hits 0 burst time
	  else
	  	{
	  	  //cout <<"P" << ptr->getID() << " ended on time " << n << endl;
		  ptr->setEndTime(n);
		  int turnA = ptr->getEndTime();
		  ptr->setTurnAround(turnA);
		  totalTurnAround += ptr->getTurnAround();
	  	  jobQ.pop();
	  	}

	}

  //output
  cout << setprecision(3) << fixed << showpoint;
  double throughPut = 60/((double)n/(double)size);
  double avgTurnAround = (double)totalTurnAround/(double)size;
  double avgWait = ((double)totalTurnAround - (double)n)/(double)size;

  cout << "Total processing time: " << n << endl;
  cout << "Average turn around time for Jobs: " << avgTurnAround << endl;
  cout << "Overall throughput: "  << throughPut << endl;
  cout << "Average wait time: " << avgWait << endl;
}

bool sortJobs(Job job1, Job job2) {
  return (job1.getBurst() < job2.getBurst()); // Only swap if shorter, keeps sort stable.
}

void SJF(vector<Job> Jobs, int size) {
  Job *RRProcesses = new Job[size];
  queue<Job> jobQ;

  RRProcesses[0] = Jobs[0]; // First process will always run first in SJF rega \
  rdless of burst

	std::vector<Job> newJobsVector(Jobs);
  std::sort(newJobsVector.begin()+1, newJobsVector.end(), sortJobs); // Assume \
  all jobs come in at the same time

	for(int i = 1; i < size; i++)
	  {
		RRProcesses[i] = newJobsVector[i];
	  }
  //Queue up
  for(int i = 0; i < size; i++)
	{
	  jobQ.push(RRProcesses[i]);
	}

  Job* curJob;

  int totalTime = 0;
  int totalWait = 0;
  while(!jobQ.empty()) {
  	curJob = &jobQ.front(); // Now that the queue is sorted by length, we can do the shortest job first by pulling from the front of the queue.
  	totalTime += curJob->getBurst(); // Set time spent equal to the burst
  	curJob->setTurnAround(totalTime);
  	totalWait += curJob->getWait();
  	jobQ.pop();
  }

  cout << setprecision(3) << fixed << showpoint;
  double throughPut = 60/((double)totalTime/(double)size);
  double avgTurnAround =(double)totalTime/(double)size;
  double avgWait = (double)totalWait/(double)size;
  cout << setw(30) << right << "SHORTEST JOB FIRST" << endl;
  cout << "Total processing time: " << totalTime << " seconds." << endl;
  cout << "Average turn around time for Jobs: " << totalTime / size << endl;
  cout << "Overall throughput: " <<  throughPut  <<  " processes per minute" <<  endl;
  cout << "Average wait time for Jobs: " << totalWait / size << endl;
}
<|endoftext|>


<commit_before>#define ALL
#ifdef ALL
#include <iostream>

#include <n/core/Timer.h>

#include <n/math/Plane.h>
#include <n/io/File.h>

#include <SDL2/SDL.h>
#include <n/graphics/ImageLoader.h>
#include <n/graphics/GLContext.h>
#include <n/graphics/Texture.h>
#include <n/graphics/Scene.h>
#include <n/graphics/GL.h>
#include <n/graphics/StaticBuffer.h>
#include <n/graphics/TriangleBuffer.h>
#include <n/graphics/VertexArrayObject.h>
#include <n/graphics/ShaderCombinaison.h>
#include <n/graphics/Camera.h>
#include <n/graphics/StaticMesh.h>
#include <n/graphics/Material.h>
#include <n/graphics/MeshLoader.h>
#include <n/graphics/MaterialLoader.h>

#include <n/math/StaticConvexVolume.h>
#include <n/math/ConvexVolume.h>

using namespace n;
using namespace n::graphics;
using namespace n::math;
using namespace n::core;

SDL_Window *createWindow() {
	SDL_Window *mainWindow = 0;
	if(SDL_Init(SDL_INIT_VIDEO) < 0) {
		fatal("Unable to initialize SDL");
	}
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	if(!(mainWindow = SDL_CreateWindow("n 2.1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN))) {
		fatal("Unable to create window");
	}
	SDL_GL_CreateContext(mainWindow);
	SDL_GL_SetSwapInterval(0);

	GLContext::getContext();

	return mainWindow;
}

bool run(SDL_Window *mainWindow) {
	SDL_GL_SwapWindow(mainWindow);
	SDL_Event e;
	bool cc = true;
	while(SDL_PollEvent(&e)) {
		if(e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)) {
			cc = false;
			break;
		}
	}
	return cc;
}

class Obj : public StaticMesh
{
	public:
		Obj(String n) : StaticMesh(MeshLoader::load<String>(n)), model(n) {
			axis = ((Vec3(random(), random(), random()) - 0.5) * 2).normalized();
		}

		virtual void render(RenderQueue &qu) override {
			static Timer timer;
			static double x = 0;
			double t = timer.reset();
			x += t * 0.5;
			Quaternion<> q = Quaternion<>::fromAxisAngle(axis.cross(Vec3(1, 0, 0)).cross(axis), t);
			axis = q(axis);
			setRotation(Quaternion<>::fromAxisAngle(axis, x));
			if(!getMeshInstance().isValid()) {
				fatal("Unable to load mesh");
			}
			StaticMesh::render(qu);
		}

	private:
		String model;
		Vec3 axis;
};

int main(int, char **) {
	SDL_Window *win = createWindow();

	Shader<VertexShader> vert("#version 420 core\n"
										"layout(location = 0) in vec3 n_VertexPosition;"
										"layout(location = 1) in vec3 n_VertexNormal;"
										"layout(location = 2) in vec3 n_VertexTangent;"
										"uniform mat4 n_ViewProjectionMatrix;"
										"uniform mat4 n_ModelMatrix;"
										"uniform vec3 n_Camera;"

										"out vec3 N;"
										"out vec3 V;"
										"out vec3 T;"
										"out vec3 B;"

										"void main() {"
											"vec4 model = n_ModelMatrix * vec4(n_VertexPosition, 1.0);"
											"gl_Position = n_ViewProjectionMatrix * model;"

											"V = normalize(n_Camera - model.xyz);"
											"N = mat3(n_ModelMatrix) * n_VertexNormal;"
											"T = mat3(n_ModelMatrix) * n_VertexTangent;"
											"B = cross(N, T);"
										"}");

	io::File glsl("shader");
	if(!glsl.open(io::IODevice::Read)) {
		fatal("Unable to open shader");
	}
	char *brdfc = new char[glsl.size() + 1];
	brdfc[glsl.readBytes(brdfc)] = 0;
	String brdf(brdfc);
	delete[] brdfc;
	glsl.close();

	String fragStr = "#version 420 core\n"
					 "#define PI 3.14159265358979323846\n"
					 "layout(location = 0) out vec4 n_FragColor;"
					 "uniform vec4 n_Color;"
					 "uniform float n_Roughness;"
					 "uniform float n_Metallic;"
					 "in vec3 N;"
					 "in vec3 V;"
					 "in vec3 T;"
					 "in vec3 B;"

					 + brdf +

					"void main() {"
						"vec3 C = n_Color.rgb;"
						"vec3 L = normalize(vec3(0.5, 0.5, 1.0));"
						"vec3 NN = normalize(N);"
						"n_FragColor = vec4((d_BRDF(C, L, V, NN) + s_BRDF(C, L, V, NN)), n_Color.a);"
					"}";

	Shader<FragmentShader> frag(fragStr);

	ShaderCombinaison shader(&frag, &vert, 0);
	if(!shader.isValid()) {
		std::cerr<<shader.getLogs()<<std::endl;
		std::cerr<<frag.getLogs()<<std::endl;
		std::cerr<<vert.getLogs()<<std::endl;
		fatal("Unable to compile shader.");
	}

	shader.bind();

	Camera cam;
	cam.setPosition(Vec3(0, 0, 5));
	shader["n_Camera"] = cam.getPosition();
	cam.setRotation(Quaternion<>::fromEuler(0, toRad(90), 0));

	GLContext::getContext()->setProjectionMatrix(cam.getProjectionMatrix());
	GLContext::getContext()->setViewMatrix(cam.getViewMatrix());
	Scene scene;

	auto c = new Obj("scube.obj");
	c->setPosition(Vec3(0, 2.5, 0));
	scene.insert(c);
	c = new Obj("sphere.obj");
	c->setPosition(Vec3(0, 0, 0));
	scene.insert(c);
	c = new Obj("scube.obj");
	c->setPosition(Vec3(0, -2.5, 0));
	scene.insert(c);

	Timer timer;
	while(run(win)) {
		gl::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		core::Array<StaticMesh *> meshes = scene.query<StaticMesh>(cam);
		RenderQueue queue;
		for(Renderable *m : meshes) {
			m->render(queue);
		}
		for(const auto &q : queue.getBatches()) {
			q();
		}
		GLContext::getContext()->processTasks();
		if(GLContext::checkGLError()) {
			fatal("GL error");
		}
		//shader["n_Roughness"] = (1 + sin(timer.elapsed()));
		gl::glFlush();
	}
	return 0;
}

#else

#include <n/core/Array.h>

int main(int, char **) {
	return 0;
}

#endif

<commit_msg>Limited framerate somewat<commit_after>#define ALL
#ifdef ALL
#include <iostream>

#include <n/core/Timer.h>

#include <n/math/Plane.h>
#include <n/io/File.h>

#include <SDL2/SDL.h>
#include <n/graphics/ImageLoader.h>
#include <n/graphics/GLContext.h>
#include <n/graphics/Texture.h>
#include <n/graphics/Scene.h>
#include <n/graphics/GL.h>
#include <n/graphics/StaticBuffer.h>
#include <n/graphics/TriangleBuffer.h>
#include <n/graphics/VertexArrayObject.h>
#include <n/graphics/ShaderCombinaison.h>
#include <n/graphics/Camera.h>
#include <n/graphics/StaticMesh.h>
#include <n/graphics/Material.h>
#include <n/graphics/MeshLoader.h>
#include <n/graphics/MaterialLoader.h>

#include <n/math/StaticConvexVolume.h>
#include <n/math/ConvexVolume.h>

using namespace n;
using namespace n::graphics;
using namespace n::math;
using namespace n::core;

SDL_Window *createWindow() {
	SDL_Window *mainWindow = 0;
	if(SDL_Init(SDL_INIT_VIDEO) < 0) {
		fatal("Unable to initialize SDL");
	}
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	if(!(mainWindow = SDL_CreateWindow("n 2.1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN))) {
		fatal("Unable to create window");
	}
	SDL_GL_CreateContext(mainWindow);
	SDL_GL_SetSwapInterval(0);

	GLContext::getContext();

	return mainWindow;
}

bool run(SDL_Window *mainWindow) {
	SDL_GL_SwapWindow(mainWindow);
	SDL_Event e;
	bool cc = true;
	while(SDL_PollEvent(&e)) {
		if(e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)) {
			cc = false;
			break;
		}
	}
	return cc;
}

class Obj : public StaticMesh
{
	public:
		Obj(String n) : StaticMesh(MeshLoader::load<String>(n)), model(n) {
			axis = ((Vec3(random(), random(), random()) - 0.5) * 2).normalized();
		}

		virtual void render(RenderQueue &qu) override {
			static Timer timer;
			static double x = 0;
			double t = timer.reset();
			x += t * 0.5;
			Quaternion<> q = Quaternion<>::fromAxisAngle(axis.cross(Vec3(1, 0, 0)).cross(axis), t);
			axis = q(axis);
			setRotation(Quaternion<>::fromAxisAngle(axis, x));
			if(!getMeshInstance().isValid()) {
				fatal("Unable to load mesh");
			}
			StaticMesh::render(qu);
		}

	private:
		String model;
		Vec3 axis;
};

int main(int, char **) {
	SDL_Window *win = createWindow();

	Shader<VertexShader> vert("#version 420 core\n"
										"layout(location = 0) in vec3 n_VertexPosition;"
										"layout(location = 1) in vec3 n_VertexNormal;"
										"layout(location = 2) in vec3 n_VertexTangent;"
										"uniform mat4 n_ViewProjectionMatrix;"
										"uniform mat4 n_ModelMatrix;"
										"uniform vec3 n_Camera;"

										"out vec3 N;"
										"out vec3 V;"
										"out vec3 T;"
										"out vec3 B;"

										"void main() {"
											"vec4 model = n_ModelMatrix * vec4(n_VertexPosition, 1.0);"
											"gl_Position = n_ViewProjectionMatrix * model;"

											"V = normalize(n_Camera - model.xyz);"
											"N = mat3(n_ModelMatrix) * n_VertexNormal;"
											"T = mat3(n_ModelMatrix) * n_VertexTangent;"
											"B = cross(N, T);"
										"}");

	io::File glsl("shader");
	if(!glsl.open(io::IODevice::Read)) {
		fatal("Unable to open shader");
	}
	char *brdfc = new char[glsl.size() + 1];
	brdfc[glsl.readBytes(brdfc)] = 0;
	String brdf(brdfc);
	delete[] brdfc;
	glsl.close();

	String fragStr = "#version 420 core\n"
					 "#define PI 3.14159265358979323846\n"
					 "layout(location = 0) out vec4 n_FragColor;"
					 "uniform vec4 n_Color;"
					 "uniform float n_Roughness;"
					 "uniform float n_Metallic;"
					 "in vec3 N;"
					 "in vec3 V;"
					 "in vec3 T;"
					 "in vec3 B;"

					 + brdf +

					"void main() {"
						"vec3 C = n_Color.rgb;"
						"vec3 L = normalize(vec3(0.5, 0.5, 1.0));"
						"vec3 NN = normalize(N);"
						"n_FragColor = vec4((d_BRDF(C, L, V, NN) + s_BRDF(C, L, V, NN)), n_Color.a);"
					"}";

	Shader<FragmentShader> frag(fragStr);

	ShaderCombinaison shader(&frag, &vert, 0);
	if(!shader.isValid()) {
		std::cerr<<shader.getLogs()<<std::endl;
		std::cerr<<frag.getLogs()<<std::endl;
		std::cerr<<vert.getLogs()<<std::endl;
		fatal("Unable to compile shader.");
	}

	shader.bind();

	Camera cam;
	cam.setPosition(Vec3(0, 0, 5));
	shader["n_Camera"] = cam.getPosition();
	cam.setRotation(Quaternion<>::fromEuler(0, toRad(90), 0));

	GLContext::getContext()->setProjectionMatrix(cam.getProjectionMatrix());
	GLContext::getContext()->setViewMatrix(cam.getViewMatrix());
	Scene scene;

	auto c = new Obj("scube.obj");
	c->setPosition(Vec3(0, 2.5, 0));
	scene.insert(c);
	c = new Obj("sphere.obj");
	c->setPosition(Vec3(0, 0, 0));
	scene.insert(c);
	c = new Obj("scube.obj");
	c->setPosition(Vec3(0, -2.5, 0));
	scene.insert(c);

	Timer timer;
	while(run(win)) {
		gl::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		core::Array<StaticMesh *> meshes = scene.query<StaticMesh>(cam);
		RenderQueue queue;
		for(Renderable *m : meshes) {
			m->render(queue);
		}
		for(const auto &q : queue.getBatches()) {
			q();
		}
		GLContext::getContext()->processTasks();
		if(GLContext::checkGLError()) {
			fatal("GL error");
		}
		concurent::Thread::sleep(0.01);
		gl::glFlush();
	}
	return 0;
}

#else

#include <n/core/Array.h>

int main(int, char **) {
	return 0;
}

#endif

<|endoftext|>


<commit_before>6e6c42bd-ad58-11e7-91e1-ac87a332f658<commit_msg>I am finally done<commit_after>6ece8f4f-ad58-11e7-9658-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
//#include <vector>
//#include <fstream>

using namespace std;

int main()
{
    //game start
    cout << " -----------------------------" << endl
         << "|     Plants v.s Zombies      |" << endl
         << " -----------------------------" << endl;
    constexpr int LAND_DEFAULT=8;
    constexpr int LAND_MAX=10;
    constexpr int LAND_MIN=1;
    constexpr int ZOMBIE_DEFAULT=3;
    constexpr int ZOMBIE_MAX=10;
    constexpr int ZOMBIE_MIN=1;

    string input;
    //initialize game setting
    cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
    int value = LAND_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > LAND_MAX) value = LAND_MAX;
        if(value < LAND_MIN) value = LAND_MIN;
    }
    const int LANDS=value;

    cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
    value=ZOMBIE_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
        if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
    }
    const int ZOMBIES=value;

    //game rules
    cout << "=============================================================================" << endl
         << "Plants vs. Zombies Rule:" << endl
         << endl
         << "How to win:" << endl
         << "  (1) All zombies are dead." << endl
         << "  (2) At least one plant is live." << endl
         << "  (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
         << endl
         << "How to lose:" << endl
         << "  All plants are dead." << endl
         << "=============================================================================" << endl;
    system("pause");
    system("cls");

    //game start
    /*
    //construct
    Player *player = new Player();
    Zombie *zombie = new Zombie()[ZOMBIES];
    Land *land = new Land()[LANDS];
    Map *map = new Map(land);
    vector<Plant*> plant;
    ifstream fin=open("plants.txt");
    while(!fin.eof())
    {
        char type;
        fin << type;
        if(fin.eof()) break;
        Plant *tmp = nullptr;
        switch(type)
        {
        case 'C':
            {
                tmp = new CoinPlant(fin);
            }
        case 'S':
            {
                tmp = new HornPlant(fin);
            }
        case 'B':
            {
                tmp = new BombPlant(fin);
            }
        case 'H':
            {
                tmp = new HealPlant(fin);
            }
        default:
            continue;
        }
        if(tmp)
        {
            plant.push_back(tmp);
        }
    }

    cout << *map << endl;
    cout << "------------------------------------------------" << endl;
    cout << "Zombie information:" << endl;
    for(int i=0;i<ZOMBIES;i++)
    {
        cout << '[' << i << "] " << zombie[i];
    }
    cout << endl << "================================================" << endl;
    for(int i=0;i<plant.size();++i)
    {
        cout << '[' << i << "] " ;
        switch(plant[i]->type())
        {
            case 'C':
                cout << dynamic_cast<CoinPlant *>(plant[i]);
            case 'S':
                cout << dynamic_cast<HornPlant *>(plant[i]);
            case 'B':
                cout << dynamic_cast<BombPlant *>(plant[i]);
            case 'H':
                cout << dynamic_cast<HealPlant *>(plant[i]);
        }
        cout << endl;
    }
    cout << endl << *player;
    int choice = plant.size();
    cout << ":    Enter your choice (" << choice << " to give up, default: " << choice << ")...>";

    // destruct
    while(!plant.empty())
        delete plant.pop_back();
    delete player;
    delete map;
    delete [] zombie;
    delete [] land;
    */

    return 0;
}
<commit_msg>preset which need to convert type<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
//#include <vector>
//#include <fstream>

using namespace std;

int main()
{
    //game start
    cout << " -----------------------------" << endl
         << "|     Plants v.s Zombies      |" << endl
         << " -----------------------------" << endl;
    constexpr int LAND_DEFAULT=8;
    constexpr int LAND_MAX=10;
    constexpr int LAND_MIN=1;
    constexpr int ZOMBIE_DEFAULT=3;
    constexpr int ZOMBIE_MAX=10;
    constexpr int ZOMBIE_MIN=1;

    string input;
    //initialize game setting
    cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
    int value = LAND_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > LAND_MAX) value = LAND_MAX;
        if(value < LAND_MIN) value = LAND_MIN;
    }
    const int LANDS=value;

    cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
    value=ZOMBIE_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
        if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
    }
    const int ZOMBIES=value;

    //game rules
    cout << "=============================================================================" << endl
         << "Plants vs. Zombies Rule:" << endl
         << endl
         << "How to win:" << endl
         << "  (1) All zombies are dead." << endl
         << "  (2) At least one plant is live." << endl
         << "  (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
         << endl
         << "How to lose:" << endl
         << "  All plants are dead." << endl
         << "=============================================================================" << endl;
    system("pause");
    system("cls");

    //game start
    /*
    //construct
    Player *player = new Player();
    Zombie *zombie = new Zombie()[ZOMBIES];
    Land *land = new Land()[LANDS];
    Map *map = new Map(land);
    vector<Plant*> plant;
    ifstream fin=open("plants.txt");
    while(!fin.eof())
    {
        char type;
        fin << type;
        if(fin.eof()) break;
        Plant *tmp = nullptr;
        switch(type)
        {
        case 'C':
            {
                tmp = new CoinPlant(fin);
            }
        case 'S':
            {
                tmp = new HornPlant(fin);
            }
        case 'B':
            {
                tmp = new BombPlant(fin);
            }
        case 'H':
            {
                tmp = new HealPlant(fin);
            }
        default:
            continue;
        }
        if(tmp)
        {
            plant.push_back(tmp);
        }
    }

    cout << *map << endl;
    cout << "------------------------------------------------" << endl;
    cout << "Zombie information:" << endl;
    for(int i=0;i<ZOMBIES;i++)
    {
        cout << '[' << i << "] " << zombie[i];
    }
    cout << endl << "================================================" << endl;
    for(int i=0;i<plant.size();++i)
    {
        cout << '[' << i << "] " ;
        switch(plant[i]->type())
        {
            case 'C':
                cout << dynamic_cast<CoinPlant *>(plant[i]);
            case 'S':
                cout << dynamic_cast<HornPlant *>(plant[i]);
            case 'B':
                cout << dynamic_cast<BombPlant *>(plant[i]);
            case 'H':
                cout << dynamic_cast<HealPlant *>(plant[i]);
        }
        cout << endl;
    }
    cout << endl << *player;
    int choice = plant.size();
    cout << ":    Enter your choice (" << choice << " to give up, default: " << choice << ")...>";

    switch(plant[choice].type())
    {
    case 'C':
        land->plant(CoinPlant(*dynamic_cast<CoinPlant *>(plant[choice])));
    case 'S':
        land->plant(HornPlant(*dynamic_cast<CoinPlant *>(plant[choice])));
    case 'B':
        land->plant(BombPlant(*dynamic_cast<CoinPlant *>(plant[choice])));
    case 'H':
        land->plant(HealPlant(*dynamic_cast<CoinPlant *>(plant[choice])))
    }

    // destruct
    while(!plant.empty())
        delete plant.pop_back();
    delete player;
    delete map;
    delete [] zombie;
    delete [] land;
    */

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

//Thomas' Prototypes

//Hannah's Prototypes

int atomic_distance (int distance); //Kate's Prototype: defines atomic distance as integer

int (main)
{
using nedit file...
create new input "hannah's test changes"
}

<commit_msg>Update to Kate's First Function Prototype<commit_after>#include <iostream>

//Thomas' Prototypes

//Hannah's Prototypes

int atomic_distance (int x, int y, int z); //Kate's Prototype: defines atomic distance as combination of x, y, z coordinates

int (main)
{
using nedit file...
create new input "hannah's test changes"
}

<|endoftext|>


<commit_before>/*
 * Website:
 *      https://github.com/wo3kie/dojo
 *
 * Author:
 *      Lukasz Czerwinski
 *
 * Compilation:
 *      g++ --std=c++11 tuple.cpp -o tuple
 *
 * Usage:
 *      $ ./tuple
 */

#include <iostream>

template<typename Arg, typename ... Args>
struct Tuple
{
	Tuple(){
	}

	Tuple(Arg arg, Args... args)
		: head_(arg)
		, tail_(args...)
	{
	}

	Arg head_;
	Tuple<Args...> tail_;
};

template<typename Arg>
struct Tuple<Arg>
{
	Tuple(){
	}

	Tuple(Arg arg)
		: head_(arg)
	{
	}

	Arg head_;
};

template<typename ... Args>
Tuple<Args...> makeTuple(Args ... args){
	return Tuple<Args...>(args...);
}

template<int I, typename Arg, typename ... Args>
struct Get
{
	auto operator()(Tuple<Arg, Args...> tuple)
	{
		return Get<I - 1, Args...>()(tuple.tail_);
	}
};

template<typename Arg, typename ... Args>
struct Get<0, Arg, Args...>
{
	Arg operator()(Tuple<Arg, Args...> tuple){
		return tuple.head_;
	}
};

template<int I, typename Arg, typename ... Args>
auto get(Tuple<Arg, Args...> tuple){
	return Get<I, Arg, Args...>()(tuple);
}

template<typename Arg, typename ... Args>
int size(Tuple<Arg, Args...> tuple){
	return 1 + sizeof...(Args);
}

#include <cassert>
#include <string>

int main(){
	auto tuple = makeTuple(0, 1.0, '2', "3");

	assert(get<0>(tuple) == 0);
	assert(get<1>(tuple) == 1.0);
	assert(get<2>(tuple) == '2');

	using namespace std::string_literals;
	assert(get<3>(tuple) == "3"s);

	assert(size(tuple) == 4);
}

<commit_msg>tuple.cpp<commit_after>/*
 * Website:
 *      https://github.com/wo3kie/dojo
 *
 * Author:
 *      Lukasz Czerwinski
 *
 * Compilation:
 *      g++ --std=c++14 tuple.cpp -o tuple
 *
 * Usage:
 *      $ ./tuple
 */

#include <iostream>

template<typename Arg, typename ... Args>
struct Tuple
{
	Tuple(){
	}

	Tuple(Arg arg, Args... args)
		: head_(arg)
		, tail_(args...)
	{
	}

	Arg head_;
	Tuple<Args...> tail_;
};

template<typename Arg>
struct Tuple<Arg>
{
	Tuple(){
	}

	Tuple(Arg arg)
		: head_(arg)
	{
	}

	Arg head_;
};

template<typename ... Args>
constexpr Tuple<Args...> makeTuple(Args && ... args){
	return Tuple<Args...>(std::forward<Args>(args)...);
}

template<int I, typename Arg, typename ... Args>
struct Get
{
	constexpr auto operator()(Tuple<Arg, Args...> tuple) const {
		return Get<I - 1, Args...>()(tuple.tail_);
	}
};

template<typename Arg, typename ... Args>
struct Get<0, Arg, Args...>
{
	constexpr Arg operator()(Tuple<Arg, Args...> tuple) const {
		return tuple.head_;
	}
};

template<int I, typename Arg, typename ... Args>
constexpr auto get(Tuple<Arg, Args...> tuple){
	return Get<I, Arg, Args...>()(tuple);
}

template<typename Arg, typename ... Args>
constexpr int size(Tuple<Arg, Args...> const & tuple){
	return 1 + sizeof...(Args);
}

#include <cassert>
#include <string>

int main(){
	auto tuple = makeTuple(0, 1.0, '2', "3");

	assert(get<0>(tuple) == 0);
	assert(get<1>(tuple) == 1.0);
	assert(get<2>(tuple) == '2');

	using namespace std::string_literals;
	assert(get<3>(tuple) == "3"s);

	assert(size(tuple) == 4);
}

<|endoftext|>


<commit_before>/*=============================================================================
   Copyright (c) 2016-2017 Joel de Guzman

   Distributed under the MIT License [ https://opensource.org/licenses/MIT ]
=============================================================================*/
#include <photon/support/glyphs.hpp>
#include <photon/support/detail/scratch_context.hpp>

namespace photon
{
   static detail::scratch_context scratch_context_;

   glyphs::glyphs(char const* first, char const* last)
    : _first(first)
    , _last(last)
   {
      PHOTON_ASSERT(_first, "Precondition failure: _first must not be null");
      PHOTON_ASSERT(_last, "Precondition failure: _last must not be null");
   }

   glyphs::glyphs(
      char const* first, char const* last
    , int glyph_start, int glyph_end
    , int cluster_start, int cluster_end
    , master_glyphs const& master
    , bool strip_leading_spaces
   )
    : _first(first)
    , _last(last)
    , _scaled_font(master._scaled_font)
    , _glyphs(master._glyphs + glyph_start)
    , _glyph_count(glyph_end - glyph_start)
    , _clusters(master._clusters + cluster_start)
    , _cluster_count(cluster_end - cluster_start)
    , _clusterflags(master._clusterflags)
   {
      PHOTON_ASSERT(_first, "Precondition failure: _first must not be null");
      PHOTON_ASSERT(_last, "Precondition failure: _last must not be null");
      PHOTON_ASSERT(_scaled_font, "Precondition failure: _scaled_font must not be null");
      PHOTON_ASSERT(_glyphs, "Precondition failure: _glyphs must not be null");
      PHOTON_ASSERT(_clusters, "Precondition failure: _clusters must not be null");

      // We strip leading spaces until after the last leading newline.
      // Examples:
      //
      //    "\n\n  " ===>  "  "
      //    " \n\n"  ===>  ""
      //    "   xxx" ===>  "xxx"

      auto  strip_leading = [this](auto f)
      {
         int      glyph_index = 0;
         unsigned codepoint;
         unsigned state = 0;

         cairo_text_cluster_t* cluster = _clusters;
         for (auto i = _first; i != _last; ++i)
         {
            if (!decode_utf8(state, codepoint, uint8_t(*i)))
            {
               if (!f(codepoint))
                  break;
               glyph_index += cluster->num_glyphs;
               ++cluster;
            }
         }

         auto   clusters_skipped = int(cluster - _clusters);

         _glyph_count -= glyph_index;
         _glyphs += glyph_index;
         _cluster_count -= clusters_skipped;
         _clusters = cluster;
         _first += clusters_skipped;
      };

      if (strip_leading_spaces)
         strip_leading([](auto cp){ return !is_newline(cp) && is_space(cp); });
      strip_leading([](auto cp){ return is_newline(cp); });
   }

   void glyphs::draw(point pos, canvas& canvas_)
   {
      // return early if there's nothing to draw
      if (_first == _last)
         return;

      PHOTON_ASSERT(_scaled_font, "Precondition failure: _scaled_font must not be null");
      PHOTON_ASSERT(_glyphs, "Precondition failure: _glyphs must not be null");
      PHOTON_ASSERT(_clusters, "Precondition failure: _clusters must not be null");

      auto cr = &canvas_.cairo_context();
      auto state = canvas_.new_state();

      cairo_set_scaled_font(cr, _scaled_font);
      cairo_translate(cr, pos.x - _glyphs->x, pos.y - _glyphs->y);
      canvas_.apply_fill_style();

      cairo_show_text_glyphs(
         cr, _first, int(_last - _first),
         _glyphs, _glyph_count,
         _clusters, _cluster_count, _clusterflags
      );
   }

   float glyphs::width() const
   {
      if (_first == _last)
         return 0;

      PHOTON_ASSERT(_scaled_font, "Precondition failure: _scaled_font must not be null");
      PHOTON_ASSERT(_glyphs, "Precondition failure: _glyphs must not be null");
      PHOTON_ASSERT(_clusters, "Precondition failure: _clusters must not be null");

      if (_glyph_count)
      {
         cairo_text_extents_t extents;
         auto glyph = _glyphs + _glyph_count -1;
         cairo_scaled_font_glyph_extents(_scaled_font, glyph, 1, &extents);
         return (glyph->x + extents.x_advance) - _glyphs->x;
      }
      return 0;
   }

   glyphs::font_metrics glyphs::metrics() const
   {
      cairo_font_extents_t font_extents;
      cairo_scaled_font_extents(_scaled_font, &font_extents);

      return {
         /*ascent=*/    float(font_extents.ascent),
         /*descent=*/   float(font_extents.descent),
         /*leading=*/   float(font_extents.height-(font_extents.ascent + font_extents.descent)),
      };
   }

   ////////////////////////////////////////////////////////////////////////////
   master_glyphs::master_glyphs(
       char const* first, char const* last
     , char const* face, float size, int style
   )
    : glyphs(first, last)
   {
      canvas cnv{ *scratch_context_.context() };
      cnv.font(face, size, style);
      auto cr = scratch_context_.context();
      _scaled_font = cairo_scaled_font_reference(cairo_get_scaled_font(cr));
      build();
   }

   master_glyphs::master_glyphs(char const* first, char const* last, master_glyphs const& source)
    : glyphs(first, last)
   {
      canvas cnv{ *scratch_context_.context() };
      _scaled_font = cairo_scaled_font_reference(source._scaled_font);
      build();
   }

   master_glyphs::master_glyphs(master_glyphs&& rhs)
    : glyphs(rhs._first, rhs._last)
   {
      _scaled_font = rhs._scaled_font;
      _glyphs = rhs._glyphs;
      _glyph_count = rhs._glyph_count;
      _clusters = rhs._clusters;
      _cluster_count = rhs._cluster_count;
      _clusterflags = rhs._clusterflags;

      rhs._glyphs = nullptr;
      rhs._clusters = nullptr;
      rhs._scaled_font = nullptr;
   }

   master_glyphs& master_glyphs::operator=(master_glyphs&& rhs)
   {
      if (&rhs != this)
      {
         _first = rhs._first;
         _last = rhs._last;
         _scaled_font = rhs._scaled_font;
         _glyphs = rhs._glyphs;
         _glyph_count = rhs._glyph_count;
         _clusters = rhs._clusters;
         _cluster_count = rhs._cluster_count;
         _clusterflags = rhs._clusterflags;

         rhs._glyphs = nullptr;
         rhs._clusters = nullptr;
         rhs._scaled_font = nullptr;
      }
      return *this;
   }

   master_glyphs::~master_glyphs()
   {
      if (_glyphs)
         cairo_glyph_free(_glyphs);
      if (_clusters)
         cairo_text_cluster_free(_clusters);
      if (_scaled_font)
         cairo_scaled_font_destroy(_scaled_font);

      _glyphs = nullptr;
      _clusters = nullptr;
      _scaled_font = nullptr;
   }

   void master_glyphs::text(char const* first, char const* last)
   {
      if (_glyphs)
      {
         cairo_glyph_free(_glyphs);
         _glyphs = nullptr;
      }
      if (_clusters)
      {
         cairo_text_cluster_free(_clusters);
         _clusters = nullptr;
      }

      _first = first;
      _last = last;
      build();
   }

   void master_glyphs::break_lines(float width, std::vector<glyphs>& lines)
   {
      PHOTON_ASSERT(_scaled_font, "Precondition failure: _scaled_font must not be null");

      // reurn early if there's nothing to break
      if (_first == _last)
         return;

      PHOTON_ASSERT(_glyphs, "Precondition failure: _glyphs must not be null");
      PHOTON_ASSERT(_clusters, "Precondition failure: _clusters must not be null");

      char const* first = _first;
      char const* last = _last;
      char const* space_pos = _first;
      int         start_glyph_index = 0;
      int         start_cluster_index = 0;
      int         space_glyph_index = 0;
      int         space_cluster_index = 0;
      float       start_x = _glyphs->x;

      auto add_line = [&]()
      {
         glyphs glyph_{
            first, space_pos
          , start_glyph_index, space_glyph_index
          , start_cluster_index, space_cluster_index
          , *this
          , lines.size() > 1 // skip leading spaces if this is not the first line
         };
         lines.push_back(std::move(glyph_));
         first = space_pos;
         start_glyph_index = space_glyph_index;
         start_cluster_index = space_cluster_index;
         start_x = _glyphs[space_glyph_index].x;
      };

      int      glyph_index = 0;
      unsigned codepoint;
      unsigned state = 0;

      cairo_text_cluster_t* cluster = _clusters;
      for (auto i = _first; i != _last; ++i)
      {
         if (!decode_utf8(state, codepoint, uint8_t(*i)))
         {
            cairo_glyph_t*  glyph = _glyphs + glyph_index;

            // Check if we exceeded the line width:
            cairo_text_extents_t extents;
            cairo_scaled_font_glyph_extents(_scaled_font, glyph, 1, &extents);
            if (((glyph->x + extents.x_advance) - start_x) > width)
            {
               // Add the line if we did (exceed the line width)
               add_line();
            }

            // Did we have a space?
            else if (is_space(codepoint))
            {
               // Mark the spaces for later
               space_glyph_index = glyph_index;
               space_cluster_index = int(cluster - _clusters);
               space_pos = i;

               // If we got an explicit new line, add the line right away.
               if ((space_glyph_index != start_glyph_index) && is_newline(codepoint))
                  add_line();
            }

            glyph_index += cluster->num_glyphs;
            ++cluster;
         }
      }

      glyphs glyph_{
         first, last
       , start_glyph_index, _glyph_count
       , start_cluster_index, _cluster_count
       , *this
       , lines.size() > 1 // skip leading spaces if this is not the first line
      };

      lines.push_back(std::move(glyph_));
   }

   void master_glyphs::build()
   {
      // reurn early if there's nothing to build
      if (_first == _last)
         return;

      auto stat = cairo_scaled_font_text_to_glyphs(
         _scaled_font, 0, 0, _first, int(_last - _first),
         &_glyphs, &_glyph_count, &_clusters, &_cluster_count,
         &_clusterflags);

      if (stat != CAIRO_STATUS_SUCCESS)
      {
         _glyphs = nullptr;
         _clusters = nullptr;
         throw failed_to_build_master_glyphs{};
      }
   }
}
<commit_msg>bugfix: remove leading space of second line<commit_after>/*=============================================================================
   Copyright (c) 2016-2017 Joel de Guzman

   Distributed under the MIT License [ https://opensource.org/licenses/MIT ]
=============================================================================*/
#include <photon/support/glyphs.hpp>
#include <photon/support/detail/scratch_context.hpp>

namespace photon
{
   static detail::scratch_context scratch_context_;

   glyphs::glyphs(char const* first, char const* last)
    : _first(first)
    , _last(last)
   {
      PHOTON_ASSERT(_first, "Precondition failure: _first must not be null");
      PHOTON_ASSERT(_last, "Precondition failure: _last must not be null");
   }

   glyphs::glyphs(
      char const* first, char const* last
    , int glyph_start, int glyph_end
    , int cluster_start, int cluster_end
    , master_glyphs const& master
    , bool strip_leading_spaces
   )
    : _first(first)
    , _last(last)
    , _scaled_font(master._scaled_font)
    , _glyphs(master._glyphs + glyph_start)
    , _glyph_count(glyph_end - glyph_start)
    , _clusters(master._clusters + cluster_start)
    , _cluster_count(cluster_end - cluster_start)
    , _clusterflags(master._clusterflags)
   {
      PHOTON_ASSERT(_first, "Precondition failure: _first must not be null");
      PHOTON_ASSERT(_last, "Precondition failure: _last must not be null");
      PHOTON_ASSERT(_scaled_font, "Precondition failure: _scaled_font must not be null");
      PHOTON_ASSERT(_glyphs, "Precondition failure: _glyphs must not be null");
      PHOTON_ASSERT(_clusters, "Precondition failure: _clusters must not be null");

      // We strip leading spaces until after the last leading newline.
      // Examples:
      //
      //    "\n\n  " ===>  "  "
      //    " \n\n"  ===>  ""
      //    "   xxx" ===>  "xxx"

      auto  strip_leading = [this](auto f)
      {
         int      glyph_index = 0;
         unsigned codepoint;
         unsigned state = 0;

         cairo_text_cluster_t* cluster = _clusters;
         for (auto i = _first; i != _last; ++i)
         {
            if (!decode_utf8(state, codepoint, uint8_t(*i)))
            {
               if (!f(codepoint))
                  break;
               glyph_index += cluster->num_glyphs;
               ++cluster;
            }
         }

         auto   clusters_skipped = int(cluster - _clusters);

         _glyph_count -= glyph_index;
         _glyphs += glyph_index;
         _cluster_count -= clusters_skipped;
         _clusters = cluster;
         _first += clusters_skipped;
      };

      if (strip_leading_spaces)
         strip_leading([](auto cp){ return !is_newline(cp) && is_space(cp); });
      strip_leading([](auto cp){ return is_newline(cp); });
   }

   void glyphs::draw(point pos, canvas& canvas_)
   {
      // return early if there's nothing to draw
      if (_first == _last)
         return;

      PHOTON_ASSERT(_scaled_font, "Precondition failure: _scaled_font must not be null");
      PHOTON_ASSERT(_glyphs, "Precondition failure: _glyphs must not be null");
      PHOTON_ASSERT(_clusters, "Precondition failure: _clusters must not be null");

      auto cr = &canvas_.cairo_context();
      auto state = canvas_.new_state();

      cairo_set_scaled_font(cr, _scaled_font);
      cairo_translate(cr, pos.x - _glyphs->x, pos.y - _glyphs->y);
      canvas_.apply_fill_style();

      cairo_show_text_glyphs(
         cr, _first, int(_last - _first),
         _glyphs, _glyph_count,
         _clusters, _cluster_count, _clusterflags
      );
   }

   float glyphs::width() const
   {
      if (_first == _last)
         return 0;

      PHOTON_ASSERT(_scaled_font, "Precondition failure: _scaled_font must not be null");
      PHOTON_ASSERT(_glyphs, "Precondition failure: _glyphs must not be null");
      PHOTON_ASSERT(_clusters, "Precondition failure: _clusters must not be null");

      if (_glyph_count)
      {
         cairo_text_extents_t extents;
         auto glyph = _glyphs + _glyph_count -1;
         cairo_scaled_font_glyph_extents(_scaled_font, glyph, 1, &extents);
         return (glyph->x + extents.x_advance) - _glyphs->x;
      }
      return 0;
   }

   glyphs::font_metrics glyphs::metrics() const
   {
      cairo_font_extents_t font_extents;
      cairo_scaled_font_extents(_scaled_font, &font_extents);

      return {
         /*ascent=*/    float(font_extents.ascent),
         /*descent=*/   float(font_extents.descent),
         /*leading=*/   float(font_extents.height-(font_extents.ascent + font_extents.descent)),
      };
   }

   ////////////////////////////////////////////////////////////////////////////
   master_glyphs::master_glyphs(
       char const* first, char const* last
     , char const* face, float size, int style
   )
    : glyphs(first, last)
   {
      canvas cnv{ *scratch_context_.context() };
      cnv.font(face, size, style);
      auto cr = scratch_context_.context();
      _scaled_font = cairo_scaled_font_reference(cairo_get_scaled_font(cr));
      build();
   }

   master_glyphs::master_glyphs(char const* first, char const* last, master_glyphs const& source)
    : glyphs(first, last)
   {
      canvas cnv{ *scratch_context_.context() };
      _scaled_font = cairo_scaled_font_reference(source._scaled_font);
      build();
   }

   master_glyphs::master_glyphs(master_glyphs&& rhs)
    : glyphs(rhs._first, rhs._last)
   {
      _scaled_font = rhs._scaled_font;
      _glyphs = rhs._glyphs;
      _glyph_count = rhs._glyph_count;
      _clusters = rhs._clusters;
      _cluster_count = rhs._cluster_count;
      _clusterflags = rhs._clusterflags;

      rhs._glyphs = nullptr;
      rhs._clusters = nullptr;
      rhs._scaled_font = nullptr;
   }

   master_glyphs& master_glyphs::operator=(master_glyphs&& rhs)
   {
      if (&rhs != this)
      {
         _first = rhs._first;
         _last = rhs._last;
         _scaled_font = rhs._scaled_font;
         _glyphs = rhs._glyphs;
         _glyph_count = rhs._glyph_count;
         _clusters = rhs._clusters;
         _cluster_count = rhs._cluster_count;
         _clusterflags = rhs._clusterflags;

         rhs._glyphs = nullptr;
         rhs._clusters = nullptr;
         rhs._scaled_font = nullptr;
      }
      return *this;
   }

   master_glyphs::~master_glyphs()
   {
      if (_glyphs)
         cairo_glyph_free(_glyphs);
      if (_clusters)
         cairo_text_cluster_free(_clusters);
      if (_scaled_font)
         cairo_scaled_font_destroy(_scaled_font);

      _glyphs = nullptr;
      _clusters = nullptr;
      _scaled_font = nullptr;
   }

   void master_glyphs::text(char const* first, char const* last)
   {
      if (_glyphs)
      {
         cairo_glyph_free(_glyphs);
         _glyphs = nullptr;
      }
      if (_clusters)
      {
         cairo_text_cluster_free(_clusters);
         _clusters = nullptr;
      }

      _first = first;
      _last = last;
      build();
   }

   void master_glyphs::break_lines(float width, std::vector<glyphs>& lines)
   {
      PHOTON_ASSERT(_scaled_font, "Precondition failure: _scaled_font must not be null");

      // reurn early if there's nothing to break
      if (_first == _last)
         return;

      PHOTON_ASSERT(_glyphs, "Precondition failure: _glyphs must not be null");
      PHOTON_ASSERT(_clusters, "Precondition failure: _clusters must not be null");

      char const* first = _first;
      char const* last = _last;
      char const* space_pos = _first;
      int         start_glyph_index = 0;
      int         start_cluster_index = 0;
      int         space_glyph_index = 0;
      int         space_cluster_index = 0;
      float       start_x = _glyphs->x;

      auto add_line = [&]()
      {
         glyphs glyph_{
            first, space_pos
          , start_glyph_index, space_glyph_index
          , start_cluster_index, space_cluster_index
          , *this
          , lines.size() > 0 // skip leading spaces if this is not the first line
         };
         lines.push_back(std::move(glyph_));
         first = space_pos;
         start_glyph_index = space_glyph_index;
         start_cluster_index = space_cluster_index;
         start_x = _glyphs[space_glyph_index].x;
      };

      int      glyph_index = 0;
      unsigned codepoint;
      unsigned state = 0;

      cairo_text_cluster_t* cluster = _clusters;
      for (auto i = _first; i != _last; ++i)
      {
         if (!decode_utf8(state, codepoint, uint8_t(*i)))
         {
            cairo_glyph_t*  glyph = _glyphs + glyph_index;

            // Check if we exceeded the line width:
            cairo_text_extents_t extents;
            cairo_scaled_font_glyph_extents(_scaled_font, glyph, 1, &extents);
            if (((glyph->x + extents.x_advance) - start_x) > width)
            {
               // Add the line if we did (exceed the line width)
               add_line();
            }

            // Did we have a space?
            else if (is_space(codepoint))
            {
               // Mark the spaces for later
               space_glyph_index = glyph_index;
               space_cluster_index = int(cluster - _clusters);
               space_pos = i;

               // If we got an explicit new line, add the line right away.
               if ((space_glyph_index != start_glyph_index) && is_newline(codepoint))
                  add_line();
            }

            glyph_index += cluster->num_glyphs;
            ++cluster;
         }
      }

      glyphs glyph_{
         first, last
       , start_glyph_index, _glyph_count
       , start_cluster_index, _cluster_count
       , *this
       , lines.size() > 1 // skip leading spaces if this is not the first line
      };

      lines.push_back(std::move(glyph_));
   }

   void master_glyphs::build()
   {
      // reurn early if there's nothing to build
      if (_first == _last)
         return;

      auto stat = cairo_scaled_font_text_to_glyphs(
         _scaled_font, 0, 0, _first, int(_last - _first),
         &_glyphs, &_glyph_count, &_clusters, &_cluster_count,
         &_clusterflags);

      if (stat != CAIRO_STATUS_SUCCESS)
      {
         _glyphs = nullptr;
         _clusters = nullptr;
         throw failed_to_build_master_glyphs{};
      }
   }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <ostream>
#include <string>

int main()
{
    std::cout<< "Adınız Nedir? ";
    std::string str;
    std::getline(std::cin,str);
    std::cout<< "Selâmü Aleyküm "<< str<< '\n';
    return 0;
}

<commit_msg>removed redundant return from main<commit_after>#include <iostream>
#include <ostream>
#include <string>

int main()
{
    std::cout<< "Adınız Nedir? ";
    std::string str;
    std::getline(std::cin,str);
    std::cout<< "Selâmü Aleyküm "<< str<< '\n';
}

<|endoftext|>