text
stringlengths 54
60.6k
|
|---|
<commit_before>
#pragma once
#include "numerics/frequency_analysis.hpp"
#include <algorithm>
#include <functional>
#include <vector>
#include "base/tags.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/hilbert.hpp"
#include "numerics/poisson_series_basis.hpp"
#include "numerics/root_finders.hpp"
#include "numerics/unbounded_arrays.hpp"
#include "quantities/elementary_functions.hpp"
namespace principia {
namespace numerics {
namespace frequency_analysis {
namespace internal_frequency_analysis {
using base::uninitialized;
using geometry::Hilbert;
using geometry::Vector;
using quantities::Inverse;
using quantities::IsFinite;
using quantities::Sqrt;
using quantities::Square;
using quantities::SquareRoot;
template<typename Function,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
AngularFrequency PreciseMode(
Interval<AngularFrequency> const& fft_mode,
Function const& function,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight) {
auto const weighted_function = weight * function;
auto const weighted_function_spectrum = weighted_function.FourierTransform();
auto power =
[&weighted_function_spectrum](AngularFrequency const& ω) {
return weighted_function_spectrum(ω).Norm²();
};
return Brent(power,
fft_mode.min,
fft_mode.max,
std::greater<>());
}
template<int aperiodic_degree, int periodic_degree,
typename Function,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
PoissonSeries<std::invoke_result_t<Function, Instant>,
aperiodic_degree, periodic_degree,
Evaluator>
Projection(Function const& function,
AngularFrequency const& ω,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight,
Instant const& t_min,
Instant const& t_max) {
std::optional<AngularFrequency> optional_ω = ω;
// A calculator that returns optional_ω once and then stops.
auto angular_frequency_calculator = [&optional_ω](auto const& residual) {
auto const result = optional_ω;
optional_ω = std::nullopt;
return result;
};
return IncrementalProjection<aperiodic_degree, periodic_degree>(
function,
angular_frequency_calculator,
weight,
t_min, t_max);
}
#define DO_THE_LOGGING 0
#define USE_CGS 1
#define USE_INTEGRATE 0
template<int aperiodic_degree, int periodic_degree,
typename Function,
typename AngularFrequencyCalculator,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
PoissonSeries<std::invoke_result_t<Function, Instant>,
aperiodic_degree, periodic_degree,
Evaluator>
IncrementalProjection(Function const& function,
AngularFrequencyCalculator const& calculator,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight,
Instant const& t_min,
Instant const& t_max) {
using Value = std::invoke_result_t<Function, Instant>;
using Norm = typename Hilbert<Value>::NormType;
using Normalized = typename Hilbert<Value>::NormalizedType;
using Series = PoissonSeries<Value,
aperiodic_degree, periodic_degree,
Evaluator>;
// This code follows [Kud07], section 2. Our indices start at 0, unlike those
// of Кудрявцев which start at 1.
Instant const& t0 = weight.origin();
std::optional<AngularFrequency> ω = calculator(function);
CHECK(ω.has_value());
std::vector<Series> basis;
// The Poisson series basis[k] belongs to the subspace basis_subspaces[k];
// this remains true after orthonormalization, i.e., q[k] belongs to the
// subspace basis_subspaces[k] below.
std::vector<PoissonSeriesSubspace> basis_subspaces;
int basis_size;
// TODO(phl): This is replicated below.
if (ω.value() == AngularFrequency{}) {
auto const ω_basis =
PoissonSeriesBasisGenerator<Series,
aperiodic_degree>::Basis(t0);
auto const ω_basis_subspaces =
PoissonSeriesBasisGenerator<Series, aperiodic_degree>::Subspaces(t0);
basis_size = std::tuple_size_v<decltype(ω_basis)>;
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
} else {
auto const ω_basis =
PoissonSeriesBasisGenerator<Series,
periodic_degree>::Basis(ω.value(), t0);
auto const ω_basis_subspaces =
PoissonSeriesBasisGenerator<Series, periodic_degree>::Subspaces(
ω.value(), t0);
basis_size = std::tuple_size_v<decltype(ω_basis)>;
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
}
// This is logically Q in the QR decomposition of basis.
std::vector<PoissonSeries<Normalized,
aperiodic_degree, periodic_degree,
Evaluator>> q;
auto const& a₀ = basis[0];
auto const r₀₀ = a₀.Norm(weight, t_min, t_max);
CHECK(IsFinite(r₀₀)) << a₀;
q.push_back(a₀ / r₀₀);
auto const A₀ = InnerProduct(function, q[0], weight, t_min, t_max);
Series F = A₀ * q[0];
auto f = function - F;
int m_begin = 1;
for (;;) {
for (int m = m_begin; m < basis_size; ++m) {
auto const& aₘ = basis[m];
// k -> m
std::optional<Series> previous_q̂ₘ;
Series q̂ₘ = aₘ;
std::vector<Norm> rₘ(m);
// Loop on p.
do {
std::vector<Norm> sᵖₘ;
for (int i = 0; i < m; ++i) {
sᵖₘ.push_back(InnerProduct(q[i], q̂ₘ, weight, t_min, t_max));
}
previous_q̂ₘ = q̂ₘ;
for (int i = 0; i < m; ++i) {
q̂ₘ -= sᵖₘ[i] * q[i];
}
for (int i = 0; i < m; ++i) {
rₘ[i] += sᵖₘ[i];
}
//LOG(ERROR) << "m: " << m << " q̂ₘ: " << q̂ₘ.Norm(weight, t_min, t_max)
// << " previous q̂ₘ: "
// << previous_q̂ₘ.value().Norm(
// weight, t_min, t_max);
} while (q̂ₘ.Norm(weight, t_min, t_max) <
0.5 * previous_q̂ₘ.value().Norm(weight, t_min, t_max));
auto const rₘₘ = q̂ₘ.Norm(weight, t_min, t_max);
q.push_back(q̂ₘ / rₘₘ);
#if 0
auto const r₀ₘ = InnerProduct(q[0], aₘ, weight, t_min, t_max);
Series Σrᵢₘqᵢ = r₀ₘ * q[0];
for (int i = 1; i < m; ++i) {
auto const rᵢₘ = InnerProduct(q[i], aₘ, weight, t_min, t_max);
Σrᵢₘqᵢ += rᵢₘ * q[i];
}
auto const qʹₘ = aₘ - Σrᵢₘqᵢ;
auto rₘₘ = qʹₘ.Norm(weight, t_min, t_max);
q.push_back(qʹₘ / rₘₘ);
#endif
DCHECK_EQ(m + 1, q.size());
Norm const Aₘ = InnerProduct(f, q[m], weight, t_min, t_max);
auto const Aₘqₘ = Aₘ * q[m];
f -= Aₘqₘ;
F += Aₘqₘ;
}
ω = calculator(f);
if (!ω.has_value()) {
return F;
}
int ω_basis_size;
if (ω.value() == AngularFrequency{}) {
auto const ω_basis =
PoissonSeriesBasisGenerator<Series,
aperiodic_degree>::Basis(t0);
auto const ω_basis_subspaces =
PoissonSeriesBasisGenerator<Series, aperiodic_degree>::Subspaces(t0);
ω_basis_size = std::tuple_size_v<decltype(ω_basis)>;
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
} else {
auto const ω_basis =
PoissonSeriesBasisGenerator<Series,
periodic_degree>::Basis(ω.value(), t0);
auto const ω_basis_subspaces =
PoissonSeriesBasisGenerator<Series, periodic_degree>::Subspaces(
ω.value(), t0);
ω_basis_size = std::tuple_size_v<decltype(ω_basis)>;
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
}
m_begin = basis_size;
basis_size += ω_basis_size;
}
}
} // namespace internal_frequency_analysis
} // namespace frequency_analysis
} // namespace numerics
} // namespace principia
<commit_msg>Some code simplification.<commit_after>
#pragma once
#include "numerics/frequency_analysis.hpp"
#include <algorithm>
#include <functional>
#include <vector>
#include "base/tags.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/hilbert.hpp"
#include "numerics/poisson_series_basis.hpp"
#include "numerics/root_finders.hpp"
#include "numerics/unbounded_arrays.hpp"
#include "quantities/elementary_functions.hpp"
namespace principia {
namespace numerics {
namespace frequency_analysis {
namespace internal_frequency_analysis {
using base::uninitialized;
using geometry::Hilbert;
using geometry::Vector;
using quantities::Inverse;
using quantities::IsFinite;
using quantities::Sqrt;
using quantities::Square;
using quantities::SquareRoot;
template<typename Function,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
AngularFrequency PreciseMode(
Interval<AngularFrequency> const& fft_mode,
Function const& function,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight) {
auto const weighted_function = weight * function;
auto const weighted_function_spectrum = weighted_function.FourierTransform();
auto power =
[&weighted_function_spectrum](AngularFrequency const& ω) {
return weighted_function_spectrum(ω).Norm²();
};
return Brent(power,
fft_mode.min,
fft_mode.max,
std::greater<>());
}
template<int aperiodic_degree, int periodic_degree,
typename Function,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
PoissonSeries<std::invoke_result_t<Function, Instant>,
aperiodic_degree, periodic_degree,
Evaluator>
Projection(Function const& function,
AngularFrequency const& ω,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight,
Instant const& t_min,
Instant const& t_max) {
std::optional<AngularFrequency> optional_ω = ω;
// A calculator that returns optional_ω once and then stops.
auto angular_frequency_calculator = [&optional_ω](auto const& residual) {
auto const result = optional_ω;
optional_ω = std::nullopt;
return result;
};
return IncrementalProjection<aperiodic_degree, periodic_degree>(
function,
angular_frequency_calculator,
weight,
t_min, t_max);
}
#define DO_THE_LOGGING 0
#define USE_CGS 1
#define USE_INTEGRATE 0
template<int aperiodic_degree, int periodic_degree,
typename Function,
typename AngularFrequencyCalculator,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
PoissonSeries<std::invoke_result_t<Function, Instant>,
aperiodic_degree, periodic_degree,
Evaluator>
IncrementalProjection(Function const& function,
AngularFrequencyCalculator const& calculator,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight,
Instant const& t_min,
Instant const& t_max) {
using Value = std::invoke_result_t<Function, Instant>;
using Norm = typename Hilbert<Value>::NormType;
using Normalized = typename Hilbert<Value>::NormalizedType;
using Series = PoissonSeries<Value,
aperiodic_degree, periodic_degree,
Evaluator>;
// This code follows [Kud07], section 2. Our indices start at 0, unlike those
// of Кудрявцев which start at 1.
Instant const& t0 = weight.origin();
std::optional<AngularFrequency> ω = calculator(function);
CHECK(ω.has_value());
std::vector<Series> basis;
// The Poisson series basis[k] belongs to the subspace basis_subspaces[k];
// this remains true after orthonormalization, i.e., q[k] belongs to the
// subspace basis_subspaces[k] below.
std::vector<PoissonSeriesSubspace> basis_subspaces;
int basis_size;
// TODO(phl): This is replicated below.
if (ω.value() == AngularFrequency{}) {
auto const ω_basis =
PoissonSeriesBasisGenerator<Series,
aperiodic_degree>::Basis(t0);
auto const ω_basis_subspaces =
PoissonSeriesBasisGenerator<Series, aperiodic_degree>::Subspaces(t0);
basis_size = std::tuple_size_v<decltype(ω_basis)>;
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
} else {
auto const ω_basis =
PoissonSeriesBasisGenerator<Series,
periodic_degree>::Basis(ω.value(), t0);
auto const ω_basis_subspaces =
PoissonSeriesBasisGenerator<Series, periodic_degree>::Subspaces(
ω.value(), t0);
basis_size = std::tuple_size_v<decltype(ω_basis)>;
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
}
// This is logically Q in the QR decomposition of basis.
std::vector<PoissonSeries<Normalized,
aperiodic_degree, periodic_degree,
Evaluator>> q;
auto const& a₀ = basis[0];
auto const r₀₀ = a₀.Norm(weight, t_min, t_max);
CHECK(IsFinite(r₀₀)) << a₀;
q.push_back(a₀ / r₀₀);
auto const A₀ = InnerProduct(function, q[0], weight, t_min, t_max);
Series F = A₀ * q[0];
auto f = function - F;
int m_begin = 1;
for (;;) {
for (int m = m_begin; m < basis_size; ++m) {
auto const& aₘ = basis[m];
// k -> m
Series q̂ₘ = aₘ;
Series previous_q̂ₘ = q̂ₘ;
std::vector<Norm> rₘ(m);
// Loop on p.
do {
previous_q̂ₘ = q̂ₘ;
std::vector<Norm> sᵖₘ;
for (int i = 0; i < m; ++i) {
if (!PoissonSeriesSubspace::orthogonal(basis_subspaces[i],
basis_subspaces[m])) {
auto const sᵖₘ =
InnerProduct(q[i], previous_q̂ₘ, weight, t_min, t_max);
q̂ₘ -= sᵖₘ * q[i];
}
}
//LOG(ERROR) << "m: " << m << " q̂ₘ: " << q̂ₘ.Norm(weight, t_min, t_max)
// << " previous q̂ₘ: "
// << previous_q̂ₘ.value().Norm(
// weight, t_min, t_max);
} while (q̂ₘ.Norm(weight, t_min, t_max) <
0.5 * previous_q̂ₘ.Norm(weight, t_min, t_max));
auto const rₘₘ = q̂ₘ.Norm(weight, t_min, t_max);
q.push_back(q̂ₘ / rₘₘ);
#if 0
auto const r₀ₘ = InnerProduct(q[0], aₘ, weight, t_min, t_max);
Series Σrᵢₘqᵢ = r₀ₘ * q[0];
for (int i = 1; i < m; ++i) {
auto const rᵢₘ = InnerProduct(q[i], aₘ, weight, t_min, t_max);
Σrᵢₘqᵢ += rᵢₘ * q[i];
}
auto const qʹₘ = aₘ - Σrᵢₘqᵢ;
auto rₘₘ = qʹₘ.Norm(weight, t_min, t_max);
q.push_back(qʹₘ / rₘₘ);
#endif
DCHECK_EQ(m + 1, q.size());
Norm const Aₘ = InnerProduct(f, q[m], weight, t_min, t_max);
auto const Aₘqₘ = Aₘ * q[m];
f -= Aₘqₘ;
F += Aₘqₘ;
}
ω = calculator(f);
if (!ω.has_value()) {
return F;
}
int ω_basis_size;
if (ω.value() == AngularFrequency{}) {
auto const ω_basis =
PoissonSeriesBasisGenerator<Series,
aperiodic_degree>::Basis(t0);
auto const ω_basis_subspaces =
PoissonSeriesBasisGenerator<Series, aperiodic_degree>::Subspaces(t0);
ω_basis_size = std::tuple_size_v<decltype(ω_basis)>;
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
} else {
auto const ω_basis =
PoissonSeriesBasisGenerator<Series,
periodic_degree>::Basis(ω.value(), t0);
auto const ω_basis_subspaces =
PoissonSeriesBasisGenerator<Series, periodic_degree>::Subspaces(
ω.value(), t0);
ω_basis_size = std::tuple_size_v<decltype(ω_basis)>;
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
}
m_begin = basis_size;
basis_size += ω_basis_size;
}
}
} // namespace internal_frequency_analysis
} // namespace frequency_analysis
} // namespace numerics
} // namespace principia
<|endoftext|>
|
<commit_before>
#pragma once
#include "numerics/frequency_analysis.hpp"
#include <algorithm>
#include <functional>
#include <vector>
#include "base/status.hpp"
#include "base/tags.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/hilbert.hpp"
#include "numerics/poisson_series_basis.hpp"
#include "numerics/root_finders.hpp"
#include "numerics/unbounded_arrays.hpp"
#include "quantities/elementary_functions.hpp"
namespace principia {
namespace numerics {
namespace frequency_analysis {
namespace internal_frequency_analysis {
using base::Error;
using base::Status;
using base::uninitialized;
using geometry::Hilbert;
using geometry::Vector;
using quantities::Inverse;
using quantities::IsFinite;
using quantities::Sqrt;
using quantities::Square;
using quantities::SquareRoot;
// Appends basis elements for |ω| to |basis| and |basis_subspaces|. Returns the
// number of elements that were appended.
template<int aperiodic_degree, int periodic_degree,
typename BasisSeries>
int MakeBasis(std::optional<AngularFrequency> const& ω,
Instant const& t_min,
Instant const& t_max,
std::vector<BasisSeries>& basis,
std::vector<PoissonSeriesSubspace>& basis_subspaces) {
if (ω.value() == AngularFrequency{}) {
using Generator =
PoissonSeriesBasisGenerator<BasisSeries, aperiodic_degree>;
auto const ω_basis = Generator::Basis(t_min, t_max);
auto const ω_basis_subspaces = Generator::Subspaces();
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
return std::tuple_size_v<decltype(ω_basis)>;
} else {
using Generator = PoissonSeriesBasisGenerator<BasisSeries, periodic_degree>;
auto const ω_basis = Generator::Basis(ω.value(), t_min, t_max);
auto const ω_basis_subspaces = Generator::Subspaces(ω.value());
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
return std::tuple_size_v<decltype(ω_basis)>;
}
}
//TODO(phl):comment
template<typename Function, typename BasisSeries,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
Status GramSchmidtStep(
Function const& aₘ,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree, Evaluator> const& weight,
Instant const& t_min,
Instant const& t_max,
std::vector<PoissonSeriesSubspace> const& basis_subspaces,
std::vector<BasisSeries> const& q,
BasisSeries& qₘ,
std::vector<double>& rₘ) {
// This code follows Björk, Numerics of Gram-Schmidt Orthogonalization,
// Algorithm 6.1. It processes one column of q and r at a time.
static constexpr double α = 0.5;
int const m = q.size();
rₘ.resize(m + 1, 0.0);
Function q̂ₘ = aₘ;
// Formal integration works for a single basis element.
double q̂ₘ_norm =
Sqrt((PointwiseInnerProduct(q̂ₘ, q̂ₘ) * weight).Integrate(t_min, t_max) /
(t_max - t_min));
// Loop on p.
Function previous_q̂ₘ = q̂ₘ;
double previous_q̂ₘ_norm;
do {
previous_q̂ₘ = q̂ₘ;
previous_q̂ₘ_norm = q̂ₘ_norm;
for (int i = 0; i < m; ++i) {
if (!PoissonSeriesSubspace::orthogonal(basis_subspaces[i],
basis_subspaces[m])) {
double const sᵖₘ =
InnerProduct(q[i], previous_q̂ₘ, weight, t_min, t_max);
q̂ₘ -= sᵖₘ * q[i];
rₘ[i] += sᵖₘ;
}
}
q̂ₘ_norm = q̂ₘ.Norm(weight, t_min, t_max);
if (!IsFinite(q̂ₘ_norm)) {
return Status(Error::OUT_OF_RANGE, u8"Unable to compute q̂ₘ_norm");
}
} while (q̂ₘ_norm < α * previous_q̂ₘ_norm);
// Fill the result.
qₘ = q̂ₘ / q̂ₘ_norm;
rₘ[m] = q̂ₘ_norm;
return Status::OK;
}
template<typename Function,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
AngularFrequency PreciseMode(
Interval<AngularFrequency> const& fft_mode,
Function const& function,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight) {
auto const weighted_function = weight * function;
auto const weighted_function_spectrum = weighted_function.FourierTransform();
auto power =
[&weighted_function_spectrum](AngularFrequency const& ω) {
return weighted_function_spectrum(ω).Norm²();
};
return Brent(power,
fft_mode.min,
fft_mode.max,
std::greater<>());
}
template<int aperiodic_degree, int periodic_degree,
typename Function,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
PoissonSeries<std::invoke_result_t<Function, Instant>,
aperiodic_degree, periodic_degree,
Evaluator>
Projection(Function const& function,
AngularFrequency const& ω,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight,
Instant const& t_min,
Instant const& t_max) {
std::optional<AngularFrequency> optional_ω = ω;
// A calculator that returns optional_ω once and then stops.
auto angular_frequency_calculator = [&optional_ω](auto const& residual) {
auto const result = optional_ω;
optional_ω = std::nullopt;
return result;
};
return IncrementalProjection<aperiodic_degree, periodic_degree>(
function,
angular_frequency_calculator,
weight,
t_min, t_max);
}
template<int aperiodic_degree, int periodic_degree,
typename Function,
typename AngularFrequencyCalculator,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
PoissonSeries<std::invoke_result_t<Function, Instant>,
aperiodic_degree, periodic_degree,
Evaluator>
IncrementalProjection(Function const& function,
AngularFrequencyCalculator const& calculator,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight,
Instant const& t_min,
Instant const& t_max) {
using Value = std::invoke_result_t<Function, Instant>;
using Norm = typename Hilbert<Value>::NormType;
using Normalized = typename Hilbert<Value>::NormalizedType;
using BasisSeries = PoissonSeries<Normalized,
aperiodic_degree, periodic_degree,
Evaluator>;
using ResultSeries = PoissonSeries<Value,
aperiodic_degree, periodic_degree,
Evaluator>;
Instant const& t0 = weight.origin();
auto const basis_zero = static_cast<
typename BasisSeries::AperiodicPolynomial>(
typename PoissonSeries<Normalized, 0, 0, Evaluator>::AperiodicPolynomial(
{Normalized{}}, t0));
auto const result_zero =
static_cast<typename ResultSeries::AperiodicPolynomial>(
typename PoissonSeries<Value, 0, 0, Evaluator>::AperiodicPolynomial(
{Value{}}, t0));
std::optional<AngularFrequency> ω = calculator(function);
CHECK(ω.has_value());
std::vector<BasisSeries> basis;
// The Poisson series basis[k] belongs to the subspace basis_subspaces[k];
// this remains true after orthonormalization, i.e., q[k] belongs to the
// subspace basis_subspaces[k] below.
std::vector<PoissonSeriesSubspace> basis_subspaces;
int basis_size = MakeBasis<aperiodic_degree, periodic_degree>(
ω, t_min, t_max, basis, basis_subspaces);
// This is logically Q in the QR decomposition of basis.
std::vector<BasisSeries> q;
// This is logically R in the QR decomposition of basis.
UnboundedUpperTriangularMatrix<double> r(basis_size); // Zero-initialized.
ResultSeries F(result_zero, {{}});
auto f = function - F;
int m_begin = 0;
for (;;) {
for (int m = m_begin; m < basis_size; ++m) {
BasisSeries qₘ(basis_zero, {{}});
std::vector<double> rₘ;
auto const status = GramSchmidtStep(
/*aₘ=*/basis[m], weight, t_min, t_max, basis_subspaces, q, qₘ, rₘ);
if (!status.ok()) {
return F;
}
q.push_back(qₘ);
DCHECK_EQ(m + 1, q.size());
Norm const Aₘ = InnerProduct(f, q[m], weight, t_min, t_max);
auto const Aₘqₘ = Aₘ * q[m];
f -= Aₘqₘ;
F += Aₘqₘ;
}
ω = calculator(f);
if (!ω.has_value()) {
return F;
}
int const ω_basis_size = MakeBasis<aperiodic_degree, periodic_degree>(
ω, t_min, t_max, basis, basis_subspaces);
m_begin = basis_size;
basis_size += ω_basis_size;
r.Extend(basis_size);
}
}
} // namespace internal_frequency_analysis
} // namespace frequency_analysis
} // namespace numerics
} // namespace principia
<commit_msg>Fill the QR decomposition.<commit_after>
#pragma once
#include "numerics/frequency_analysis.hpp"
#include <algorithm>
#include <functional>
#include <vector>
#include "base/status.hpp"
#include "base/tags.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/hilbert.hpp"
#include "numerics/poisson_series_basis.hpp"
#include "numerics/root_finders.hpp"
#include "numerics/unbounded_arrays.hpp"
#include "quantities/elementary_functions.hpp"
namespace principia {
namespace numerics {
namespace frequency_analysis {
namespace internal_frequency_analysis {
using base::Error;
using base::Status;
using base::uninitialized;
using geometry::Hilbert;
using geometry::Vector;
using quantities::Inverse;
using quantities::IsFinite;
using quantities::Sqrt;
using quantities::Square;
using quantities::SquareRoot;
// Appends basis elements for |ω| to |basis| and |basis_subspaces|. Returns the
// number of elements that were appended.
template<int aperiodic_degree, int periodic_degree,
typename BasisSeries>
int MakeBasis(std::optional<AngularFrequency> const& ω,
Instant const& t_min,
Instant const& t_max,
std::vector<BasisSeries>& basis,
std::vector<PoissonSeriesSubspace>& basis_subspaces) {
if (ω.value() == AngularFrequency{}) {
using Generator =
PoissonSeriesBasisGenerator<BasisSeries, aperiodic_degree>;
auto const ω_basis = Generator::Basis(t_min, t_max);
auto const ω_basis_subspaces = Generator::Subspaces();
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
return std::tuple_size_v<decltype(ω_basis)>;
} else {
using Generator = PoissonSeriesBasisGenerator<BasisSeries, periodic_degree>;
auto const ω_basis = Generator::Basis(ω.value(), t_min, t_max);
auto const ω_basis_subspaces = Generator::Subspaces(ω.value());
std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));
std::move(ω_basis_subspaces.begin(),
ω_basis_subspaces.end(),
std::back_inserter(basis_subspaces));
return std::tuple_size_v<decltype(ω_basis)>;
}
}
//TODO(phl):comment
template<typename Function, typename BasisSeries,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
Status GramSchmidtStep(
Function const& aₘ,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree, Evaluator> const& weight,
Instant const& t_min,
Instant const& t_max,
std::vector<PoissonSeriesSubspace> const& basis_subspaces,
std::vector<BasisSeries> const& q,
BasisSeries& qₘ,
std::vector<double>& rₘ) {
// This code follows Björk, Numerics of Gram-Schmidt Orthogonalization,
// Algorithm 6.1. It processes one column of q and r at a time.
static constexpr double α = 0.5;
int const m = q.size();
rₘ.resize(m + 1, 0.0);
Function q̂ₘ = aₘ;
// Formal integration works for a single basis element.
double q̂ₘ_norm =
Sqrt((PointwiseInnerProduct(q̂ₘ, q̂ₘ) * weight).Integrate(t_min, t_max) /
(t_max - t_min));
// Loop on p.
Function previous_q̂ₘ = q̂ₘ;
double previous_q̂ₘ_norm;
do {
previous_q̂ₘ = q̂ₘ;
previous_q̂ₘ_norm = q̂ₘ_norm;
for (int i = 0; i < m; ++i) {
if (!PoissonSeriesSubspace::orthogonal(basis_subspaces[i],
basis_subspaces[m])) {
double const sᵖₘ =
InnerProduct(q[i], previous_q̂ₘ, weight, t_min, t_max);
q̂ₘ -= sᵖₘ * q[i];
rₘ[i] += sᵖₘ;
}
}
q̂ₘ_norm = q̂ₘ.Norm(weight, t_min, t_max);
if (!IsFinite(q̂ₘ_norm)) {
return Status(Error::OUT_OF_RANGE, u8"Unable to compute q̂ₘ_norm");
}
} while (q̂ₘ_norm < α * previous_q̂ₘ_norm);
// Fill the result.
qₘ = q̂ₘ / q̂ₘ_norm;
rₘ[m] = q̂ₘ_norm;
return Status::OK;
}
template<typename Function,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
AngularFrequency PreciseMode(
Interval<AngularFrequency> const& fft_mode,
Function const& function,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight) {
auto const weighted_function = weight * function;
auto const weighted_function_spectrum = weighted_function.FourierTransform();
auto power =
[&weighted_function_spectrum](AngularFrequency const& ω) {
return weighted_function_spectrum(ω).Norm²();
};
return Brent(power,
fft_mode.min,
fft_mode.max,
std::greater<>());
}
template<int aperiodic_degree, int periodic_degree,
typename Function,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
PoissonSeries<std::invoke_result_t<Function, Instant>,
aperiodic_degree, periodic_degree,
Evaluator>
Projection(Function const& function,
AngularFrequency const& ω,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight,
Instant const& t_min,
Instant const& t_max) {
std::optional<AngularFrequency> optional_ω = ω;
// A calculator that returns optional_ω once and then stops.
auto angular_frequency_calculator = [&optional_ω](auto const& residual) {
auto const result = optional_ω;
optional_ω = std::nullopt;
return result;
};
return IncrementalProjection<aperiodic_degree, periodic_degree>(
function,
angular_frequency_calculator,
weight,
t_min, t_max);
}
template<int aperiodic_degree, int periodic_degree,
typename Function,
typename AngularFrequencyCalculator,
int aperiodic_wdegree, int periodic_wdegree,
template<typename, typename, int> class Evaluator>
PoissonSeries<std::invoke_result_t<Function, Instant>,
aperiodic_degree, periodic_degree,
Evaluator>
IncrementalProjection(Function const& function,
AngularFrequencyCalculator const& calculator,
PoissonSeries<double,
aperiodic_wdegree, periodic_wdegree,
Evaluator> const& weight,
Instant const& t_min,
Instant const& t_max) {
using Value = std::invoke_result_t<Function, Instant>;
using Norm = typename Hilbert<Value>::NormType;
using Normalized = typename Hilbert<Value>::NormalizedType;
using BasisSeries = PoissonSeries<Normalized,
aperiodic_degree, periodic_degree,
Evaluator>;
using ResultSeries = PoissonSeries<Value,
aperiodic_degree, periodic_degree,
Evaluator>;
Instant const& t0 = weight.origin();
auto const basis_zero = static_cast<
typename BasisSeries::AperiodicPolynomial>(
typename PoissonSeries<Normalized, 0, 0, Evaluator>::AperiodicPolynomial(
{Normalized{}}, t0));
auto const result_zero =
static_cast<typename ResultSeries::AperiodicPolynomial>(
typename PoissonSeries<Value, 0, 0, Evaluator>::AperiodicPolynomial(
{Value{}}, t0));
std::optional<AngularFrequency> ω = calculator(function);
CHECK(ω.has_value());
std::vector<BasisSeries> basis;
// The Poisson series basis[k] belongs to the subspace basis_subspaces[k];
// this remains true after orthonormalization, i.e., q[k] belongs to the
// subspace basis_subspaces[k] below.
std::vector<PoissonSeriesSubspace> basis_subspaces;
int basis_size = MakeBasis<aperiodic_degree, periodic_degree>(
ω, t_min, t_max, basis, basis_subspaces);
// This is logically Q in the QR decomposition of basis.
std::vector<BasisSeries> q;
// This is logically R in the QR decomposition of basis.
UnboundedUpperTriangularMatrix<double> r(basis_size, uninitialized);
ResultSeries F(result_zero, {{}});
auto f = function - F;
int m_begin = 0;
for (;;) {
for (int m = m_begin; m < basis_size; ++m) {
BasisSeries qₘ(basis_zero, {{}});
std::vector<double> rₘ;
auto const status = GramSchmidtStep(
/*aₘ=*/basis[m], weight, t_min, t_max, basis_subspaces, q, qₘ, rₘ);
if (!status.ok()) {
return F;
}
for (int i = 0; i <=m; ++i) {
r[i][m] = rₘ[i];
}
q.push_back(qₘ);
DCHECK_EQ(m + 1, q.size());
Norm const Aₘ = InnerProduct(f, q[m], weight, t_min, t_max);
auto const Aₘqₘ = Aₘ * q[m];
f -= Aₘqₘ;
F += Aₘqₘ;
}
ω = calculator(f);
if (!ω.has_value()) {
return F;
}
int const ω_basis_size = MakeBasis<aperiodic_degree, periodic_degree>(
ω, t_min, t_max, basis, basis_subspaces);
m_begin = basis_size;
basis_size += ω_basis_size;
r.Extend(basis_size, uninitialized);
}
}
} // namespace internal_frequency_analysis
} // namespace frequency_analysis
} // namespace numerics
} // namespace principia
<|endoftext|>
|
<commit_before>#ifndef PARAMETERHANDLER_HH_INCLUDED
#define PARAMETERHANDLER_HH_INCLUDED
#include <fstream>
#include <ostream>
#include <map>
/**
* \brief class processing parameter file
*
* \c ParameterHandler reads a parameter file once and stores all found values internally
**/
class ParameterHandler
{
private:
typedef std::map< std::string, std::string > MapType;
MapType parameter_map_;
bool status_;
public:
/** \ Please doc me!
*
**/
ParameterHandler( const std::string filename )
:status_( false )
{
ParseParamFile( filename );
}
ParameterHandler( )
:status_( false )
{
}
/** \brief function used for parametrized ctor and two-step creation
**/
bool ParseParamFile( const std::string filename )
{
std::ifstream parameter_file( filename.c_str() );
if( parameter_file.is_open() )
{
while( !parameter_file.eof() )
{
std :: string line;
std :: getline( parameter_file, line );
if( line.size() == 0 )
continue;
if( (line[ 0 ] != '%') && (line[ 0 ] != '#') )
{
std::string param_name = line.substr( 0, line.find_first_of(":") );
std::string value = line.substr( line.find_first_of(":")+1, line.length() );
parameter_map_[param_name] = value;
}
}
status_ = true;
parameter_file.close();
}
else {
//LOGERROR
status_ = false;
std::cerr << "ERROR: file " << filename << " not found!\n";
}
return Ok();
}
/**
* \brief checks, if a parameter is found in the parameterfile
* \arg const std::string name name of the parameter to be found
* \return returns true, if the parameter is found
**/
bool ParameterExists( const std::string name ) const
{
if ( !( status_ ) ) {
return false;
}
else {
MapType::const_iterator it = parameter_map_.find( name );
if ( it != parameter_map_.end() ) {
return true;
}
else {
return false;
}
}
}
/** \todo Please doc me! */
template < class ReturnType >
ReturnType GetParameter( const std::string name) const
{
if ( !( status_ ) ) {
return (ReturnType) 0;
}
else {
MapType::const_iterator it = parameter_map_.find( name ) ;
if ( it != parameter_map_.end() ){
return Stuff::fromString<ReturnType>( it->second );
}
else {
//LogError
return (ReturnType) 0;
}
}
}
/** \todo Please doc me! */
void Print( std::ostream &out ) const
{
assert( status_ );
for (MapType::const_iterator it = parameter_map_.begin(); parameter_map_.end() != it; ++it){
out << it->first << ":" << it->second << "\n" ;
}
out << std::endl;
}
/** \todo Please doc me! */
bool Ok()
{
return status_;
}
/** \todo Please doc me! */
~ParameterHandler(){}
};
///** \brief global singelton for paramhandler
ParameterHandler& params()
{
static ParameterHandler param;
return param;
}
#endif // PARAMETERHANDLER_HH_INCLUDED
<commit_msg>remove obsolete file<commit_after><|endoftext|>
|
<commit_before>#ifndef CLOVER_UTIL_PROFILING_HPP
#define CLOVER_UTIL_PROFILING_HPP
#include "build.hpp"
#include "util/preproc_join.hpp"
#include <thread>
// No profiling on windows due to odd crashes with mingw 4.8.2
#define PROFILING_ENABLED (ATOMIC_PTR_READWRITE == true && OS != OS_WINDOWS)
namespace clover {
namespace util {
namespace detail {
struct BlockInfo {
const char* funcName;
uint32 line;
/// Don't assume that labels with same string will point to
/// the same memory - depends on compiler optimizations
const char* label;
uint64 exclusiveMemAllocs;
uint64 inclusiveMemAllocs;
};
struct BlockProfiler {
static BlockInfo createBlockInfo( const char* func,
uint32 line,
const char* label);
BlockProfiler(BlockInfo& info);
~BlockProfiler();
};
struct StackJoiner {
StackJoiner();
~StackJoiner();
};
struct StackDetacher {
StackDetacher();
~StackDetacher();
};
void setSuperThread(std::thread::id super_id);
} // detail
/// Call in main() -- we don't want to see any impl defined pre-main stuff
void tryEnableProfiling();
#if PROFILING_ENABLED
/// Should be called on system memory allocation
void profileSystemMemAlloc();
#else
void profileSystemMemAlloc() {};
#endif
} // util
} // clover
#if PROFILING_ENABLED
/// Same as PROFILE but with a label
#define PROFILE_(label)\
static util::detail::BlockInfo JOIN(profiler_block_info_, __LINE__)= \
util::detail::BlockProfiler::createBlockInfo( \
__PRETTY_FUNCTION__, \
__LINE__, \
label); \
util::detail::BlockProfiler JOIN(profiler_, __LINE__)(JOIN(profiler_block_info_, __LINE__))
/// Marks current block to be profiled
#define PROFILE()\
PROFILE_(nullptr)
/// Notifies profiler of a super thread
#define PROFILER_SUPER_THREAD(thread_id)\
util::detail::setSuperThread(thread_id)
/// Joins callstacks of this and super thread in current scope
#define PROFILER_STACK_JOIN()\
util::detail::StackJoiner JOIN(stack_joiner_, __LINE__)
/// Detaches callstacks of this and super thread in current scope
#define PROFILER_STACK_DETACH()\
util::detail::StackDetacher JOIN(stack_detacher_, __LINE__)
#else
#define PROFILE_(label)
#define PROFILE()
#define PROFILER_SUPER_THREAD(thread_id)
#define PROFILER_STACK_JOIN()
#define PROFILER_STACK_DETACH()
#endif
#endif // CLOVER_UTIL_PROFILING_HPP
<commit_msg>Profiling is now working on windows?!<commit_after>#ifndef CLOVER_UTIL_PROFILING_HPP
#define CLOVER_UTIL_PROFILING_HPP
#include "build.hpp"
#include "util/preproc_join.hpp"
#include <thread>
// No profiling on windows due to odd crashes with mingw 4.8.2
#define PROFILING_ENABLED (ATOMIC_PTR_READWRITE == true)
namespace clover {
namespace util {
namespace detail {
struct BlockInfo {
const char* funcName;
uint32 line;
/// Don't assume that labels with same string will point to
/// the same memory - depends on compiler optimizations
const char* label;
uint64 exclusiveMemAllocs;
uint64 inclusiveMemAllocs;
};
struct BlockProfiler {
static BlockInfo createBlockInfo( const char* func,
uint32 line,
const char* label);
BlockProfiler(BlockInfo& info);
~BlockProfiler();
};
struct StackJoiner {
StackJoiner();
~StackJoiner();
};
struct StackDetacher {
StackDetacher();
~StackDetacher();
};
void setSuperThread(std::thread::id super_id);
} // detail
/// Call in main() -- we don't want to see any impl defined pre-main stuff
void tryEnableProfiling();
#if PROFILING_ENABLED
/// Should be called on system memory allocation
void profileSystemMemAlloc();
#else
void profileSystemMemAlloc() {};
#endif
} // util
} // clover
#if PROFILING_ENABLED
/// Same as PROFILE but with a label
#define PROFILE_(label)\
static util::detail::BlockInfo JOIN(profiler_block_info_, __LINE__)= \
util::detail::BlockProfiler::createBlockInfo( \
__PRETTY_FUNCTION__, \
__LINE__, \
label); \
util::detail::BlockProfiler JOIN(profiler_, __LINE__)(JOIN(profiler_block_info_, __LINE__))
/// Marks current block to be profiled
#define PROFILE()\
PROFILE_(nullptr)
/// Notifies profiler of a super thread
#define PROFILER_SUPER_THREAD(thread_id)\
util::detail::setSuperThread(thread_id)
/// Joins callstacks of this and super thread in current scope
#define PROFILER_STACK_JOIN()\
util::detail::StackJoiner JOIN(stack_joiner_, __LINE__)
/// Detaches callstacks of this and super thread in current scope
#define PROFILER_STACK_DETACH()\
util::detail::StackDetacher JOIN(stack_detacher_, __LINE__)
#else
#define PROFILE_(label)
#define PROFILE()
#define PROFILER_SUPER_THREAD(thread_id)
#define PROFILER_STACK_JOIN()
#define PROFILER_STACK_DETACH()
#endif
#endif // CLOVER_UTIL_PROFILING_HPP
<|endoftext|>
|
<commit_before>#include <Refal2.h>
namespace Refal2 {
//-----------------------------------------------------------------------------
// CProgram
CProgram::CProgram( int numberOfModules ) :
modulesSize( numberOfModules ),
modules( new CRuntimeModule[modulesSize] ),
emptyFunction( new CEmptyFunction )
{
assert( modulesSize > 0 );
assert( modules != nullptr );
}
CProgram::~CProgram()
{
delete[] modules;
}
CRuntimeModule& CProgram::Module( TRuntimeModuleId moduleId )
{
assert( moduleId >= 0 && moduleId < modulesSize );
return modules[moduleId];
}
//-----------------------------------------------------------------------------
// CProgramPrintHelper
void CProgramPrintHelper::Label( std::ostream& outputStream,
const TLabel label ) const
{
const int labelModuleId = label / LabelMask;
if( PrintLabelWithModule() ) {
outputStream << labelModuleId << ":";
}
outputStream << program->Module( labelModuleId ).Functions.
GetKey( label % LabelMask );
}
//-----------------------------------------------------------------------------
// CGlobalFunctionData
class CGlobalFunctionData {
public:
CGlobalFunctionData();
bool IsEmbeddedFunction() const;
bool IsPreparatoryFunction() const;
bool IsDefined() const;
void SetPreparatoryFunction(
const CPreparatoryFunction* const _preparatoryFunction,
const TRuntimeModuleId _runtimeModuleId );
const CPreparatoryFunction* PreparatoryFunction() const;
const TRuntimeModuleId RuntimeModuleId() const;
void SetEmbeddedFunction( const TEmbeddedFunctionPtr _embeddedFunction );
TEmbeddedFunctionPtr EmbeddedFunction() const;
CRuntimeFunctionPtr RuntimeFunction( const CProgramPtr& program ) const;
private:
const CPreparatoryFunction* preparatoryFunction;
TEmbeddedFunctionPtr embeddedFunction;
TRuntimeModuleId runtimeModuleId;
mutable CRuntimeFunctionPtr runtimeFunction;
};
//-----------------------------------------------------------------------------
// CGlobalFunctionData
CGlobalFunctionData::CGlobalFunctionData() :
preparatoryFunction( nullptr ),
embeddedFunction( nullptr ),
runtimeModuleId( 0 )
{
}
bool CGlobalFunctionData::IsEmbeddedFunction() const
{
return ( embeddedFunction != nullptr );
}
bool CGlobalFunctionData::IsPreparatoryFunction() const
{
return ( preparatoryFunction != nullptr );
}
bool CGlobalFunctionData::IsDefined() const
{
return ( IsEmbeddedFunction() || IsPreparatoryFunction() );
}
void CGlobalFunctionData::SetPreparatoryFunction(
const CPreparatoryFunction* const _preparatoryFunction,
const TRuntimeModuleId _runtimeModuleId )
{
assert( !IsDefined() );
assert( _preparatoryFunction != nullptr );
preparatoryFunction = _preparatoryFunction;
runtimeModuleId = _runtimeModuleId;
}
const CPreparatoryFunction* CGlobalFunctionData::PreparatoryFunction() const
{
assert( IsPreparatoryFunction() );
return preparatoryFunction;
}
const TRuntimeModuleId CGlobalFunctionData::RuntimeModuleId() const
{
assert( IsPreparatoryFunction() );
return runtimeModuleId;
}
void CGlobalFunctionData::SetEmbeddedFunction(
const TEmbeddedFunctionPtr _embeddedFunction )
{
assert( !IsDefined() );
assert( _embeddedFunction != nullptr );
embeddedFunction = _embeddedFunction;
}
TEmbeddedFunctionPtr CGlobalFunctionData::EmbeddedFunction() const
{
assert( IsEmbeddedFunction() );
return embeddedFunction;
}
CRuntimeFunctionPtr CGlobalFunctionData::RuntimeFunction(
const CProgramPtr& program ) const
{
if( !static_cast<bool>( runtimeFunction ) ) {
if( IsEmbeddedFunction() ) {
runtimeFunction.reset( new CEmbeddedFunction(
embeddedFunction ) );
} else {
assert( IsPreparatoryFunction() );
if( PreparatoryFunction()->IsEmpty() ) {
runtimeFunction = program->EmptyFunction();
} else {
runtimeFunction.reset( new COrdinaryFunction(
PreparatoryFunction()->FirstOperation(),
RuntimeModuleId() ) );
}
}
}
return runtimeFunction;
}
//-----------------------------------------------------------------------------
// CInternalProgramBuilder
const char* const ProgramStartFunctionName = "go";
class CInternalProgramBuilder {
public:
static CProgramPtr Build( CModuleDataVector& modules,
CErrorsHelper& errors );
private:
CErrorsHelper& errors;
CDictionary<CGlobalFunctionData, std::string> globals;
CProgramPtr program;
CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules );
typedef void ( CInternalProgramBuilder::*TProcessFunctionPtr )(
CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId );
void processModules( const CModuleDataVector& modules,
const TProcessFunctionPtr processFunction );
void collectFunction( CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId );
void collect( const CModuleDataVector& modules );
void check();
void compileFunction( CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId );
void compile( const CModuleDataVector& modules );
void linkFunction( CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId );
void link( const CModuleDataVector& modules );
};
//-----------------------------------------------------------------------------
CInternalProgramBuilder::CInternalProgramBuilder( CErrorsHelper& _errors,
int numberOfModules ) :
errors( _errors ),
program( new CProgram( numberOfModules ) )
{
assert( static_cast<bool>( program ) );
// add standart functions
for( const CEmbeddedFunctionData* function = EmbeddedFunctionDataTable();
function->EmbeddedFunction != nullptr; function++ )
{
assert( function->ExternalName != nullptr );
std::string externalName = function->ExternalName;
assert( !externalName.empty() );
const int globalIndex = globals.AddKey( externalName );
CGlobalFunctionData& global = globals.GetData( globalIndex );
global.SetEmbeddedFunction( function->EmbeddedFunction );
}
// add `ProgramStartFunctionName`
const int globalGoIndex = globals.AddKey( ProgramStartFunctionName );
assert( !globals.GetData( globalGoIndex ).IsDefined() );
}
CProgramPtr CInternalProgramBuilder::Build( CModuleDataVector& modules,
CErrorsHelper& errors )
{
assert( !errors.HasErrors() );
assert( !modules.empty() );
CInternalProgramBuilder builder( errors, modules.size() );
builder.collect( modules );
if( !errors.HasErrors() ) {
builder.check();
if( !errors.HasErrors() ) {
builder.compile( modules );
assert( !errors.HasErrors() );
builder.link( modules );
assert( !errors.HasErrors() );
return builder.program;
}
}
modules.clear();
return nullptr;
}
void CInternalProgramBuilder::processModules( const CModuleDataVector& modules,
const TProcessFunctionPtr processFunction )
{
TRuntimeModuleId currentModuleId = 0;
for( CModuleDataVector::const_iterator module = modules.begin();
module != modules.end(); ++module )
{
const CPreparatoryFunctions& functions = ( *module )->Functions;
for( int i = 0; i < functions.Size(); i++ ) {
( this->*processFunction )( functions.GetData( i ).get(),
currentModuleId );
}
currentModuleId++;
}
}
void CInternalProgramBuilder::collectFunction( CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId )
{
if( !function->IsExternal() && !function->IsEntry() ) {
return;
}
const int globalIndex = globals.AddKey( function->ExternalName() );
if( function->IsEntry() ) {
assert( !function->IsExternal() );
CGlobalFunctionData& global = globals.GetData( globalIndex );
if( global.IsDefined() ) {
std::ostringstream stringStream;
stringStream << "function with external name `"
<< function->ExternalNameToken().word
<< "` already defined in program";
errors.RaiseError( ES_LinkError, stringStream.str() );
} else {
global.SetPreparatoryFunction( function, runtimeModuleId );
}
}
}
void CInternalProgramBuilder::collect( const CModuleDataVector& modules )
{
processModules( modules, &CInternalProgramBuilder::collectFunction );
}
void CInternalProgramBuilder::check()
{
for( int globalIndex = 0; globalIndex < globals.Size(); globalIndex++ )
{
if( !globals.GetData( globalIndex ).IsDefined() ) {
std::ostringstream stringStream;
stringStream << "function with external name `"
<< globals.GetKey( globalIndex ) << "` was not defined";
errors.RaiseError( ES_LinkError, stringStream.str() );
}
}
}
void CInternalProgramBuilder::compileFunction( CPreparatoryFunction* function,
const TRuntimeModuleId /*runtimeModuleId*/ )
{
CFunctionCompiler compiler( program->OperationsHolder() );
if( function->IsOrdinary() ) {
DEBUG_PRINT( __FUNCTION__ << " " << function->Name() )
function->Compile( compiler );
}
}
void CInternalProgramBuilder::compile( const CModuleDataVector& modules )
{
processModules( modules, &CInternalProgramBuilder::compileFunction );
}
void CInternalProgramBuilder::linkFunction( CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId )
{
CRuntimeFunctions& functions = program->Module( runtimeModuleId ).Functions;
const int functionKey = functions.AddKey( function->Name() );
CRuntimeFunctionPtr& runtimeFunction = functions.GetData( functionKey );
assert( !static_cast<bool>( runtimeFunction ) );
switch( function->GetType() ) {
case PFT_Empty:
runtimeFunction = program->EmptyFunction();
break;
case PFT_Compiled:
runtimeFunction.reset( new COrdinaryFunction(
function->FirstOperation(), runtimeModuleId ) );
break;
case PFT_External:
{
const int globalIndex = globals.FindKey( function->ExternalName() );
assert( globalIndex != InvalidDictionaryIndex );
const CGlobalFunctionData& global = globals.GetData( globalIndex );
runtimeFunction = global.RuntimeFunction( program );
break;
}
default:
assert( false );
break;
}
}
void CInternalProgramBuilder::link( const CModuleDataVector& modules )
{
const CGlobalFunctionData& goFunction = globals.GetData( globals.FindKey(
ProgramStartFunctionName ) );
TOperationAddress goFirstOperation =
goFunction.PreparatoryFunction()->FirstOperation();
TRuntimeModuleId goRuntimeModuleId = goFunction.RuntimeModuleId();
// link all
processModules( modules, &CInternalProgramBuilder::linkFunction );
// set program start function
const CRuntimeFunctions& runtimeFunctions =
program->Module( goRuntimeModuleId ).Functions;
TLabel goLabel = InvalidDictionaryIndex;
for( int i = 0; i < runtimeFunctions.Size(); i++ ) {
if( runtimeFunctions.GetData( i )->IsOrdinary()
&& static_cast<const COrdinaryFunction*>(
runtimeFunctions.GetData( i ).get() )->FirstOperation() ==
goFirstOperation )
{
goLabel = i;
}
}
assert( goLabel != InvalidDictionaryIndex );
program->SetProgramStartFunction( goLabel + goRuntimeModuleId * LabelMask );
}
//-----------------------------------------------------------------------------
// CProgramBuilder
CProgramBuilder::CProgramBuilder( IErrorHandler* errorHandler ) :
CFunctionBuilder( errorHandler )
{
Reset();
}
void CProgramBuilder::Reset()
{
CFunctionBuilder::Reset();
}
void CProgramBuilder::AddModule( CModuleDataPtr& module )
{
modules.push_back( CModuleDataPtr( module.release() ) );
}
CProgramPtr CProgramBuilder::BuildProgram()
{
return CInternalProgramBuilder::Build( modules, *this );
}
//-----------------------------------------------------------------------------
} // end of namespace Refal2
<commit_msg>bug fixes<commit_after>#include <Refal2.h>
namespace Refal2 {
//-----------------------------------------------------------------------------
// CProgram
CProgram::CProgram( int numberOfModules ) :
modulesSize( numberOfModules ),
modules( new CRuntimeModule[modulesSize] ),
emptyFunction( new CEmptyFunction )
{
assert( modulesSize > 0 );
assert( modules != nullptr );
}
CProgram::~CProgram()
{
delete[] modules;
}
CRuntimeModule& CProgram::Module( TRuntimeModuleId moduleId )
{
assert( moduleId >= 0 && moduleId < modulesSize );
return modules[moduleId];
}
//-----------------------------------------------------------------------------
// CProgramPrintHelper
void CProgramPrintHelper::Label( std::ostream& outputStream,
const TLabel label ) const
{
const int labelModuleId = label / LabelMask;
if( PrintLabelWithModule() ) {
outputStream << labelModuleId << ":";
}
outputStream << program->Module( labelModuleId ).Functions.
GetKey( label % LabelMask );
}
//-----------------------------------------------------------------------------
// CGlobalFunctionData
class CGlobalFunctionData {
public:
CGlobalFunctionData();
bool IsEmbeddedFunction() const;
bool IsPreparatoryFunction() const;
bool IsDefined() const;
void SetPreparatoryFunction(
const CPreparatoryFunction* const _preparatoryFunction,
const TRuntimeModuleId _runtimeModuleId );
const CPreparatoryFunction* PreparatoryFunction() const;
const TRuntimeModuleId RuntimeModuleId() const;
void SetEmbeddedFunction( const TEmbeddedFunctionPtr _embeddedFunction );
TEmbeddedFunctionPtr EmbeddedFunction() const;
CRuntimeFunctionPtr RuntimeFunction( const CProgramPtr& program ) const;
private:
const CPreparatoryFunction* preparatoryFunction;
TEmbeddedFunctionPtr embeddedFunction;
TRuntimeModuleId runtimeModuleId;
mutable CRuntimeFunctionPtr runtimeFunction;
};
//-----------------------------------------------------------------------------
// CGlobalFunctionData
CGlobalFunctionData::CGlobalFunctionData() :
preparatoryFunction( nullptr ),
embeddedFunction( nullptr ),
runtimeModuleId( 0 )
{
}
bool CGlobalFunctionData::IsEmbeddedFunction() const
{
return ( embeddedFunction != nullptr );
}
bool CGlobalFunctionData::IsPreparatoryFunction() const
{
return ( preparatoryFunction != nullptr );
}
bool CGlobalFunctionData::IsDefined() const
{
return ( IsEmbeddedFunction() || IsPreparatoryFunction() );
}
void CGlobalFunctionData::SetPreparatoryFunction(
const CPreparatoryFunction* const _preparatoryFunction,
const TRuntimeModuleId _runtimeModuleId )
{
assert( !IsDefined() );
assert( _preparatoryFunction != nullptr );
preparatoryFunction = _preparatoryFunction;
runtimeModuleId = _runtimeModuleId;
}
const CPreparatoryFunction* CGlobalFunctionData::PreparatoryFunction() const
{
assert( IsPreparatoryFunction() );
return preparatoryFunction;
}
const TRuntimeModuleId CGlobalFunctionData::RuntimeModuleId() const
{
assert( IsPreparatoryFunction() );
return runtimeModuleId;
}
void CGlobalFunctionData::SetEmbeddedFunction(
const TEmbeddedFunctionPtr _embeddedFunction )
{
assert( !IsDefined() );
assert( _embeddedFunction != nullptr );
embeddedFunction = _embeddedFunction;
}
TEmbeddedFunctionPtr CGlobalFunctionData::EmbeddedFunction() const
{
assert( IsEmbeddedFunction() );
return embeddedFunction;
}
CRuntimeFunctionPtr CGlobalFunctionData::RuntimeFunction(
const CProgramPtr& program ) const
{
if( !static_cast<bool>( runtimeFunction ) ) {
if( IsEmbeddedFunction() ) {
runtimeFunction.reset( new CEmbeddedFunction(
embeddedFunction ) );
} else {
assert( IsPreparatoryFunction() );
if( PreparatoryFunction()->IsEmpty() ) {
runtimeFunction = program->EmptyFunction();
} else {
runtimeFunction.reset( new COrdinaryFunction(
PreparatoryFunction()->FirstOperation(),
RuntimeModuleId() ) );
}
}
}
return runtimeFunction;
}
//-----------------------------------------------------------------------------
// CInternalProgramBuilder
const char* const ProgramStartFunctionName = "go";
class CInternalProgramBuilder {
public:
static CProgramPtr Build( CModuleDataVector& modules,
CErrorsHelper& errors );
private:
CErrorsHelper& errors;
CDictionary<CGlobalFunctionData, std::string> globals;
CProgramPtr program;
CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules );
typedef void ( CInternalProgramBuilder::*TProcessFunctionPtr )(
CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId );
void processModules( const CModuleDataVector& modules,
const TProcessFunctionPtr processFunction );
void collectFunction( CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId );
void collect( const CModuleDataVector& modules );
void check();
void compileFunction( CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId );
void compile( const CModuleDataVector& modules );
void linkFunction( CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId );
void link( const CModuleDataVector& modules );
};
//-----------------------------------------------------------------------------
CInternalProgramBuilder::CInternalProgramBuilder( CErrorsHelper& _errors,
int numberOfModules ) :
errors( _errors ),
program( new CProgram( numberOfModules ) )
{
assert( static_cast<bool>( program ) );
// add standart functions
for( const CEmbeddedFunctionData* function = EmbeddedFunctionDataTable();
function->EmbeddedFunction != nullptr; function++ )
{
assert( function->ExternalName != nullptr );
std::string externalName = function->ExternalName;
assert( !externalName.empty() );
const int globalIndex = globals.AddKey( externalName );
CGlobalFunctionData& global = globals.GetData( globalIndex );
global.SetEmbeddedFunction( function->EmbeddedFunction );
}
// add `ProgramStartFunctionName`
const int globalGoIndex = globals.AddKey( ProgramStartFunctionName );
assert( !globals.GetData( globalGoIndex ).IsDefined() );
}
CProgramPtr CInternalProgramBuilder::Build( CModuleDataVector& modules,
CErrorsHelper& errors )
{
if( !errors.HasErrors() && !modules.empty() ) {
CInternalProgramBuilder builder( errors, modules.size() );
builder.collect( modules );
if( !errors.HasErrors() ) {
builder.check();
if( !errors.HasErrors() ) {
builder.compile( modules );
assert( !errors.HasErrors() );
builder.link( modules );
assert( !errors.HasErrors() );
return builder.program;
}
}
}
modules.clear();
return nullptr;
}
void CInternalProgramBuilder::processModules( const CModuleDataVector& modules,
const TProcessFunctionPtr processFunction )
{
TRuntimeModuleId currentModuleId = 0;
for( CModuleDataVector::const_iterator module = modules.begin();
module != modules.end(); ++module )
{
const CPreparatoryFunctions& functions = ( *module )->Functions;
for( int i = 0; i < functions.Size(); i++ ) {
( this->*processFunction )( functions.GetData( i ).get(),
currentModuleId );
}
currentModuleId++;
}
}
void CInternalProgramBuilder::collectFunction( CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId )
{
if( !function->IsExternal() && !function->IsEntry() ) {
return;
}
const int globalIndex = globals.AddKey( function->ExternalName() );
if( function->IsEntry() ) {
assert( !function->IsExternal() );
CGlobalFunctionData& global = globals.GetData( globalIndex );
if( global.IsDefined() ) {
std::ostringstream stringStream;
stringStream << "function with external name `"
<< function->ExternalNameToken().word
<< "` already defined in program";
errors.RaiseError( ES_LinkError, stringStream.str() );
} else {
global.SetPreparatoryFunction( function, runtimeModuleId );
}
}
}
void CInternalProgramBuilder::collect( const CModuleDataVector& modules )
{
processModules( modules, &CInternalProgramBuilder::collectFunction );
}
void CInternalProgramBuilder::check()
{
for( int globalIndex = 0; globalIndex < globals.Size(); globalIndex++ )
{
if( !globals.GetData( globalIndex ).IsDefined() ) {
std::ostringstream stringStream;
stringStream << "function with external name `"
<< globals.GetKey( globalIndex ) << "` was not defined";
errors.RaiseError( ES_LinkError, stringStream.str() );
}
}
}
void CInternalProgramBuilder::compileFunction( CPreparatoryFunction* function,
const TRuntimeModuleId /*runtimeModuleId*/ )
{
CFunctionCompiler compiler( program->OperationsHolder() );
if( function->IsOrdinary() ) {
DEBUG_PRINT( __FUNCTION__ << " " << function->Name() )
function->Compile( compiler );
}
}
void CInternalProgramBuilder::compile( const CModuleDataVector& modules )
{
processModules( modules, &CInternalProgramBuilder::compileFunction );
}
void CInternalProgramBuilder::linkFunction( CPreparatoryFunction* function,
const TRuntimeModuleId runtimeModuleId )
{
CRuntimeFunctions& functions = program->Module( runtimeModuleId ).Functions;
const int functionKey = functions.AddKey( function->Name() );
CRuntimeFunctionPtr& runtimeFunction = functions.GetData( functionKey );
assert( !static_cast<bool>( runtimeFunction ) );
switch( function->GetType() ) {
case PFT_Empty:
runtimeFunction = program->EmptyFunction();
break;
case PFT_Compiled:
runtimeFunction.reset( new COrdinaryFunction(
function->FirstOperation(), runtimeModuleId ) );
break;
case PFT_External:
{
const int globalIndex = globals.FindKey( function->ExternalName() );
assert( globalIndex != InvalidDictionaryIndex );
const CGlobalFunctionData& global = globals.GetData( globalIndex );
runtimeFunction = global.RuntimeFunction( program );
break;
}
default:
assert( false );
break;
}
}
void CInternalProgramBuilder::link( const CModuleDataVector& modules )
{
const CGlobalFunctionData& goFunction = globals.GetData( globals.FindKey(
ProgramStartFunctionName ) );
TOperationAddress goFirstOperation =
goFunction.PreparatoryFunction()->FirstOperation();
TRuntimeModuleId goRuntimeModuleId = goFunction.RuntimeModuleId();
// link all
processModules( modules, &CInternalProgramBuilder::linkFunction );
// set program start function
const CRuntimeFunctions& runtimeFunctions =
program->Module( goRuntimeModuleId ).Functions;
TLabel goLabel = InvalidDictionaryIndex;
for( int i = 0; i < runtimeFunctions.Size(); i++ ) {
if( runtimeFunctions.GetData( i )->IsOrdinary()
&& static_cast<const COrdinaryFunction*>(
runtimeFunctions.GetData( i ).get() )->FirstOperation() ==
goFirstOperation )
{
goLabel = i;
}
}
assert( goLabel != InvalidDictionaryIndex );
program->SetProgramStartFunction( goLabel + goRuntimeModuleId * LabelMask );
}
//-----------------------------------------------------------------------------
// CProgramBuilder
CProgramBuilder::CProgramBuilder( IErrorHandler* errorHandler ) :
CFunctionBuilder( errorHandler )
{
Reset();
}
void CProgramBuilder::Reset()
{
CFunctionBuilder::Reset();
}
void CProgramBuilder::AddModule( CModuleDataPtr& module )
{
modules.push_back( CModuleDataPtr( module.release() ) );
}
CProgramPtr CProgramBuilder::BuildProgram()
{
return CInternalProgramBuilder::Build( modules, *this );
}
//-----------------------------------------------------------------------------
} // end of namespace Refal2
<|endoftext|>
|
<commit_before>#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "filelib.h"
#include "stringlib.h"
#include "sparse_vector.h"
#include "scorer.h"
#include "viterbi_envelope.h"
#include "inside_outside.h"
#include "error_surface.h"
#include "hg.h"
#include "hg_io.h"
using namespace std;
namespace po = boost::program_options;
void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("reference,r",po::value<vector<string> >(), "[REQD] Reference translation (tokenized text)")
("source,s",po::value<string>(), "Source file (ignored, except for AER)")
("loss_function,l",po::value<string>()->default_value("ibm_bleu"), "Loss function being optimized")
("input,i",po::value<string>()->default_value("-"), "Input file to map (- is STDIN)")
("help,h", "Help");
po::options_description dcmdline_options;
dcmdline_options.add(opts);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
bool flag = false;
if (!conf->count("reference")) {
cerr << "Please specify one or more references using -r <REF.TXT>\n";
flag = true;
}
if (flag || conf->count("help")) {
cerr << dcmdline_options << endl;
exit(1);
}
}
bool ReadSparseVectorString(const string& s, SparseVector<double>* v) {
vector<string> fields;
Tokenize(s, ';', &fields);
if (fields.empty()) return false;
for (int i = 0; i < fields.size(); ++i) {
vector<string> pair(2);
Tokenize(fields[i], '=', &pair);
if (pair.size() != 2) {
cerr << "Error parsing vector string: " << fields[i] << endl;
return false;
}
v->set_value(FD::Convert(pair[0]), atof(pair[1].c_str()));
}
return true;
}
int main(int argc, char** argv) {
po::variables_map conf;
InitCommandLine(argc, argv, &conf);
const string loss_function = conf["loss_function"].as<string>();
ScoreType type = ScoreTypeFromString(loss_function);
DocScorer ds(type, conf["reference"].as<vector<string> >(), conf["source"].as<string>());
cerr << "Loaded " << ds.size() << " references for scoring with " << loss_function << endl;
Hypergraph hg;
string last_file;
ReadFile in_read(conf["input"].as<string>());
istream &in=*in_read.stream();
while(in) {
string line;
getline(in, line);
if (line.empty()) continue;
istringstream is(line);
int sent_id;
string file, s_origin, s_axis;
is >> file >> sent_id >> s_origin >> s_axis;
SparseVector<double> origin;
assert(ReadSparseVectorString(s_origin, &origin));
SparseVector<double> axis;
assert(ReadSparseVectorString(s_axis, &axis));
// cerr << "File: " << file << "\nAxis: " << axis << "\n X: " << origin << endl;
if (last_file != file) {
last_file = file;
ReadFile rf(file);
HypergraphIO::ReadFromJSON(rf.stream(), &hg);
}
ViterbiEnvelopeWeightFunction wf(origin, axis);
ViterbiEnvelope ve = Inside<ViterbiEnvelope, ViterbiEnvelopeWeightFunction>(hg, NULL, wf);
ErrorSurface es;
ds[sent_id]->ComputeErrorSurface(ve, &es, type, hg);
//cerr << "Viterbi envelope has " << ve.size() << " segments\n";
// cerr << "Error surface has " << es.size() << " segments\n";
string val;
es.Serialize(&val);
cout << 'M' << ' ' << s_origin << ' ' << s_axis << '\t';
B64::b64encode(val.c_str(), val.size(), &cout);
cout << endl;
}
return 0;
}
<commit_msg>whitespace<commit_after>#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "filelib.h"
#include "stringlib.h"
#include "sparse_vector.h"
#include "scorer.h"
#include "viterbi_envelope.h"
#include "inside_outside.h"
#include "error_surface.h"
#include "hg.h"
#include "hg_io.h"
using namespace std;
namespace po = boost::program_options;
void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("reference,r",po::value<vector<string> >(), "[REQD] Reference translation (tokenized text)")
("source,s",po::value<string>(), "Source file (ignored, except for AER)")
("loss_function,l",po::value<string>()->default_value("ibm_bleu"), "Loss function being optimized")
("input,i",po::value<string>()->default_value("-"), "Input file to map (- is STDIN)")
("help,h", "Help");
po::options_description dcmdline_options;
dcmdline_options.add(opts);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
bool flag = false;
if (!conf->count("reference")) {
cerr << "Please specify one or more references using -r <REF.TXT>\n";
flag = true;
}
if (flag || conf->count("help")) {
cerr << dcmdline_options << endl;
exit(1);
}
}
bool ReadSparseVectorString(const string& s, SparseVector<double>* v) {
vector<string> fields;
Tokenize(s, ';', &fields);
if (fields.empty()) return false;
for (int i = 0; i < fields.size(); ++i) {
vector<string> pair(2);
Tokenize(fields[i], '=', &pair);
if (pair.size() != 2) {
cerr << "Error parsing vector string: " << fields[i] << endl;
return false;
}
v->set_value(FD::Convert(pair[0]), atof(pair[1].c_str()));
}
return true;
}
int main(int argc, char** argv) {
po::variables_map conf;
InitCommandLine(argc, argv, &conf);
const string loss_function = conf["loss_function"].as<string>();
ScoreType type = ScoreTypeFromString(loss_function);
DocScorer ds(type, conf["reference"].as<vector<string> >(), conf["source"].as<string>());
cerr << "Loaded " << ds.size() << " references for scoring with " << loss_function << endl;
Hypergraph hg;
string last_file;
ReadFile in_read(conf["input"].as<string>());
istream &in=*in_read.stream();
while(in) {
string line;
getline(in, line);
if (line.empty()) continue;
istringstream is(line);
int sent_id;
string file, s_origin, s_axis;
is >> file >> sent_id >> s_origin >> s_axis;
SparseVector<double> origin;
assert(ReadSparseVectorString(s_origin, &origin));
SparseVector<double> axis;
assert(ReadSparseVectorString(s_axis, &axis));
// cerr << "File: " << file << "\nAxis: " << axis << "\n X: " << origin << endl;
if (last_file != file) {
last_file = file;
ReadFile rf(file);
HypergraphIO::ReadFromJSON(rf.stream(), &hg);
}
ViterbiEnvelopeWeightFunction wf(origin, axis);
ViterbiEnvelope ve = Inside<ViterbiEnvelope, ViterbiEnvelopeWeightFunction>(hg, NULL, wf);
ErrorSurface es;
ds[sent_id]->ComputeErrorSurface(ve, &es, type, hg);
//cerr << "Viterbi envelope has " << ve.size() << " segments\n";
// cerr << "Error surface has " << es.size() << " segments\n";
string val;
es.Serialize(&val);
cout << 'M' << ' ' << s_origin << ' ' << s_axis << '\t';
B64::b64encode(val.c_str(), val.size(), &cout);
cout << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppUtils.h"
#include "QXmppIq.h"
#include <QDomElement>
#include <QXmlStreamWriter>
/// Constructs a QXmppIq with the specified \a type.
///
/// \param type
QXmppIq::QXmppIq(QXmppIq::Type type)
: QXmppStanza(), m_type(type)
{
generateAndSetNextId();
}
/// Returns the IQ's type.
///
QXmppIq::Type QXmppIq::type() const
{
return m_type;
}
/// Sets the IQ's type.
///
/// \param type
void QXmppIq::setType(QXmppIq::Type type)
{
m_type = type;
}
void QXmppIq::parse(const QDomElement &element)
{
QXmppStanza::parse(element);
setTypeFromStr(element.attribute("type"));
parseElementFromChild(element);
}
void QXmppIq::parseElementFromChild(const QDomElement &element)
{
QXmppElementList extensions;
QDomElement itemElement = element.firstChildElement();
while (!itemElement.isNull())
{
extensions.append(QXmppElement(itemElement));
itemElement = itemElement.nextSiblingElement();
}
setExtensions(extensions);
}
void QXmppIq::toXml( QXmlStreamWriter *xmlWriter ) const
{
xmlWriter->writeStartElement("iq");
helperToXmlAddAttribute(xmlWriter, "id", id());
helperToXmlAddAttribute(xmlWriter, "to", to());
helperToXmlAddAttribute(xmlWriter, "from", from());
if(getTypeStr().isEmpty())
helperToXmlAddAttribute(xmlWriter, "type", "get");
else
helperToXmlAddAttribute(xmlWriter, "type", getTypeStr());
toXmlElementFromChild(xmlWriter);
error().toXml(xmlWriter);
xmlWriter->writeEndElement();
}
void QXmppIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const
{
foreach (const QXmppElement &extension, extensions())
extension.toXml(writer);
}
QString QXmppIq::getTypeStr() const
{
switch(m_type)
{
case QXmppIq::Error:
return "error";
case QXmppIq::Get:
return "get";
case QXmppIq::Set:
return "set";
case QXmppIq::Result:
return "result";
default:
qWarning("QXmppIq::getTypeStr() invalid type %d", (int)m_type);
return "";
}
}
void QXmppIq::setTypeFromStr(const QString& str)
{
if(str == "error")
{
setType(QXmppIq::Error);
return;
}
else if(str == "get")
{
setType(QXmppIq::Get);
return;
}
else if(str == "set")
{
setType(QXmppIq::Set);
return;
}
else if(str == "result")
{
setType(QXmppIq::Result);
return;
}
else
{
setType(static_cast<QXmppIq::Type>(-1));
qWarning("QXmppIq::setTypeFromStr() invalid input string type: %s",
qPrintable(str));
return;
}
}
// deprecated
QXmppIq::Type QXmppIq::getType() const
{
return m_type;
}
<commit_msg>doc improvement<commit_after>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppUtils.h"
#include "QXmppIq.h"
#include <QDomElement>
#include <QXmlStreamWriter>
/// Constructs a QXmppIq with the specified \a type.
///
/// \param type
QXmppIq::QXmppIq(QXmppIq::Type type)
: QXmppStanza(), m_type(type)
{
generateAndSetNextId();
}
/// Returns the IQ's type.
///
/// \return QXmppIq::Type
QXmppIq::Type QXmppIq::type() const
{
return m_type;
}
/// Sets the IQ's type.
///
/// \param type as QXmppIq::Type
void QXmppIq::setType(QXmppIq::Type type)
{
m_type = type;
}
void QXmppIq::parse(const QDomElement &element)
{
QXmppStanza::parse(element);
setTypeFromStr(element.attribute("type"));
parseElementFromChild(element);
}
void QXmppIq::parseElementFromChild(const QDomElement &element)
{
QXmppElementList extensions;
QDomElement itemElement = element.firstChildElement();
while (!itemElement.isNull())
{
extensions.append(QXmppElement(itemElement));
itemElement = itemElement.nextSiblingElement();
}
setExtensions(extensions);
}
void QXmppIq::toXml( QXmlStreamWriter *xmlWriter ) const
{
xmlWriter->writeStartElement("iq");
helperToXmlAddAttribute(xmlWriter, "id", id());
helperToXmlAddAttribute(xmlWriter, "to", to());
helperToXmlAddAttribute(xmlWriter, "from", from());
if(getTypeStr().isEmpty())
helperToXmlAddAttribute(xmlWriter, "type", "get");
else
helperToXmlAddAttribute(xmlWriter, "type", getTypeStr());
toXmlElementFromChild(xmlWriter);
error().toXml(xmlWriter);
xmlWriter->writeEndElement();
}
void QXmppIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const
{
foreach (const QXmppElement &extension, extensions())
extension.toXml(writer);
}
QString QXmppIq::getTypeStr() const
{
switch(m_type)
{
case QXmppIq::Error:
return "error";
case QXmppIq::Get:
return "get";
case QXmppIq::Set:
return "set";
case QXmppIq::Result:
return "result";
default:
qWarning("QXmppIq::getTypeStr() invalid type %d", (int)m_type);
return "";
}
}
void QXmppIq::setTypeFromStr(const QString& str)
{
if(str == "error")
{
setType(QXmppIq::Error);
return;
}
else if(str == "get")
{
setType(QXmppIq::Get);
return;
}
else if(str == "set")
{
setType(QXmppIq::Set);
return;
}
else if(str == "result")
{
setType(QXmppIq::Result);
return;
}
else
{
setType(static_cast<QXmppIq::Type>(-1));
qWarning("QXmppIq::setTypeFromStr() invalid input string type: %s",
qPrintable(str));
return;
}
}
// deprecated
QXmppIq::Type QXmppIq::getType() const
{
return m_type;
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Time/Duration.h"
#include "Common.h"
#include "TimeOutException.h"
#include "WaitableEvent.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
using Stroika::Foundation::Time::Duration;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
* Design notes:
*
* o The use of condition variables is non-obvious. I haven't found good documentation, but
* the best I've found would be
* https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview
*
* In particular, on the surface, it looks like the mutex locks in Wait() and signal should prevent things
* form working (deadlock). But they apparently do not cause a deadlock because
* "pthread_cond_wait() blocks the calling thread until the specified condition is signalled.
* This routine should be called while mutex is locked, and it will automatically release the
* mutex while it waits. After signal is received and thread is awakened, mutex will be
* automatically locked for use by the thread. The programmer is then responsible for
* unlocking mutex when the thread is finished with it."
*
*/
/*
********************************************************************************
****************************** WaitableEvent::WE_ ******************************
********************************************************************************
*/
void WaitableEvent::WE_::WaitUntil (Time::DurationSecondsType timeoutAt)
{
if (WaitUntilQuietly (timeoutAt) == kWaitQuietlyTimeoutResult) {
// note - safe use of TimeOutException::kThe because you cannot really wait except when threads are running, so
// inside 'main' lifetime
#if USE_NOISY_TRACE_IN_THIS_MODULE_
// only thing Throw() helper does is DbgTrace ()- and that can make traces hard to read unless you are debugging a timeout /event issue
Throw (TimeOutException::kThe);
#else
throw (TimeOutException::kThe);
#endif
}
}
bool WaitableEvent::WE_::WaitUntilQuietly (Time::DurationSecondsType timeoutAt)
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"WaitableEvent::WE_::WaitUntil", "timeout = %e", timeoutAt);
#endif
CheckForThreadInterruption ();
std::unique_lock<mutex> lock (fConditionVariable.fMutex);
if (fConditionVariable.wait_until (lock, timeoutAt, [this]() { return fTriggered; })) {
if (fResetType == eAutoReset) {
// cannot call Reset () directly because we (may???) already have the lock mutex? Maybe not cuz of cond variable?
fTriggered = false; // autoreset
}
return not kWaitQuietlyTimeoutResult;
}
else {
return kWaitQuietlyTimeoutResult;
}
}
/*
********************************************************************************
********************************** WaitableEvent *******************************
********************************************************************************
*/
constexpr WaitableEvent::ResetType WaitableEvent::eAutoReset;
constexpr WaitableEvent::ResetType WaitableEvent::eManualReset;
#if qDebug || qStroika_FeatureSupported_Valgrind
WaitableEvent::~WaitableEvent ()
{
Require (fExtraWaitableEvents_.empty ()); // Cannot kill a waitable event while its being waited on by others
// Stroika_Foundation_Debug_ValgrindDisableHelgrind (fWE_.fConditionVariable.fConditionVariable); // avoid sporadic (about 1/3 time) probably spurious helgrind failure - for test Foundation::Execution::Threads -https://stroika.atlassian.net/browse/STK-484
}
#endif
void WaitableEvent::Set ()
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx ("WaitableEvent::Set");
#endif
fWE_.Set ();
#if qExecution_WaitableEvent_SupportWaitForMultipleObjects
auto critSec{make_unique_lock (_Stroika_Foundation_Execution_Private_WaitableEvent_ModuleInit_.Actual ().fExtraWaitableEventsMutex_)};
for (auto i : fExtraWaitableEvents_) {
i->Set ();
}
#endif
}
<commit_msg>https://stroika.atlassian.net/browse/STK-484 possible fix - waitableevent - may need extra mutex lock on read (found with tsan)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Time/Duration.h"
#include "Common.h"
#include "TimeOutException.h"
#include "WaitableEvent.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
using Stroika::Foundation::Time::Duration;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
* Design notes:
*
* o The use of condition variables is non-obvious. I haven't found good documentation, but
* the best I've found would be
* https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview
*
* In particular, on the surface, it looks like the mutex locks in Wait() and signal should prevent things
* form working (deadlock). But they apparently do not cause a deadlock because
* "pthread_cond_wait() blocks the calling thread until the specified condition is signalled.
* This routine should be called while mutex is locked, and it will automatically release the
* mutex while it waits. After signal is received and thread is awakened, mutex will be
* automatically locked for use by the thread. The programmer is then responsible for
* unlocking mutex when the thread is finished with it."
*
*/
/*
********************************************************************************
****************************** WaitableEvent::WE_ ******************************
********************************************************************************
*/
void WaitableEvent::WE_::WaitUntil (Time::DurationSecondsType timeoutAt)
{
if (WaitUntilQuietly (timeoutAt) == kWaitQuietlyTimeoutResult) {
// note - safe use of TimeOutException::kThe because you cannot really wait except when threads are running, so
// inside 'main' lifetime
#if USE_NOISY_TRACE_IN_THIS_MODULE_
// only thing Throw() helper does is DbgTrace ()- and that can make traces hard to read unless you are debugging a timeout /event issue
Throw (TimeOutException::kThe);
#else
throw (TimeOutException::kThe);
#endif
}
}
bool WaitableEvent::WE_::WaitUntilQuietly (Time::DurationSecondsType timeoutAt)
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx (L"WaitableEvent::WE_::WaitUntil", "timeout = %e", timeoutAt);
#endif
CheckForThreadInterruption ();
std::unique_lock<mutex> lock (fConditionVariable.fMutex);
if (fConditionVariable.wait_until (lock, timeoutAt, [this]() { return fTriggered; })) {
if (fResetType == eAutoReset) {
// cannot call Reset () directly because we (may???) already have the lock mutex? Maybe not cuz of cond variable?
fTriggered = false; // autoreset
}
return not kWaitQuietlyTimeoutResult;
}
else {
return kWaitQuietlyTimeoutResult;
}
}
/*
********************************************************************************
********************************** WaitableEvent *******************************
********************************************************************************
*/
constexpr WaitableEvent::ResetType WaitableEvent::eAutoReset;
constexpr WaitableEvent::ResetType WaitableEvent::eManualReset;
#if qDebug || qStroika_FeatureSupported_Valgrind
WaitableEvent::~WaitableEvent ()
{
Require (fExtraWaitableEvents_.empty ()); // Cannot kill a waitable event while its being waited on by others
// Stroika_Foundation_Debug_ValgrindDisableHelgrind (fWE_.fConditionVariable.fConditionVariable); // avoid sporadic (about 1/3 time) probably spurious helgrind failure - for test Foundation::Execution::Threads -https://stroika.atlassian.net/browse/STK-484
}
#endif
void WaitableEvent::Set ()
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx ("WaitableEvent::Set");
#endif
fWE_.Set ();
#if qExecution_WaitableEvent_SupportWaitForMultipleObjects
auto critSec{make_unique_lock (_Stroika_Foundation_Execution_Private_WaitableEvent_ModuleInit_.Actual ().fExtraWaitableEventsMutex_)};
for (auto i : fExtraWaitableEvents_) {
i->Set ();
}
#endif
}
<|endoftext|>
|
<commit_before>//
// This program will take a flow XML and run it in dummy mode.
// This means that it will run every node with a dummy function and
// exercise the flow with all of its guard acquisitions.
// It can be used to test the flow for bottlenecks or other effects.
// It may also indicate interesting effects related to choice of runtime.
// Limitations:
// * guards are reduced to singleton (no () key guards)
// * no data is passed since the replacement nodes do not pass inputs or
// outputs
#include "OFlux.h"
#include "flow/OFluxFlowExerciseFunctions.h"
#include "flow/OFluxFlow.h"
#include "atomic/OFluxAtomic.h"
#include "lockfree/atomic/OFluxLFAtomicMaps.h"
#include "atomic/OFluxAtomicHolder.h"
#include "OFluxRunTimeBase.h"
#include "OFluxIOConversion.h"
#include "OFluxEarlyRelease.h"
#include "OFluxLogging.h"
#include <iostream>
#include <signal.h>
oflux::shared_ptr<oflux::RunTimeAbstract> theRT;
void
init_atomic_maps(int) {}
oflux::flow::exercise::AtomicSetAbstract * atomic_set = NULL;
oflux::flow::Flow * flow = NULL;
void handlesighup(int)
{
signal(SIGHUP,handlesighup);
atomic_set->report();
oflux::flow::exercise::node_report(flow);
theRT->log_snapshot();
}
oflux::flow::exercise::AtomicAbstract::P * _atomic_array;
void
ex_release_guards()
{
oflux::release_all_guards(theRT.get());
}
int
main(int argc, char * argv[])
{
oflux::flow::exercise::release_guards = ex_release_guards;
if(argc <= 1) {
std::cout << "provide an XML flow file argument\n";
return 9;
}
char * max_nsec_wait_str = getenv("EXERCISE_SLEEP");
if(max_nsec_wait_str) {
oflux::flow::exercise::max_nsec_wait = atol(max_nsec_wait_str);
}
int init_threads = 0;
char * init_threads_str = getenv("EXERCISE_THREADS");
if(init_threads_str) {
init_threads = atoi(init_threads_str);
}
oflux::RunTimeConfiguration rtc = {
1024*1024 // stack size
, init_threads // initial threads (ignored really)
, 0 // max threads
, 0 // max detached
, 0 // thread collection threshold
, 1000 // thread collection sample period (every N node execs)
, argv[1] // XML file
, NULL // temporary
, "xml" // xml subdir for plugins
, "lib" // lib subdir for plugins
, NULL
, init_atomic_maps
};
oflux::logging::toStream(std::cout);
oflux_log_info(" exercise::max_nsec_wait is %ld\n", oflux::flow::exercise::max_nsec_wait);
oflux::EnvironmentVar env(oflux::runtime::Factory::classic);
oflux::flow::ExerciseFunctionMaps ffmaps(env.runtime_number == 4);
atomic_set = ffmaps.atomic_set();
rtc.flow_maps = &ffmaps;
theRT.reset(oflux::runtime::Factory::create(env.runtime_number, rtc));
flow = theRT->flow();
oflux::flow::exercise::AtomicAbstract::P atomic_array[atomic_set->size()+1];
_atomic_array = &atomic_array[0];
atomic_set->fill(atomic_array);
signal(SIGHUP,handlesighup);
if(!env.nostart) {
theRT->start();
}
theRT.reset(); // force deletion of the runtime
return 0;
}
<commit_msg>max threads in exercise<commit_after>//
// This program will take a flow XML and run it in dummy mode.
// This means that it will run every node with a dummy function and
// exercise the flow with all of its guard acquisitions.
// It can be used to test the flow for bottlenecks or other effects.
// It may also indicate interesting effects related to choice of runtime.
// Limitations:
// * guards are reduced to singleton (no () key guards)
// * no data is passed since the replacement nodes do not pass inputs or
// outputs
#include "OFlux.h"
#include "flow/OFluxFlowExerciseFunctions.h"
#include "flow/OFluxFlow.h"
#include "atomic/OFluxAtomic.h"
#include "lockfree/atomic/OFluxLFAtomicMaps.h"
#include "atomic/OFluxAtomicHolder.h"
#include "OFluxRunTimeBase.h"
#include "OFluxIOConversion.h"
#include "OFluxEarlyRelease.h"
#include "OFluxLogging.h"
#include <iostream>
#include <signal.h>
oflux::shared_ptr<oflux::RunTimeAbstract> theRT;
void
init_atomic_maps(int) {}
oflux::flow::exercise::AtomicSetAbstract * atomic_set = NULL;
oflux::flow::Flow * flow = NULL;
void handlesighup(int)
{
signal(SIGHUP,handlesighup);
atomic_set->report();
oflux::flow::exercise::node_report(flow);
theRT->log_snapshot();
}
oflux::flow::exercise::AtomicAbstract::P * _atomic_array;
void
ex_release_guards()
{
oflux::release_all_guards(theRT.get());
}
int
main(int argc, char * argv[])
{
oflux::flow::exercise::release_guards = ex_release_guards;
if(argc <= 1) {
std::cout << "provide an XML flow file argument\n";
return 9;
}
char * max_nsec_wait_str = getenv("EXERCISE_SLEEP");
if(max_nsec_wait_str) {
oflux::flow::exercise::max_nsec_wait = atol(max_nsec_wait_str);
}
int init_threads = 0;
char * init_threads_str = getenv("EXERCISE_THREADS");
if(init_threads_str) {
init_threads = atoi(init_threads_str);
}
oflux::RunTimeConfiguration rtc = {
1024*1024 // stack size
, init_threads // initial threads (ignored really)
, 64 // max threads
, 0 // max detached
, 0 // thread collection threshold
, 1000 // thread collection sample period (every N node execs)
, argv[1] // XML file
, NULL // temporary
, "xml" // xml subdir for plugins
, "lib" // lib subdir for plugins
, NULL
, init_atomic_maps
};
oflux::logging::toStream(std::cout);
oflux_log_info(" exercise::max_nsec_wait is %ld\n", oflux::flow::exercise::max_nsec_wait);
oflux::EnvironmentVar env(oflux::runtime::Factory::classic);
oflux::flow::ExerciseFunctionMaps ffmaps(env.runtime_number == 4);
atomic_set = ffmaps.atomic_set();
rtc.flow_maps = &ffmaps;
theRT.reset(oflux::runtime::Factory::create(env.runtime_number, rtc));
flow = theRT->flow();
oflux::flow::exercise::AtomicAbstract::P atomic_array[atomic_set->size()+1];
_atomic_array = &atomic_array[0];
atomic_set->fill(atomic_array);
signal(SIGHUP,handlesighup);
if(!env.nostart) {
theRT->start();
}
theRT.reset(); // force deletion of the runtime
return 0;
}
<|endoftext|>
|
<commit_before>//
// Copyright 2014, 2015 Razer 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 "OSVRPrivatePCH.h"
#include "OSVRInterfaceCollection.h"
#include "OSVREntryPoint.h"
OSVR_ClientContext osvrClientContext(nullptr);
OSVREntryPoint::OSVREntryPoint()
{
osvrClientContext = osvrClientInit("OSVR Unreal Engine 4 Plugin");
InterfaceCollection = MakeShareable(new OSVRInterfaceCollection(
osvrClientContext
));
}
OSVREntryPoint::~OSVREntryPoint()
{
InterfaceCollection = nullptr;
osvrClientShutdown(osvrClientContext);
}
void OSVREntryPoint::Tick(float DeltaTime)
{
osvrClientUpdate(osvrClientContext);
}
OSVRInterfaceCollection* OSVREntryPoint::GetInterfaceCollection()
{
return InterfaceCollection.Get();
}
<commit_msg>Small change to the application identifier.<commit_after>//
// Copyright 2014, 2015 Razer 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 "OSVRPrivatePCH.h"
#include "OSVRInterfaceCollection.h"
#include "OSVREntryPoint.h"
OSVR_ClientContext osvrClientContext(nullptr);
OSVREntryPoint::OSVREntryPoint()
{
osvrClientContext = osvrClientInit("com.osvr.unreal.plugin");
InterfaceCollection = MakeShareable(new OSVRInterfaceCollection(
osvrClientContext
));
}
OSVREntryPoint::~OSVREntryPoint()
{
InterfaceCollection = nullptr;
osvrClientShutdown(osvrClientContext);
}
void OSVREntryPoint::Tick(float DeltaTime)
{
osvrClientUpdate(osvrClientContext);
}
OSVRInterfaceCollection* OSVREntryPoint::GetInterfaceCollection()
{
return InterfaceCollection.Get();
}
<|endoftext|>
|
<commit_before>#include <numeric>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <set>
#include <csignal>
#include <cmath>
#include <ctgmath>
#include "sdd/sdd.hh"
#include "sdd/tools/size.hh"
#include "sdd/tools/nodes.hh"
#include "sdd/tools/arcs.hh"
#include "sdd/tools/sequences.hh"
#include "sdd/tools/dot/sdd.hh"
using namespace std;
static bool finish = false;
void
handler(int s)
{
finish = true;
}
struct conf
: public sdd::flat_set_default_configuration
{
using Identifier = unsigned int;
using Values = sdd::values::flat_set<char>;
};
using SDD = sdd::SDD<conf>;
using values_type = conf::Values;
int
main (int argc, const char** argv)
{
const auto subsize = 100;
if (argc == 0)
{
cerr << "sdd-stream <max-length>" << endl;
return 1;
}
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = handler;
sigemptyset (&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction (SIGINT, &sigIntHandler, NULL);
size_t max_length = stoi (argv [1]);
vector<SDD> collections;
collections.reserve (subsize);
conf c;
c.final_cleanup = false; // don't cleanup memory on manager scope exit.
c.hom_cache_size = 2; // we don't use homomorphisms.
c.hom_unique_table_size = 2; // we don't use homomorphisms.
// c.sdd_intersection_cache_size = 16000000;
// c.sdd_sum_cache_size = 16000000;
// c.sdd_difference_cache_size = 16000000;
// c.sdd_unique_table_size = 10000000;
auto manager = sdd::init<conf>(c);
// // Construct the SDD order: we need one level per letter.
// vector<unsigned int> v (max_length);
// iota (v.begin(), v.end(), 0);
sdd::order_builder<conf> ob;
const sdd::order<conf> order {sdd::order_builder<conf> ()};
set<char> characters;
size_t inserted = 0;
size_t dropped = 0;
size_t total = 0;
size_t sum_inserted = 0;
string line;
line.reserve (80);
string sequence;
sequence.reserve (max_length);
cout << "\033[s" << flush;
while (getline (cin, line))
{
if (line [0] == '>')
{ // starting a new sequence:
total += 1;
if (sequence.size () != 0)
{
if (sequence.size () <= max_length)
{
SDD word = SDD(0, SDD::eol::flat, sdd::one<conf>());
for (auto i = 0u; i < sequence.size(); ++i)
{
characters.insert (sequence[sequence.size() - i - 1]);
word = SDD(0, {sequence[sequence.size() - i - 1]}, word);
}
collections.emplace_back(word);
inserted += 1;
sum_inserted += sequence.size();
}
else
dropped += 1;
sequence.clear ();
}
if (finish)
break;
}
else
sequence += line;
if (collections.size () == subsize)
{
const auto result = sdd::sum<conf> ( collections.cbegin()
, collections.cend() );
collections.clear ();
collections.push_back (result);
}
if (total % 200 == 0)
cout << "\033[u"
<< "inserted: " << inserted
<< " / "
<< "dropped: " << dropped
<< " / "
<< "total: " << total
<< flush;
}
if (sequence.size () <= max_length)
{
SDD word = SDD(0, SDD::eol::flat, sdd::one<conf>());
for (auto i = 0u; i < line.size(); ++i)
{
word = SDD(0, {line[line.size() - i - 1]}, word);
}
collections.emplace_back(word);
inserted += 1;
sum_inserted += sequence.size();
}
else
dropped += 1;
cout << "\033[u"
<< "inserted: " << inserted
<< " / "
<< "dropped: " << dropped
<< " / "
<< "total: " << total
<< endl;
const auto result = sdd::sum<conf> ( collections.cbegin()
, collections.cend() );
cout << "# Characters: " << characters.size() << endl;
cout << "# Words: " << result.size() << endl;
const auto nodes = sdd::tools::nodes(result).first;
cout << "# Nodes: " << nodes << endl;
const auto size = sdd::tools::size(result);
cout << "Size: " << ceil(static_cast<float>(size) / 1024 / 1024) << " Mbytes" << endl;
cout << "Average node size: " << (size / nodes) << " bytes" << endl;
auto frequency = sdd::tools::arcs<conf>(result);
auto sequences = sdd::tools::sequences<conf>(result);
// BUG here!
size_t nb = 0;
for (auto& p : sequences)
{
// cout << " == " << p.first << " => " << p.second << endl;
nb += p.first * p.second;
}
cout << "!!!!! nb: " << nb << " =?= " << frequency[1].first << endl;
size_t max_children = 0;
for (auto& p : frequency)
{
max_children = max_children < p.first
? p.first
: max_children;
}
size_t expected = 0;
size_t bitfield_size = ceil(static_cast<float>(characters.size())/8);
size_t base_size = bitfield_size + 4 + 8 + 1;
cout << "Bit field size: " << bitfield_size << " bytes" << endl;
cout << "Base node size: " << base_size << " bytes" << endl;
const size_t average_length = 100;
const size_t bitsize = ceil(log2(characters.size()));
cout << "Bitsize: " << bitsize << endl;
for (size_t i = 0; i <= max_children; ++i)
{
if (frequency[i].first == 0)
continue;
cout << left << setw(3) << i
<< " => "
<< left << setw(10) << frequency[i].first
<< right
<< endl;
size_t subresult = 0;
size_t subsize = 0;
if (i == 1)
{
size_t subcount = 0;
for (const auto& p : sequences)
{
size_t size = base_size + 8 + ceil(static_cast<float>(bitsize)* p.first / 8);
size += size % 8 == 0
? 0
: 8 - (size % 8);
size *= p.second;
subresult += size;
subsize += p.second;
subcount += p.second * p.first;
/*
cout << " For Length: " << p.first
<< endl
<< " # Sequences: " << p.second
<< endl
<< " String size: " << ceil((static_cast<float>(bitsize) * p.first) / 8)
<< " bytes"
<< endl
<< " Size: " << size
<< " bytes"
<< endl
<< " Average size: " << (size / p.second)
<< " bytes"
<< endl;
*/
}
subresult += (base_size + 8 + ceil(static_cast<float>(bitsize) / 8)) * (frequency[1].first - subcount);
cout << " Subcount: " << subcount << endl;
cout << " Frequency: " << frequency[i].first << endl;
size_t average = 150;
size_t should_size =
(base_size + 8 + ceil(static_cast<float>(bitsize)*average / 8))
* frequency[i].first / average;
cout << " Sould be: "
<< should_size
<< " bytes"
<< endl;
}
else
{
size_t size = base_size + i * 8;
size += size % 8 == 0
? 0
: 8 - (size % 8);
subresult = size * frequency[i].first;
subsize = frequency[i].first;
}
cout << " Total: " << subresult << " bytes"
<< endl
<< " Average: " << (subresult / subsize) << " bytes"
<< endl;
expected += subresult;
}
cout << "Expected size: " << ceil(static_cast<float>(expected) / 1024 / 1024) << " Mbytes" << endl;
cout << "Original size: " << ceil(static_cast<float>(sum_inserted) / 1024 / 1024)
<< " Mbytes"
<< endl
<< "Binary size: " << (sum_inserted * bitsize / 8 / 1024 / 1024 + 1)
<< " Mbytes"
<< endl;
if (nodes <= 5000)
{
ofstream of ("machin.dot");
of << sdd::tools::dot (result, order);
}
return 0;
}
<commit_msg>Add min-length argument.<commit_after>#include <numeric>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <set>
#include <csignal>
#include <cmath>
#include <ctgmath>
#include "sdd/sdd.hh"
#include "sdd/tools/size.hh"
#include "sdd/tools/nodes.hh"
#include "sdd/tools/arcs.hh"
#include "sdd/tools/sequences.hh"
#include "sdd/tools/dot/sdd.hh"
using namespace std;
static bool finish = false;
void
handler(int s)
{
finish = true;
}
struct conf
: public sdd::flat_set_default_configuration
{
using Identifier = unsigned int;
using Values = sdd::values::flat_set<char>;
};
using SDD = sdd::SDD<conf>;
using values_type = conf::Values;
int
main (int argc, const char** argv)
{
const auto subsize = 100;
if (argc == 0)
{
cerr << "sdd-stream <min-length> <max-length>" << endl;
return 1;
}
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = handler;
sigemptyset (&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction (SIGINT, &sigIntHandler, NULL);
size_t min_length = stoi (argv [1]);
size_t max_length = stoi (argv [2]);
vector<SDD> collections;
collections.reserve (subsize);
conf c;
c.final_cleanup = false; // don't cleanup memory on manager scope exit.
c.hom_cache_size = 2; // we don't use homomorphisms.
c.hom_unique_table_size = 2; // we don't use homomorphisms.
// c.sdd_intersection_cache_size = 16000000;
// c.sdd_sum_cache_size = 16000000;
// c.sdd_difference_cache_size = 16000000;
// c.sdd_unique_table_size = 10000000;
auto manager = sdd::init<conf>(c);
// // Construct the SDD order: we need one level per letter.
// vector<unsigned int> v (max_length);
// iota (v.begin(), v.end(), 0);
sdd::order_builder<conf> ob;
const sdd::order<conf> order {sdd::order_builder<conf> ()};
set<char> characters;
size_t inserted = 0;
size_t dropped = 0;
size_t total = 0;
size_t sum_inserted = 0;
string line;
line.reserve (80);
string sequence;
sequence.reserve (max_length);
cout << "\033[s" << flush;
while (getline (cin, line))
{
if (line [0] == '>')
{ // starting a new sequence:
total += 1;
if (sequence.size () != 0)
{
if ((sequence.size() >= min_length) && (sequence.size () <= max_length))
{
SDD word = SDD(0, SDD::eol::flat, sdd::one<conf>());
for (auto i = 0u; i < sequence.size(); ++i)
{
characters.insert (sequence[sequence.size() - i - 1]);
word = SDD(0, {sequence[sequence.size() - i - 1]}, word);
}
collections.emplace_back(word);
inserted += 1;
sum_inserted += sequence.size();
}
else
dropped += 1;
sequence.clear ();
}
if (finish)
break;
}
else
sequence += line;
if (collections.size () == subsize)
{
const auto result = sdd::sum<conf> ( collections.cbegin()
, collections.cend() );
collections.clear ();
collections.push_back (result);
}
if (total % 200 == 0)
cout << "\033[u"
<< "inserted: " << inserted
<< " / "
<< "dropped: " << dropped
<< " / "
<< "total: " << total
<< flush;
}
if ((sequence.size() >= min_length) && (sequence.size () <= max_length))
{
SDD word = SDD(0, SDD::eol::flat, sdd::one<conf>());
for (auto i = 0u; i < line.size(); ++i)
{
word = SDD(0, {line[line.size() - i - 1]}, word);
}
collections.emplace_back(word);
inserted += 1;
sum_inserted += sequence.size();
}
else
dropped += 1;
cout << "\033[u"
<< "inserted: " << inserted
<< " / "
<< "dropped: " << dropped
<< " / "
<< "total: " << total
<< endl;
const auto result = sdd::sum<conf> ( collections.cbegin()
, collections.cend() );
cout << "# Characters: " << characters.size() << endl;
cout << "# Words: " << result.size() << endl;
const auto nodes = sdd::tools::nodes(result).first;
cout << "# Nodes: " << nodes << endl;
const auto size = sdd::tools::size(result);
cout << "Size: " << ceil(static_cast<float>(size) / 1024 / 1024) << " Mbytes" << endl;
cout << "Average node size: " << (size / nodes) << " bytes" << endl;
auto frequency = sdd::tools::arcs<conf>(result);
auto sequences = sdd::tools::sequences<conf>(result);
// BUG here!
size_t nb = 0;
for (auto& p : sequences)
{
// cout << " == " << p.first << " => " << p.second << endl;
nb += p.first * p.second;
}
cout << "!!!!! nb: " << nb << " =?= " << frequency[1].first << endl;
size_t max_children = 0;
for (auto& p : frequency)
{
max_children = max_children < p.first
? p.first
: max_children;
}
size_t expected = 0;
size_t bitfield_size = ceil(static_cast<float>(characters.size())/8);
size_t base_size = bitfield_size + 4 + 8 + 1;
cout << "Bit field size: " << bitfield_size << " bytes" << endl;
cout << "Base node size: " << base_size << " bytes" << endl;
const size_t average_length = 100;
const size_t bitsize = ceil(log2(characters.size()));
cout << "Bitsize: " << bitsize << endl;
for (size_t i = 0; i <= max_children; ++i)
{
if (frequency[i].first == 0)
continue;
cout << left << setw(3) << i
<< " => "
<< left << setw(10) << frequency[i].first
<< right
<< endl;
size_t subresult = 0;
size_t subsize = 0;
if (i == 1)
{
size_t subcount = 0;
for (const auto& p : sequences)
{
size_t size = base_size + 8 + ceil(static_cast<float>(bitsize)* p.first / 8);
size += size % 8 == 0
? 0
: 8 - (size % 8);
size *= p.second;
subresult += size;
subsize += p.second;
subcount += p.second * p.first;
/*
cout << " For Length: " << p.first
<< endl
<< " # Sequences: " << p.second
<< endl
<< " String size: " << ceil((static_cast<float>(bitsize) * p.first) / 8)
<< " bytes"
<< endl
<< " Size: " << size
<< " bytes"
<< endl
<< " Average size: " << (size / p.second)
<< " bytes"
<< endl;
*/
}
subresult += (base_size + 8 + ceil(static_cast<float>(bitsize) / 8)) * (frequency[1].first - subcount);
cout << " Subcount: " << subcount << endl;
cout << " Frequency: " << frequency[i].first << endl;
size_t average = 150;
size_t should_size =
(base_size + 8 + ceil(static_cast<float>(bitsize)*average / 8))
* frequency[i].first / average;
cout << " Sould be: "
<< should_size
<< " bytes"
<< endl;
}
else
{
size_t size = base_size + i * 8;
size += size % 8 == 0
? 0
: 8 - (size % 8);
subresult = size * frequency[i].first;
subsize = frequency[i].first;
}
cout << " Total: " << subresult << " bytes"
<< endl
<< " Average: " << (subresult / subsize) << " bytes"
<< endl;
expected += subresult;
}
cout << "Expected size: " << ceil(static_cast<float>(expected) / 1024 / 1024) << " Mbytes" << endl;
cout << "Original size: " << ceil(static_cast<float>(sum_inserted) / 1024 / 1024)
<< " Mbytes"
<< endl
<< "Binary size: " << (sum_inserted * bitsize / 8 / 1024 / 1024 + 1)
<< " Mbytes"
<< endl;
if (nodes <= 5000)
{
ofstream of ("machin.dot");
of << sdd::tools::dot (result, order);
}
return 0;
}
<|endoftext|>
|
<commit_before>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_SOCKET_ABSTRACT_SOCKET_
#define POSEIDON_SOCKET_ABSTRACT_SOCKET_
#include "../fwd.hpp"
#include "enums.hpp"
#include "socket_address.hpp"
namespace poseidon {
class Abstract_Socket
: public ::asteria::Rcfwd<Abstract_Socket>
{
friend Network_Driver;
protected:
unique_FD m_fd;
atomic_relaxed<bool> m_resident = { false }; // don't delete if orphaned
// These are used by network driver.
uint64_t m_epoll_data = UINT64_MAX;
uint32_t m_epoll_events = UINT32_MAX;
// This the local address. It is initialized upon the first request.
mutable once_flag m_local_addr_once;
mutable Socket_Address m_local_addr;
// These are I/O components.
mutable simple_mutex m_io_mutex;
Connection_State m_connection_state = connection_state_empty;
linear_buffer m_rqueue;
linear_buffer m_wqueue;
protected:
// Adopts a foreign or accepted socket.
explicit
Abstract_Socket(unique_FD&& fd);
// Creates a new non-blocking socket.
explicit
Abstract_Socket(::sa_family_t family, int type, int protocol = 0);
protected:
// The network driver notifies incoming data via this callback.
// `lock` shall lock `*this` after the call if locking is supported.
// Please mind thread safety, as this function is called by the network thread.
virtual
IO_Result
do_socket_on_poll_read(simple_mutex::unique_lock& lock)
= 0;
// This function shall return the number of bytes that are pending for writing.
// `lock` shall lock `*this` after the call if locking is supported.
virtual
size_t
do_write_queue_size(simple_mutex::unique_lock& lock) const
= 0;
// The network driver notifies possibility of outgoing data via this callback.
// `lock` shall lock `*this` after the call if locking is supported.
// Please mind thread safety, as this function is called by the network thread.
virtual
IO_Result
do_socket_on_poll_write(simple_mutex::unique_lock& lock)
= 0;
// The network driver notifies closure via this callback.
// `err` is zero for graceful shutdown.
// Please mind thread safety, as this function is called by the network thread.
virtual
void
do_socket_on_poll_close(int err)
= 0;
public:
ASTERIA_NONCOPYABLE_DESTRUCTOR(Abstract_Socket);
// Prevents this socket from being deleted if network driver holds its last
// reference.
bool
set_resident(bool value = true) noexcept
{ return this->m_resident.exchange(value); }
// Returns the stream descriptor.
// This is used to query and adjust stream flags. You shall not perform I/O
// operations on it.
ROCKET_PURE
int
get_fd() const noexcept
{ return this->m_fd; }
// Causes abnormal termination of this stream.
// Any data that have not been delivered to the other peer are discarded.
// The other peer is likely to see a 'connection reset by peer' error.
void
kill() noexcept;
// Gets the (bound) address of the local peer.
const Socket_Address&
get_local_address() const;
};
} // namespace poseidon
#endif
<commit_msg>abstract_socket: Make private data private<commit_after>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_SOCKET_ABSTRACT_SOCKET_
#define POSEIDON_SOCKET_ABSTRACT_SOCKET_
#include "../fwd.hpp"
#include "enums.hpp"
#include "socket_address.hpp"
namespace poseidon {
class Abstract_Socket
: public ::asteria::Rcfwd<Abstract_Socket>
{
friend Network_Driver;
private:
unique_FD m_fd;
atomic_relaxed<bool> m_resident = { false }; // don't delete if orphaned
// These are used by network driver.
uint64_t m_epoll_data = UINT64_MAX;
uint32_t m_epoll_events = UINT32_MAX;
// This the local address. It is initialized upon the first request.
mutable once_flag m_local_addr_once;
mutable Socket_Address m_local_addr;
protected:
// These are I/O components.
mutable simple_mutex m_io_mutex;
Connection_State m_connection_state = connection_state_empty;
linear_buffer m_rqueue;
linear_buffer m_wqueue;
protected:
// Adopts a foreign or accepted socket.
explicit
Abstract_Socket(unique_FD&& fd);
// Creates a new non-blocking socket.
explicit
Abstract_Socket(::sa_family_t family, int type, int protocol = 0);
protected:
// The network driver notifies incoming data via this callback.
// `lock` shall lock `*this` after the call if locking is supported.
// Please mind thread safety, as this function is called by the network thread.
virtual
IO_Result
do_socket_on_poll_read(simple_mutex::unique_lock& lock)
= 0;
// This function shall return the number of bytes that are pending for writing.
// `lock` shall lock `*this` after the call if locking is supported.
virtual
size_t
do_write_queue_size(simple_mutex::unique_lock& lock) const
= 0;
// The network driver notifies possibility of outgoing data via this callback.
// `lock` shall lock `*this` after the call if locking is supported.
// Please mind thread safety, as this function is called by the network thread.
virtual
IO_Result
do_socket_on_poll_write(simple_mutex::unique_lock& lock)
= 0;
// The network driver notifies closure via this callback.
// `err` is zero for graceful shutdown.
// Please mind thread safety, as this function is called by the network thread.
virtual
void
do_socket_on_poll_close(int err)
= 0;
public:
ASTERIA_NONCOPYABLE_DESTRUCTOR(Abstract_Socket);
// Prevents this socket from being deleted if network driver holds its last
// reference.
bool
set_resident(bool value = true) noexcept
{ return this->m_resident.exchange(value); }
// Returns the stream descriptor.
// This is used to query and adjust stream flags. You shall not perform I/O
// operations on it.
ROCKET_PURE
int
get_fd() const noexcept
{ return this->m_fd; }
// Causes abnormal termination of this stream.
// Any data that have not been delivered to the other peer are discarded.
// The other peer is likely to see a 'connection reset by peer' error.
void
kill() noexcept;
// Gets the (bound) address of the local peer.
const Socket_Address&
get_local_address() const;
};
} // namespace poseidon
#endif
<|endoftext|>
|
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <string.h>
#include <fnordmetric/sql/svalue.h>
#include <fnordmetric/sql/symboltable.h>
#include <fnordmetric/util/runtimeexception.h>
namespace fnordmetric {
namespace query {
void eqExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 2);
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_INTEGER:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() == rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getInteger() == rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getFloat() == rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() == rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
RAISE(util::RuntimeException, "can't compare %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __eq_symbol("eq", &eqExpr);
void andExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 2);
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_BOOL:
switch(rhs->getType()) {
case SValue::T_BOOL:
*out = SValue(lhs->getBool() && rhs->getBool());
return;
}
}
assert(0);
}
static SymbolTableEntry __and_symbol("and", &andExpr);
void orExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 2);
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_BOOL:
switch(rhs->getType()) {
case SValue::T_BOOL:
*out = SValue(lhs->getBool() || rhs->getBool());
return;
}
}
assert(0);
}
static SymbolTableEntry __or_symbol("or", &orExpr);
void negExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 1);
SValue* val = argv;
switch(val->getType()) {
case SValue::T_INTEGER:
*out = SValue(val->getInteger() * -1);
return;
case SValue::T_FLOAT:
*out = SValue(val->getFloat() * -1.0f);
return;
case SValue::T_BOOL:
*out = SValue(!val->getBool());
return;
default:
break;
}
assert(0);
}
static SymbolTableEntry __neg_symbol("neg", &negExpr);
void ltExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 2);
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_INTEGER:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() < rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getInteger() < rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getFloat() < rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() < rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
assert(0);
}
static SymbolTableEntry __lt_symbol("lt", <Expr);
void gtExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 2);
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_INTEGER:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() > rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getInteger() > rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getFloat() > rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() > rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
assert(0); // FIXPAUL
}
static SymbolTableEntry __gt_symbol("gt", >Expr);
}
}
<commit_msg>boolean expressions...<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <string.h>
#include <fnordmetric/sql/svalue.h>
#include <fnordmetric/sql/symboltable.h>
#include <fnordmetric/util/runtimeexception.h>
namespace fnordmetric {
namespace query {
void eqExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 2);
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_INTEGER:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() == rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getInteger() == rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getFloat() == rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() == rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
*out = SValue(*lhs == *rhs);
}
static SymbolTableEntry __eq_symbol("eq", &eqExpr);
void andExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 2);
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_BOOL:
switch(rhs->getType()) {
case SValue::T_BOOL:
*out = SValue(lhs->getBool() && rhs->getBool());
return;
}
}
RAISE(util::RuntimeException, "can't AND %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __and_symbol("and", &andExpr);
void orExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 2);
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_BOOL:
switch(rhs->getType()) {
case SValue::T_BOOL:
*out = SValue(lhs->getBool() || rhs->getBool());
return;
}
}
RAISE(util::RuntimeException, "can't OR %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __or_symbol("or", &orExpr);
void negExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 1);
SValue* val = argv;
switch(val->getType()) {
case SValue::T_INTEGER:
*out = SValue(val->getInteger() * -1);
return;
case SValue::T_FLOAT:
*out = SValue(val->getFloat() * -1.0f);
return;
case SValue::T_BOOL:
*out = SValue(!val->getBool());
return;
default:
break;
}
RAISE(util::RuntimeException, "can't negate %s",
val->getTypeName());
}
static SymbolTableEntry __neg_symbol("neg", &negExpr);
void ltExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 2);
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_INTEGER:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() < rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getInteger() < rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getFloat() < rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() < rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
RAISE(util::RuntimeException, "can't compare %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __lt_symbol("lt", <Expr);
void gtExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
assert(argc == 2);
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_INTEGER:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() > rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getInteger() > rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getFloat() > rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() > rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
RAISE(util::RuntimeException, "can't compare %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __gt_symbol("gt", >Expr);
}
}
<|endoftext|>
|
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <string.h>
#include <fnordmetric/sql/svalue.h>
#include <fnordmetric/sql/symboltable.h>
#include <fnordmetric/util/runtimeexception.h>
namespace fnordmetric {
namespace query {
void eqExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 2) {
RAISE(
util::RuntimeException,
"wrong number of arguments for eq. expected: 2, got: %i", argc);
}
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
switch(rhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() == rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() == rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() == rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
if (lhs->getType() == SValue::T_STRING ||
rhs->getType() == SValue::T_STRING) {
*out = SValue(lhs->toString() == rhs->toString());
return;
}
RAISE(util::RuntimeException, "can't compare %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __eq_symbol("eq", &eqExpr);
void andExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 2) {
RAISE(
util::RuntimeException,
"wrong number of arguments for and. expected: 2, got: %i", argc);
}
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_BOOL:
switch(rhs->getType()) {
case SValue::T_BOOL:
*out = SValue(lhs->getBool() && rhs->getBool());
return;
}
}
RAISE(util::RuntimeException, "can't AND %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __and_symbol("and", &andExpr);
void orExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 2) {
RAISE(
util::RuntimeException,
"wrong number of arguments for or. expected: 2, got: %i", argc);
}
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_BOOL:
switch(rhs->getType()) {
case SValue::T_BOOL:
*out = SValue(lhs->getBool() || rhs->getBool());
return;
}
}
RAISE(util::RuntimeException, "can't OR %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __or_symbol("or", &orExpr);
void negExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 1) {
RAISE(
util::RuntimeException,
"wrong number of arguments for neg. expected: 1, got: %i", argc);
}
SValue* val = argv;
switch(val->getType()) {
case SValue::T_INTEGER:
*out = SValue(val->getInteger() * -1);
return;
case SValue::T_FLOAT:
*out = SValue(val->getFloat() * -1.0f);
return;
case SValue::T_BOOL:
*out = SValue(!val->getBool());
return;
default:
break;
}
RAISE(util::RuntimeException, "can't negate %s",
val->getTypeName());
}
static SymbolTableEntry __neg_symbol("neg", &negExpr);
void ltExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 2) {
RAISE(
util::RuntimeException,
"wrong number of arguments for lt. expected: 2, got: %i", argc);
}
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_INTEGER:
switch(rhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() < rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getInteger() < rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getFloat() < rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() < rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
RAISE(util::RuntimeException, "can't compare %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __lt_symbol("lt", <Expr);
void gtExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 2) {
RAISE(
util::RuntimeException,
"wrong number of arguments for gt. expected: 2, got: %i", argc);
}
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_INTEGER:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() > rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getInteger() > rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->getType()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getFloat() > rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() > rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
RAISE(util::RuntimeException, "can't ompare %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __gt_symbol("gt", >Expr);
}
}
<commit_msg>numeric conversion in lt/gt expressions<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <string.h>
#include <fnordmetric/sql/svalue.h>
#include <fnordmetric/sql/symboltable.h>
#include <fnordmetric/util/runtimeexception.h>
namespace fnordmetric {
namespace query {
void eqExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 2) {
RAISE(
util::RuntimeException,
"wrong number of arguments for eq. expected: 2, got: %i", argc);
}
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
switch(rhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() == rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() == rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() == rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
if (lhs->getType() == SValue::T_STRING ||
rhs->getType() == SValue::T_STRING) {
*out = SValue(lhs->toString() == rhs->toString());
return;
}
RAISE(util::RuntimeException, "can't compare %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __eq_symbol("eq", &eqExpr);
void andExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 2) {
RAISE(
util::RuntimeException,
"wrong number of arguments for and. expected: 2, got: %i", argc);
}
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_BOOL:
switch(rhs->getType()) {
case SValue::T_BOOL:
*out = SValue(lhs->getBool() && rhs->getBool());
return;
}
}
RAISE(util::RuntimeException, "can't AND %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __and_symbol("and", &andExpr);
void orExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 2) {
RAISE(
util::RuntimeException,
"wrong number of arguments for or. expected: 2, got: %i", argc);
}
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->getType()) {
case SValue::T_BOOL:
switch(rhs->getType()) {
case SValue::T_BOOL:
*out = SValue(lhs->getBool() || rhs->getBool());
return;
}
}
RAISE(util::RuntimeException, "can't OR %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __or_symbol("or", &orExpr);
void negExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 1) {
RAISE(
util::RuntimeException,
"wrong number of arguments for neg. expected: 1, got: %i", argc);
}
SValue* val = argv;
switch(val->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
*out = SValue(val->getInteger() * -1);
return;
case SValue::T_FLOAT:
*out = SValue(val->getFloat() * -1.0f);
return;
case SValue::T_BOOL:
*out = SValue(!val->getBool());
return;
default:
break;
}
RAISE(util::RuntimeException, "can't negate %s",
val->getTypeName());
}
static SymbolTableEntry __neg_symbol("neg", &negExpr);
void ltExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 2) {
RAISE(
util::RuntimeException,
"wrong number of arguments for lt. expected: 2, got: %i", argc);
}
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
switch(rhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() < rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() < rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() < rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
RAISE(util::RuntimeException, "can't compare %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __lt_symbol("lt", <Expr);
void gtExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
if (argc != 2) {
RAISE(
util::RuntimeException,
"wrong number of arguments for gt. expected: 2, got: %i", argc);
}
SValue* lhs = argv;
SValue* rhs = argv + 1;
switch(lhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
switch(rhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
*out = SValue(lhs->getInteger() > rhs->getInteger());
return;
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() > rhs->getFloat());
return;
default:
break;
}
break;
case SValue::T_FLOAT:
switch(rhs->testTypeWithNumericConversion()) {
case SValue::T_INTEGER:
case SValue::T_FLOAT:
*out = SValue(lhs->getFloat() > rhs->getFloat());
return;
default:
break;
}
break;
default:
break;
}
RAISE(util::RuntimeException, "can't compare %s with %s",
lhs->getTypeName(),
rhs->getTypeName());
}
static SymbolTableEntry __gt_symbol("gt", >Expr);
}
}
<|endoftext|>
|
<commit_before>
#include "util/zorba.h"
#include "store/naive/qname_pool.h"
namespace xqp
{
QNamePool* QNameImpl::theQNamePool = NULL;
//const xqp_unsignedLong QNamePool::MAX_CACHE_SIZE = 65536;
const float QNamePool::DEFAULT_LOAD_FACTOR = 0.6;
/////////////////////////////////////////////////////////////////////////////////
// //
// QNamePool //
// //
/////////////////////////////////////////////////////////////////////////////////
/*******************************************************************************
********************************************************************************/
QNamePool::QNamePool(xqp_unsignedLong size)
:
theCache(new QNameImpl[size]),
theCacheSize(size),
theFirstFree(1),
theNumFree(size - 1),
theNumQNames(0),
theHashTabSize(2 * size),
theLoadFactor(DEFAULT_LOAD_FACTOR)
{
// Put all the preallocated slots in the free list of the cahce.
for (xqp_unsignedLong i = 1; i < size - 1; i++)
{
theCache[i].theNextFree = i + 1;
theCache[i].thePrevFree = i - 1;
theCache[i].thePosition = i;
}
theCache[size-1].theNextFree = 0;
theCache[size-1].thePrevFree = size - 2;
theCache[size-1].thePosition = size - 1;
// Allocate the hash table. Its initial size is double the size of theCache,
// plus an inital 32 overflow entries.
theHashTab.resize(theHashTabSize + 32);
// Format the overflow area of theHashTab as a list of free entries
HashEntry* lastentry = &theHashTab[theHashTabSize + 31];
for (HashEntry* entry = &theHashTab[theHashTabSize]; entry < lastentry; entry++)
entry->theNext = entry + 1;
}
/*******************************************************************************
********************************************************************************/
QNamePool::~QNamePool()
{
#if 0
xqp_unsignedLong n = theOverflow.size();
for (xqp_unsignedLong i = 0; i < n; i++)
{
if (theOverflow[i] != NULL)
delete theOverflow[i];
}
#else
xqp_unsignedLong n = theHashTab.size();
for (xqp_unsignedLong i = 0; i < n; i++)
{
if (theHashTab[i].theQName != NULL && theHashTab[i].theQName->isOverflow())
::delete theHashTab[i].theQName;
}
#endif
if (theCache != NULL)
{
delete [] theCache;
theCache = NULL;
}
}
/*******************************************************************************
********************************************************************************/
QNameImpl* QNamePool::insert(
const char* ns,
const char* pre,
const char* ln)
{
QNameImpl* qn;
HashEntry* entry = hash(ns, pre, ln);
// If the qname is already in the pool, return a ptr to its containing slot.
// If the slot is in the free list of the cache, it is first removed from
// that list.
if (entry->theQName != NULL)
{
qn = entry->theQName;
if (qn->isInCache())
{
if (qn->theNextFree != 0)
theCache[qn->theNextFree].thePrevFree = qn->thePrevFree;
if (qn->thePrevFree != 0)
{
theCache[qn->thePrevFree].theNextFree = qn->theNextFree;
}
else if (theFirstFree == qn->thePosition)
{
theFirstFree = qn->theNextFree;
}
qn->theNextFree = qn->thePrevFree = 0;
theNumFree--;
}
return qn;
}
// The qname is not in the pool.
// Use the 1st slot from the free list of the cache to store the new qname.
// The qname was is currently in that slot is removed from the cache.
if (theFirstFree != 0)
{
qn = &theCache[theFirstFree];
entry->theQName = qn;
theFirstFree = qn->theNextFree;
theCache[theFirstFree].thePrevFree = 0;
if (!qn->theLocal.empty())
unhash(qn->theNamespace.c_str(), qn->thePrefix.c_str(), qn->theLocal.c_str());
qn->theNextFree = qn->thePrevFree = 0;
qn->theNamespace = ns;
qn->thePrefix = pre;
qn->theLocal = ln;
theNumFree--;
return qn;
}
// The cache was full, so allocate a QNameItem from the heap.
qn = new QNameImpl(ns, pre, ln);
//theOverflow.push_back(qn);
entry->theQName = qn;
return qn;
}
/*******************************************************************************
********************************************************************************/
void QNamePool::remove(QNameImpl* qn)
{
if (qn->get_refCount() > 0)
return;
if (qn->isInCache())
{
qn->theNextFree = theFirstFree;
theCache[theFirstFree].thePrevFree = qn->thePosition;
theFirstFree = qn->thePosition;
theNumFree++;
}
else
{
// If all the pointers to QNameItems were smart pointers, we could leave
// qn in the pool, and let the pool garbage-collect it later (if it still
// unused). If however QNameItems may be referenced by regular pointers as
// well, then qn must be removed from the pool and really deleted
unhash(qn->getNamespace().c_str(),
qn->getPrefix().c_str(),
qn->getLocalName().c_str());
//std::vector<QNameImpl *>::iterator it;
//it = theOverflow.begin() + qn->thePosition;
//theOverflow.erase(it);
::delete qn;
}
}
/*******************************************************************************
Check if the given qname is already in the pool, and if so, return its hash
entry. If not, allocate a new hash entry for it, and return it to the caller.
********************************************************************************/
QNamePool::HashEntry*
QNamePool::hash(const char* ns, const char* pre, const char* ln)
{
xqp_unsignedLong len;
HashEntry* entry;
HashEntry* lastentry;
// Get ptr to the 1st entry of the hash bucket corresponding to the given qname
xqp_unsignedLong hval = hashfun::h32(pre, hashfun::h32(ln, hashfun::h32(ns))) % theHashTabSize;
entry = &theHashTab[ hval % theHashTabSize];
// If the hash bucket is empty, its 1st entry is used to store the new qname.
if (entry->isFree())
{
theNumQNames++;
return entry;
}
// Search the hash bucket looking for the given qname.
while (entry != NULL)
{
QNameImpl* qn = entry->theQName;
len = qn->theLocal.bytes();
if (len != strlen(ln) || memcmp(qn->theLocal.c_str(), ln, len) != 0)
{
lastentry = entry;
entry = entry->theNext;
continue;
}
len = qn->theNamespace.bytes();
if (len != strlen(ns) || memcmp(qn->theNamespace.c_str(), ns, len) != 0)
{
lastentry = entry;
entry = entry->theNext;
continue;
}
len = qn->thePrefix.bytes();
if (len != strlen(pre) || memcmp(qn->thePrefix.c_str(), pre, len) != 0)
{
lastentry = entry;
entry = entry->theNext;
continue;
}
return entry;
}
// The qname was not found.
// Double the size of hash table if it is more than 60% full.
if (theNumQNames > theHashTabSize * theLoadFactor)
resizeHashTab();
// Get an entry from the free list in the overflow section of the hash teble
// If no free entry exists, a new entry is appended into the hash table.
if (theHashTab[theHashTabSize].theNext == 0)
{
theHashTab.push_back(HashEntry());
entry = &theHashTab[theHashTab.size() - 1];
lastentry->theNext = entry;
}
else
{
entry = theHashTab[theHashTabSize].theNext;
theHashTab[theHashTabSize].theNext = entry->theNext;
lastentry->theNext = entry;
entry->theNext = NULL;
}
theNumQNames++;
return entry;
}
/*******************************************************************************
Remove the given qname from the hash table, if it is found there.
********************************************************************************/
void QNamePool::unhash(const char* ns, const char* pre, const char* ln)
{
xqp_unsignedLong len;
HashEntry* entry;
HashEntry* preventry = NULL;
// Get ptr to the 1st entry of the hash bucket corresponding to the given qname
xqp_unsignedLong hval = hashfun::h32(pre, hashfun::h32(ln, hashfun::h32(ns))) % theHashTabSize;
entry = &theHashTab[ hval % theHashTabSize];
// If the hash bucket is empty, the qname is not in the hash table.
if (entry->isFree())
return;
// Search the hash bucket looking for the given qname.
while (entry != NULL)
{
QNameImpl* qn = entry->theQName;
len = qn->theLocal.bytes();
if (len != strlen(ln) || memcmp(qn->theLocal.c_str(), ln, len) != 0)
{
preventry = entry;
entry = entry->theNext;
continue;
}
len = qn->theNamespace.bytes();
if (len != strlen(ns) || memcmp(qn->theNamespace.c_str(), ns, len) != 0)
{
preventry = entry;
entry = entry->theNext;
continue;
}
len = qn->thePrefix.bytes();
if (len != strlen(pre) || memcmp(qn->thePrefix.c_str(), pre, len) != 0)
{
preventry = entry;
entry = entry->theNext;
continue;
}
// Found the qname in the current entry. Must remove the entry from the
// hash bucket and add it to the free list.
if (preventry != NULL)
{
preventry->theNext = entry->theNext;
entry->theQName = NULL;
entry->theNext = theHashTab[theHashTabSize].theNext;
theHashTab[theHashTabSize].theNext = entry;
}
else if (entry->theNext != NULL)
{
HashEntry* nextentry = entry->theNext;
*entry = *nextentry;
nextentry->theQName = NULL;
nextentry->theNext = theHashTab[theHashTabSize].theNext;
theHashTab[theHashTabSize].theNext = nextentry;
}
else
{
entry->theQName = NULL;
}
theNumQNames--;
return;
}
}
/*******************************************************************************
********************************************************************************/
void QNamePool::resizeHashTab()
{
HashEntry* entry;
HashEntry* lastentry;
// Make a copy of theHashTab, and then resize it to double theHashTabSize
std::vector<HashEntry> oldTab = theHashTab;
xqp_unsignedLong oldsize = oldTab.size();
theHashTabSize <<= 1;
theHashTab.clear();
theHashTab.resize(theHashTabSize + 32);
// Format the overflow area of theHashTab as a list of free entries
lastentry = &theHashTab[theHashTabSize + 31];
for (entry = &theHashTab[theHashTabSize]; entry < lastentry; entry++)
entry->theNext = entry + 1;
// Now rehash every entry
for (xqp_unsignedLong i = 0; i < oldsize; i++)
{
QNameImpl* qn = oldTab[i].theQName;
xqp_unsignedLong h = hashfun::h32(qn->thePrefix.c_str(),
hashfun::h32(qn->theLocal.c_str(),
hashfun::h32(qn->theNamespace.c_str())));
entry = &theHashTab[h % theHashTabSize];
if (!entry->isFree())
{
// Go to the last entry of the current bucket
HashEntry* lastentry = entry;
while (lastentry->theNext != NULL)
lastentry = lastentry->theNext;
// Get an entry from the free list in the overflow section of the hash
// table. If no free entry exists, a new entry is appended into the table.
if (theHashTab[theHashTabSize].theNext == 0)
{
theHashTab.push_back(HashEntry());
entry = &theHashTab[theHashTab.size() - 1];
lastentry->theNext = entry;
}
else
{
entry = theHashTab[theHashTabSize].theNext;
theHashTab[theHashTabSize].theNext = entry->theNext;
lastentry->theNext = entry;
entry->theNext = NULL;
}
}
entry->theQName = qn;
}
}
/////////////////////////////////////////////////////////////////////////////////
// //
// QNameItem //
// //
/////////////////////////////////////////////////////////////////////////////////
QNameImpl::QNameImpl(
const xqp_string& ns,
const xqp_string& pre,
const xqp_string& local)
:
theNamespace(ns),
thePrefix (pre),
theLocal(local),
theNextFree(0),
thePrevFree(0)
{
}
QNameImpl::QNameImpl(
const char* ns,
const char* pre,
const char* local)
:
theNamespace(ns),
thePrefix (pre),
theLocal(local),
theNextFree(0),
thePrevFree(0)
{
}
void QNameImpl::setQNamePool(QNamePool* p)
{
theQNamePool = p;
}
void QNameImpl::free()
{
getQNamePool()->remove(this);
}
qnamekey_t QNameImpl::getQNameKey( ) const
{
return Item::createQNameKey(theNamespace, thePrefix, theLocal);
}
Item_t QNameImpl::getAtomizationValue( ) const
{
return zorba::getItemFactory()->createQName(theNamespace, thePrefix, theLocal).get_ptr();
}
bool QNameImpl::equals(Item_t item) const
{
return (this == item.get_ptr() ||
(item->getNamespace() == theNamespace &&
item->getLocalName() == theLocal));
}
Item_t QNameImpl::getEBV( ) const
{
ZorbaErrorAlerts::error_alert (
error_messages::FORG0006_INVALID_ARGUMENT_TYPE,
error_messages::RUNTIME_ERROR,
NULL,
false,
"Effective Boolean Value is not defined for QName!");
return NULL;
}
xqp_string QNameImpl::getStringProperty( ) const
{
return thePrefix != "" ? thePrefix + ":" + theLocal : theLocal;
}
xqp_string QNameImpl::show() const
{
return "xs:qname(" + theNamespace + "," + thePrefix + "," + theLocal + ")";
}
}
<commit_msg>tiny (?) optimizations in qnamae pool constructor/desctructor<commit_after>
#include "util/zorba.h"
#include "store/naive/qname_pool.h"
namespace xqp
{
QNamePool* QNameImpl::theQNamePool = NULL;
const float QNamePool::DEFAULT_LOAD_FACTOR = 0.6;
/////////////////////////////////////////////////////////////////////////////////
// //
// QNamePool //
// //
/////////////////////////////////////////////////////////////////////////////////
/*******************************************************************************
********************************************************************************/
QNamePool::QNamePool(xqp_unsignedLong size)
:
theCache(new QNameImpl[size]),
theCacheSize(size),
theFirstFree(1),
theNumFree(size - 1),
theNumQNames(0),
theHashTabSize(2 * size),
theLoadFactor(DEFAULT_LOAD_FACTOR)
{
// Put all the preallocated slots in the free list of the cahce.
QNameImpl* qn = &theCache[1];
QNameImpl* last = qn + size - 1;
for (xqp_unsignedLong i = 1; qn < last; qn++, i++)
{
qn->theNextFree = i + 1;
qn->thePrevFree = i - 1;
qn->thePosition = i;
}
qn->theNextFree = 0;
// Allocate the hash table. Its initial size is double the size of theCache,
// plus an inital 32 overflow entries.
theHashTab.resize(theHashTabSize + 32);
// Format the overflow area of theHashTab as a list of free entries
HashEntry* lastentry = &theHashTab[theHashTabSize + 31];
for (HashEntry* entry = &theHashTab[theHashTabSize]; entry < lastentry; entry++)
entry->theNext = entry + 1;
}
/*******************************************************************************
********************************************************************************/
QNamePool::~QNamePool()
{
#if 0
xqp_unsignedLong n = theOverflow.size();
for (xqp_unsignedLong i = 0; i < n; i++)
{
if (theOverflow[i] != NULL)
delete theOverflow[i];
}
#else
xqp_unsignedLong n = theHashTab.size();
for (xqp_unsignedLong i = 0; i < n; i++)
{
if (theHashTab[i].theQName != NULL && theHashTab[i].theQName->isOverflow())
::delete theHashTab[i].theQName;
}
#endif
if (theCache != NULL)
{
delete [] theCache;
theCache = NULL;
}
}
/*******************************************************************************
********************************************************************************/
QNameImpl* QNamePool::insert(
const char* ns,
const char* pre,
const char* ln)
{
QNameImpl* qn;
HashEntry* entry = hash(ns, pre, ln);
// If the qname is already in the pool, return a ptr to its containing slot.
// If the slot is in the free list of the cache, it is first removed from
// that list.
if (entry->theQName != NULL)
{
qn = entry->theQName;
if (qn->isInCache())
{
if (qn->theNextFree != 0)
theCache[qn->theNextFree].thePrevFree = qn->thePrevFree;
if (qn->thePrevFree != 0)
{
theCache[qn->thePrevFree].theNextFree = qn->theNextFree;
}
else if (theFirstFree == qn->thePosition)
{
theFirstFree = qn->theNextFree;
}
qn->theNextFree = qn->thePrevFree = 0;
theNumFree--;
}
return qn;
}
// The qname is not in the pool.
// Use the 1st slot from the free list of the cache to store the new qname.
// The qname was is currently in that slot is removed from the cache.
if (theFirstFree != 0)
{
qn = &theCache[theFirstFree];
entry->theQName = qn;
theFirstFree = qn->theNextFree;
theCache[theFirstFree].thePrevFree = 0;
if (!qn->theLocal.empty())
unhash(qn->theNamespace.c_str(), qn->thePrefix.c_str(), qn->theLocal.c_str());
qn->theNextFree = qn->thePrevFree = 0;
qn->theNamespace = ns;
qn->thePrefix = pre;
qn->theLocal = ln;
theNumFree--;
return qn;
}
// The cache was full, so allocate a QNameItem from the heap.
qn = new QNameImpl(ns, pre, ln);
//theOverflow.push_back(qn);
entry->theQName = qn;
return qn;
}
/*******************************************************************************
********************************************************************************/
void QNamePool::remove(QNameImpl* qn)
{
if (qn->get_refCount() > 0)
return;
if (qn->isInCache())
{
qn->theNextFree = theFirstFree;
theCache[theFirstFree].thePrevFree = qn->thePosition;
theFirstFree = qn->thePosition;
theNumFree++;
}
else
{
// If all the pointers to QNameItems were smart pointers, we could leave
// qn in the pool, and let the pool garbage-collect it later (if it still
// unused). If however QNameItems may be referenced by regular pointers as
// well, then qn must be removed from the pool and really deleted
unhash(qn->getNamespace().c_str(),
qn->getPrefix().c_str(),
qn->getLocalName().c_str());
//std::vector<QNameImpl *>::iterator it;
//it = theOverflow.begin() + qn->thePosition;
//theOverflow.erase(it);
::delete qn;
}
}
/*******************************************************************************
Check if the given qname is already in the pool, and if so, return its hash
entry. If not, allocate a new hash entry for it, and return it to the caller.
********************************************************************************/
QNamePool::HashEntry*
QNamePool::hash(const char* ns, const char* pre, const char* ln)
{
xqp_unsignedLong len;
HashEntry* entry;
HashEntry* lastentry;
// Get ptr to the 1st entry of the hash bucket corresponding to the given qname
xqp_unsignedLong hval = hashfun::h32(pre,
hashfun::h32(ln,
hashfun::h32(ns))) % theHashTabSize;
entry = &theHashTab[ hval % theHashTabSize];
// If the hash bucket is empty, its 1st entry is used to store the new qname.
if (entry->isFree())
{
theNumQNames++;
return entry;
}
// Search the hash bucket looking for the given qname.
while (entry != NULL)
{
QNameImpl* qn = entry->theQName;
len = qn->theLocal.bytes();
if (len != strlen(ln) || memcmp(qn->theLocal.c_str(), ln, len) != 0)
{
lastentry = entry;
entry = entry->theNext;
continue;
}
len = qn->theNamespace.bytes();
if (len != strlen(ns) || memcmp(qn->theNamespace.c_str(), ns, len) != 0)
{
lastentry = entry;
entry = entry->theNext;
continue;
}
len = qn->thePrefix.bytes();
if (len != strlen(pre) || memcmp(qn->thePrefix.c_str(), pre, len) != 0)
{
lastentry = entry;
entry = entry->theNext;
continue;
}
return entry;
}
// The qname was not found.
// Double the size of hash table if it is more than 60% full.
if (theNumQNames > theHashTabSize * theLoadFactor)
resizeHashTab();
// Get an entry from the free list in the overflow section of the hash teble
// If no free entry exists, a new entry is appended into the hash table.
if (theHashTab[theHashTabSize].theNext == 0)
{
theHashTab.push_back(HashEntry());
entry = &theHashTab[theHashTab.size() - 1];
lastentry->theNext = entry;
}
else
{
entry = theHashTab[theHashTabSize].theNext;
theHashTab[theHashTabSize].theNext = entry->theNext;
lastentry->theNext = entry;
entry->theNext = NULL;
}
theNumQNames++;
return entry;
}
/*******************************************************************************
Remove the given qname from the hash table, if it is found there.
********************************************************************************/
void QNamePool::unhash(const char* ns, const char* pre, const char* ln)
{
xqp_unsignedLong len;
HashEntry* entry;
HashEntry* preventry = NULL;
// Get ptr to the 1st entry of the hash bucket corresponding to the given qname
xqp_unsignedLong hval = hashfun::h32(pre,
hashfun::h32(ln,
hashfun::h32(ns))) % theHashTabSize;
entry = &theHashTab[ hval % theHashTabSize];
// If the hash bucket is empty, the qname is not in the hash table.
if (entry->isFree())
return;
// Search the hash bucket looking for the given qname.
while (entry != NULL)
{
QNameImpl* qn = entry->theQName;
len = qn->theLocal.bytes();
if (len != strlen(ln) || memcmp(qn->theLocal.c_str(), ln, len) != 0)
{
preventry = entry;
entry = entry->theNext;
continue;
}
len = qn->theNamespace.bytes();
if (len != strlen(ns) || memcmp(qn->theNamespace.c_str(), ns, len) != 0)
{
preventry = entry;
entry = entry->theNext;
continue;
}
len = qn->thePrefix.bytes();
if (len != strlen(pre) || memcmp(qn->thePrefix.c_str(), pre, len) != 0)
{
preventry = entry;
entry = entry->theNext;
continue;
}
// Found the qname in the current entry. Must remove the entry from the
// hash bucket and add it to the free list.
if (preventry != NULL)
{
preventry->theNext = entry->theNext;
entry->theQName = NULL;
entry->theNext = theHashTab[theHashTabSize].theNext;
theHashTab[theHashTabSize].theNext = entry;
}
else if (entry->theNext != NULL)
{
HashEntry* nextentry = entry->theNext;
*entry = *nextentry;
nextentry->theQName = NULL;
nextentry->theNext = theHashTab[theHashTabSize].theNext;
theHashTab[theHashTabSize].theNext = nextentry;
}
else
{
entry->theQName = NULL;
}
theNumQNames--;
return;
}
}
/*******************************************************************************
********************************************************************************/
void QNamePool::resizeHashTab()
{
HashEntry* entry;
HashEntry* lastentry;
// Make a copy of theHashTab, and then resize it to double theHashTabSize
std::vector<HashEntry> oldTab = theHashTab;
xqp_unsignedLong oldsize = oldTab.size();
theHashTabSize <<= 1;
theHashTab.clear();
theHashTab.resize(theHashTabSize + 32);
// Format the overflow area of theHashTab as a list of free entries
lastentry = &theHashTab[theHashTabSize + 31];
for (entry = &theHashTab[theHashTabSize]; entry < lastentry; entry++)
entry->theNext = entry + 1;
// Now rehash every entry
for (xqp_unsignedLong i = 0; i < oldsize; i++)
{
QNameImpl* qn = oldTab[i].theQName;
xqp_unsignedLong h = hashfun::h32(qn->thePrefix.c_str(),
hashfun::h32(qn->theLocal.c_str(),
hashfun::h32(qn->theNamespace.c_str())));
entry = &theHashTab[h % theHashTabSize];
if (!entry->isFree())
{
// Go to the last entry of the current bucket
HashEntry* lastentry = entry;
while (lastentry->theNext != NULL)
lastentry = lastentry->theNext;
// Get an entry from the free list in the overflow section of the hash
// table. If no free entry exists, a new entry is appended into the table.
if (theHashTab[theHashTabSize].theNext == 0)
{
theHashTab.push_back(HashEntry());
entry = &theHashTab[theHashTab.size() - 1];
lastentry->theNext = entry;
}
else
{
entry = theHashTab[theHashTabSize].theNext;
theHashTab[theHashTabSize].theNext = entry->theNext;
lastentry->theNext = entry;
entry->theNext = NULL;
}
}
entry->theQName = qn;
}
}
/////////////////////////////////////////////////////////////////////////////////
// //
// QNameItem //
// //
/////////////////////////////////////////////////////////////////////////////////
QNameImpl::QNameImpl(
const xqp_string& ns,
const xqp_string& pre,
const xqp_string& local)
:
theNamespace(ns),
thePrefix (pre),
theLocal(local),
theNextFree(0),
thePrevFree(0)
{
}
QNameImpl::QNameImpl(
const char* ns,
const char* pre,
const char* local)
:
theNamespace(ns),
thePrefix (pre),
theLocal(local),
theNextFree(0),
thePrevFree(0)
{
}
void QNameImpl::setQNamePool(QNamePool* p)
{
theQNamePool = p;
}
void QNameImpl::free()
{
getQNamePool()->remove(this);
}
qnamekey_t QNameImpl::getQNameKey( ) const
{
return Item::createQNameKey(theNamespace, thePrefix, theLocal);
}
Item_t QNameImpl::getAtomizationValue( ) const
{
return zorba::getItemFactory()->createQName(theNamespace, thePrefix, theLocal).get_ptr();
}
bool QNameImpl::equals(Item_t item) const
{
return (this == item.get_ptr() ||
(item->getNamespace() == theNamespace &&
item->getLocalName() == theLocal));
}
Item_t QNameImpl::getEBV( ) const
{
ZorbaErrorAlerts::error_alert (
error_messages::FORG0006_INVALID_ARGUMENT_TYPE,
error_messages::RUNTIME_ERROR,
NULL,
false,
"Effective Boolean Value is not defined for QName!");
return NULL;
}
xqp_string QNameImpl::getStringProperty( ) const
{
return thePrefix != "" ? thePrefix + ":" + theLocal : theLocal;
}
xqp_string QNameImpl::show() const
{
return "xs:qname(" + theNamespace + "," + thePrefix + "," + theLocal + ")";
}
}
<|endoftext|>
|
<commit_before>/**********************************************************
* Author : Hsin-Yi Chou
* Email : hchou@cern.ch
* Last modified : 2015-07-22 16:29
* Filename : YiProdNtuple.C
* Description :
* *******************************************************/
#ifndef __YiProdNtuple_C__
#define __YiProdNtuple_C__
#include "YiProdNtuple.h"
#include "YiProdNtuple.tcc"
#include <string.h>
int main(int argc, const char ** argv) {
COUT("\n**--------------------------**\n");
COUT("\n** YiProdNtuple START **\n");
COUT("\n**--------------------------**\n");
google::InitGoogleLogging(argv[0]);
google::SetStderrLogging(google::GLOG_FATAL);
TrackSys::Sys::SetEnv("TRACKSys_MagBox", "/ams_home/hchou/AMSData/magnetic/AMS02Mag.bin");
TrackSys::Sys::SetEnv("TRACKSys_MatBox", "/ams_home/hchou/AMSData/material");
//TrackSys::Sys::SetEnv("TRACKSys_MagBox", "/eos/ams/user/h/hchou/ExternalLibs/DB/magnetic/AMS02Mag.bin");
//TrackSys::Sys::SetEnv("TRACKSys_MatBox", "/eos/ams/user/h/hchou/ExternalLibs/DB/material");
//TrackSys::Sys::SetEnv("TRACKSys_MagBox", "/afs/cern.ch/work/h/hchou/public/DATABASE/DB/magnetic/AMS02Mag.bin");
//TrackSys::Sys::SetEnv("TRACKSys_MatBox", "/afs/cern.ch/work/h/hchou/public/DATABASE/DB/material");
YiNtuple::setSelectionMode(YiNtuple::NORM);
//YiNtuple::setSelectionMode(YiNtuple::COPY);
DataSelection::setOption(DataSelection::LIST, DataSelection::ON);
DataSelection::setOption(DataSelection::RTI, DataSelection::ON);
DataSelection::setOption(DataSelection::TRG, DataSelection::ON);
DataSelection::setOption(DataSelection::TOF, DataSelection::ON);
DataSelection::setOption(DataSelection::ACC, DataSelection::ON);
DataSelection::setOption(DataSelection::TRK, DataSelection::ON);
DataSelection::setOption(DataSelection::TRD, DataSelection::ON);
DataSelection::setOption(DataSelection::RICH, DataSelection::ON);
DataSelection::setOption(DataSelection::ECAL, DataSelection::ON);
EventBase::setEventVersion(EventBase::B950);
COUT("\n\n");
COUT("Usage : YiProdNtuple event_mode file_list group_id group_size (path)\n");
COUT(" Parameters : \n");
COUT(" event_mode [ISS BT MC]\n");
COUT(" file_list\n");
COUT(" group_id\n");
COUT(" group_size\n");
COUT(" (path)\n");
COUT("\n\n");
if (argc != 5 && argc != 6)
MGSys::ShowErrorAndExit(LOCADR(), "Number of argument is not conform! Exiting ...");
std::string event_mode = argv[1];
std::string file_list = argv[2];
Long64_t group_id = atol(argv[3]);
Long64_t group_size = atol(argv[4]);
std::use_facet<std::ctype<char> >(std::locale()).toupper(&event_mode[0], &event_mode[0] + event_mode.size());
if (event_mode == "ISS") EventBase::setEventMode(EventBase::ISS);
else if (event_mode == "BT") EventBase::setEventMode(EventBase::BT);
else if (event_mode == "MC") EventBase::setEventMode(EventBase::MC);
else MGSys::ShowErrorAndExit(LOCADR(), "Can't find event mode (ISS, BT, MC)! Exiting ...");
std::string outputFile = "";
if (YiNtuple::checkSelectionMode(YiNtuple::NORM))
outputFile = STR("YiNtuple_%s.%07ld.root", event_mode.c_str(), group_id);
else if (YiNtuple::checkSelectionMode(YiNtuple::COPY))
outputFile = STR("YiMirror_%s.%07ld.root", event_mode.c_str(), group_id);
std::string path = ".";
if (argc == 6) path = argv[5];
bool isMultiTree = false;
YiNtuple * ntuple = new YiNtuple();
ntuple->setOutputFile(outputFile, path, isMultiTree);
ntuple->readDataFrom(file_list, group_id, group_size);
ntuple->loopEventChain();
if (ntuple != nullptr) delete ntuple;
ntuple = nullptr;
COUT("\n**------------------------**\n");
COUT("\n** YiProdNtuple END **\n");
COUT("\n**------------------------**\n");
return 0;
}
#endif // __YiProdNtuple_C__
<commit_msg>update<commit_after>/**********************************************************
* Author : Hsin-Yi Chou
* Email : hchou@cern.ch
* Last modified : 2015-07-22 16:29
* Filename : YiProdNtuple.C
* Description :
* *******************************************************/
#ifndef __YiProdNtuple_C__
#define __YiProdNtuple_C__
#include "YiProdNtuple.h"
#include "YiProdNtuple.tcc"
#include <string.h>
int main(int argc, const char ** argv) {
COUT("\n**--------------------------**\n");
COUT("\n** YiProdNtuple START **\n");
COUT("\n**--------------------------**\n");
google::InitGoogleLogging(argv[0]);
google::SetStderrLogging(google::GLOG_FATAL);
//TrackSys::Sys::SetEnv("TRACKSys_MagBox", "/ams_home/hchou/AMSData/magnetic/AMS02Mag.bin");
//TrackSys::Sys::SetEnv("TRACKSys_MatBox", "/ams_home/hchou/AMSData/material");
//TrackSys::Sys::SetEnv("TRACKSys_MagBox", "/eos/ams/user/h/hchou/ExternalLibs/DB/magnetic/AMS02Mag.bin");
//TrackSys::Sys::SetEnv("TRACKSys_MatBox", "/eos/ams/user/h/hchou/ExternalLibs/DB/material");
TrackSys::Sys::SetEnv("TRACKSys_MagBox", "/afs/cern.ch/work/h/hchou/public/DATABASE/DB/magnetic/AMS02Mag.bin");
TrackSys::Sys::SetEnv("TRACKSys_MatBox", "/afs/cern.ch/work/h/hchou/public/DATABASE/DB/material");
YiNtuple::setSelectionMode(YiNtuple::NORM);
//YiNtuple::setSelectionMode(YiNtuple::COPY);
DataSelection::setOption(DataSelection::LIST, DataSelection::ON);
DataSelection::setOption(DataSelection::RTI, DataSelection::ON);
DataSelection::setOption(DataSelection::TRG, DataSelection::ON);
DataSelection::setOption(DataSelection::TOF, DataSelection::ON);
DataSelection::setOption(DataSelection::ACC, DataSelection::ON);
DataSelection::setOption(DataSelection::TRK, DataSelection::ON);
DataSelection::setOption(DataSelection::TRD, DataSelection::ON);
DataSelection::setOption(DataSelection::RICH, DataSelection::ON);
DataSelection::setOption(DataSelection::ECAL, DataSelection::ON);
EventBase::setEventVersion(EventBase::B950);
COUT("\n\n");
COUT("Usage : YiProdNtuple event_mode file_list group_id group_size (path)\n");
COUT(" Parameters : \n");
COUT(" event_mode [ISS BT MC]\n");
COUT(" file_list\n");
COUT(" group_id\n");
COUT(" group_size\n");
COUT(" (path)\n");
COUT("\n\n");
if (argc != 5 && argc != 6)
MGSys::ShowErrorAndExit(LOCADR(), "Number of argument is not conform! Exiting ...");
std::string event_mode = argv[1];
std::string file_list = argv[2];
Long64_t group_id = atol(argv[3]);
Long64_t group_size = atol(argv[4]);
std::use_facet<std::ctype<char> >(std::locale()).toupper(&event_mode[0], &event_mode[0] + event_mode.size());
if (event_mode == "ISS") EventBase::setEventMode(EventBase::ISS);
else if (event_mode == "BT") EventBase::setEventMode(EventBase::BT);
else if (event_mode == "MC") EventBase::setEventMode(EventBase::MC);
else MGSys::ShowErrorAndExit(LOCADR(), "Can't find event mode (ISS, BT, MC)! Exiting ...");
std::string outputFile = "";
if (YiNtuple::checkSelectionMode(YiNtuple::NORM))
outputFile = STR("YiNtuple_%s.%07ld.root", event_mode.c_str(), group_id);
else if (YiNtuple::checkSelectionMode(YiNtuple::COPY))
outputFile = STR("YiMirror_%s.%07ld.root", event_mode.c_str(), group_id);
std::string path = ".";
if (argc == 6) path = argv[5];
bool isMultiTree = false;
YiNtuple * ntuple = new YiNtuple();
ntuple->setOutputFile(outputFile, path, isMultiTree);
ntuple->readDataFrom(file_list, group_id, group_size);
ntuple->loopEventChain();
if (ntuple != nullptr) delete ntuple;
ntuple = nullptr;
COUT("\n**------------------------**\n");
COUT("\n** YiProdNtuple END **\n");
COUT("\n**------------------------**\n");
return 0;
}
#endif // __YiProdNtuple_C__
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <directshoweventloop.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qcoreevent.h>
QT_BEGIN_NAMESPACE
class DirectShowPostedEvent
{
public:
DirectShowPostedEvent(QObject *receiver, QEvent *event)
: receiver(receiver)
, event(event)
, next(0)
{
}
~DirectShowPostedEvent()
{
delete event;
}
QObject *receiver;
QEvent *event;
DirectShowPostedEvent *next;
};
DirectShowEventLoop::DirectShowEventLoop(QObject *parent)
: QWinEventNotifier(parent)
, m_postsHead(0)
, m_postsTail(0)
, m_eventHandle(::CreateEvent(0, 0, 0, 0))
, m_waitHandle(::CreateEvent(0, 0, 0, 0))
{
setHandle(m_eventHandle);
setEnabled(true);
}
DirectShowEventLoop::~DirectShowEventLoop()
{
setEnabled(false);
::CloseHandle(m_eventHandle);
::CloseHandle(m_waitHandle);
for (DirectShowPostedEvent *post = m_postsHead; post; post = m_postsHead) {
m_postsHead = m_postsHead->next;
delete post;
}
}
void DirectShowEventLoop::wait(QMutex *mutex)
{
::ResetEvent(m_waitHandle);
mutex->unlock();
HANDLE handles[] = { m_eventHandle, m_waitHandle };
while (::WaitForMultipleObjects(2, handles, false, INFINITE) == WAIT_OBJECT_0)
processEvents();
mutex->lock();
}
void DirectShowEventLoop::wake()
{
::SetEvent(m_waitHandle);
}
void DirectShowEventLoop::postEvent(QObject *receiver, QEvent *event)
{
QMutexLocker locker(&m_mutex);
DirectShowPostedEvent *post = new DirectShowPostedEvent(receiver, event);
if (m_postsTail)
m_postsTail->next = post;
else
m_postsHead = post;
m_postsTail = post;
::SetEvent(m_eventHandle);
}
bool DirectShowEventLoop::event(QEvent *event)
{
if (event->type() == QEvent::WinEventAct) {
processEvents();
return true;
} else {
return QWinEventNotifier::event(event);
}
}
void DirectShowEventLoop::processEvents()
{
QMutexLocker locker(&m_mutex);
while(m_postsHead) {
::ResetEvent(m_eventHandle);
DirectShowPostedEvent *post = m_postsHead;
m_postsHead = m_postsHead->next;
locker.unlock();
QCoreApplication::sendEvent(post->receiver, post->event);
delete post;
locker.relock();
}
m_postsTail = 0;
}
QT_END_NAMESPACE
<commit_msg>Fix corruption of Direct Show event queue.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <directshoweventloop.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qcoreevent.h>
QT_BEGIN_NAMESPACE
class DirectShowPostedEvent
{
public:
DirectShowPostedEvent(QObject *receiver, QEvent *event)
: receiver(receiver)
, event(event)
, next(0)
{
}
~DirectShowPostedEvent()
{
delete event;
}
QObject *receiver;
QEvent *event;
DirectShowPostedEvent *next;
};
DirectShowEventLoop::DirectShowEventLoop(QObject *parent)
: QWinEventNotifier(parent)
, m_postsHead(0)
, m_postsTail(0)
, m_eventHandle(::CreateEvent(0, 0, 0, 0))
, m_waitHandle(::CreateEvent(0, 0, 0, 0))
{
setHandle(m_eventHandle);
setEnabled(true);
}
DirectShowEventLoop::~DirectShowEventLoop()
{
setEnabled(false);
::CloseHandle(m_eventHandle);
::CloseHandle(m_waitHandle);
for (DirectShowPostedEvent *post = m_postsHead; post; post = m_postsHead) {
m_postsHead = m_postsHead->next;
delete post;
}
}
void DirectShowEventLoop::wait(QMutex *mutex)
{
::ResetEvent(m_waitHandle);
mutex->unlock();
HANDLE handles[] = { m_eventHandle, m_waitHandle };
while (::WaitForMultipleObjects(2, handles, false, INFINITE) == WAIT_OBJECT_0)
processEvents();
mutex->lock();
}
void DirectShowEventLoop::wake()
{
::SetEvent(m_waitHandle);
}
void DirectShowEventLoop::postEvent(QObject *receiver, QEvent *event)
{
QMutexLocker locker(&m_mutex);
DirectShowPostedEvent *post = new DirectShowPostedEvent(receiver, event);
if (m_postsTail)
m_postsTail->next = post;
else
m_postsHead = post;
m_postsTail = post;
::SetEvent(m_eventHandle);
}
bool DirectShowEventLoop::event(QEvent *event)
{
if (event->type() == QEvent::WinEventAct) {
processEvents();
return true;
} else {
return QWinEventNotifier::event(event);
}
}
void DirectShowEventLoop::processEvents()
{
QMutexLocker locker(&m_mutex);
while(m_postsHead) {
::ResetEvent(m_eventHandle);
DirectShowPostedEvent *post = m_postsHead;
m_postsHead = m_postsHead->next;
if (!m_postsHead)
m_postsTail = 0;
locker.unlock();
QCoreApplication::sendEvent(post->receiver, post->event);
delete post;
locker.relock();
}
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#pragma once
#include "core/CompileConfig.h"
#if OUZEL_SUPPORTS_DIRECTSOUND
#include <thread>
#include <dsound.h>
#include "audio/AudioDevice.hpp"
namespace ouzel
{
namespace audio
{
class AudioDeviceDS: public AudioDevice
{
friend Audio;
public:
virtual ~AudioDeviceDS();
virtual bool update() override;
IDirectSound8* getDirectSound() const { return directSound; }
protected:
AudioDeviceDS();
virtual bool init(bool debugAudio) override;
void run();
IDirectSound8* directSound = nullptr;
IDirectSoundBuffer* primaryBuffer = nullptr;
IDirectSoundBuffer8* buffer = nullptr;
uint32_t nextBuffer = 0;
bool running = true;
std::vector<uint8_t> data;
#if OUZEL_MULTITHREADED
std::thread audioThread;
#endif
};
} // namespace audio
} // namespace ouzel
#endif
<commit_msg>Remove the declaration of update()<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#pragma once
#include "core/CompileConfig.h"
#if OUZEL_SUPPORTS_DIRECTSOUND
#include <thread>
#include <dsound.h>
#include "audio/AudioDevice.hpp"
namespace ouzel
{
namespace audio
{
class AudioDeviceDS: public AudioDevice
{
friend Audio;
public:
virtual ~AudioDeviceDS();
IDirectSound8* getDirectSound() const { return directSound; }
protected:
AudioDeviceDS();
virtual bool init(bool debugAudio) override;
void run();
IDirectSound8* directSound = nullptr;
IDirectSoundBuffer* primaryBuffer = nullptr;
IDirectSoundBuffer8* buffer = nullptr;
uint32_t nextBuffer = 0;
bool running = true;
std::vector<uint8_t> data;
#if OUZEL_MULTITHREADED
std::thread audioThread;
#endif
};
} // namespace audio
} // namespace ouzel
#endif
<|endoftext|>
|
<commit_before>/*
* (C) 2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_COMPRESSION)
#include <botan/compression.h>
#endif
namespace Botan_Tests {
#if defined(BOTAN_HAS_COMPRESSION)
namespace {
const char* text_str =
"'Twas brillig, and the slithy toves"
"Did gyre and gimble in the wabe:"
"All mimsy were the borogoves,"
"And the mome raths outgrabe."
"'Beware the Jabberwock, my son!"
"The jaws that bite, the claws that catch!"
"Beware the Jubjub bird, and shun"
"The frumious Bandersnatch!'"
"He took his vorpal sword in hand;"
"Long time the manxome foe he sought-"
"So rested he by the Tumtum tree"
"And stood awhile in thought."
"And, as in uffish thought he stood,"
"The Jabberwock, with eyes of flame,"
"Came whiffling through the tulgey wood,"
"And burbled as it came!"
"One, two! One, two! And through and through"
"The vorpal blade went snicker-snack!"
"He left it dead, and with its head"
"He went galumphing back."
"'And hast thou slain the Jabberwock?"
"Come to my arms, my beamish boy!"
"O frabjous day! Callooh! Callay!'"
"He chortled in his joy."
"'Twas brillig, and the slithy toves"
"Did gyre and gimble in the wabe:"
"All mimsy were the borogoves,"
"And the mome raths outgrabe.";
class Compression_Tests final : public Test
{
public:
std::vector<Test::Result> run() override
{
std::vector<Test::Result> results;
const size_t text_len = std::strlen(text_str);
for(std::string algo : { "zlib", "deflate", "gzip", "bz2", "lzma" })
{
try
{
Test::Result result(algo + " compression");
std::unique_ptr<Botan::Compression_Algorithm> c(Botan::make_compressor(algo));
std::unique_ptr<Botan::Decompression_Algorithm> d(Botan::make_decompressor(algo));
if(!c || !d)
{
result.note_missing(algo);
continue;
}
result.test_ne("Not the same name", c->name(), d->name());
const Botan::secure_vector<uint8_t> empty;
const Botan::secure_vector<uint8_t> all_zeros(text_len, 0);
const Botan::secure_vector<uint8_t> random_binary = Test::rng().random_vec(text_len);
const Botan::secure_vector<uint8_t> short_text = { 'f', 'o', 'o', '\n' };
const uint8_t* textb = reinterpret_cast<const uint8_t*>(text_str);
const Botan::secure_vector<uint8_t> text(textb, textb + text_len);
const size_t c1_e = run_compression(result, 1, *c, *d, empty);
const size_t c9_e = run_compression(result, 9, *c, *d, empty);
const size_t c1_z = run_compression(result, 1, *c, *d, all_zeros);
const size_t c9_z = run_compression(result, 9, *c, *d, all_zeros);
const size_t c1_r = run_compression(result, 1, *c, *d, random_binary);
const size_t c9_r = run_compression(result, 9, *c, *d, random_binary);
const size_t c1_t = run_compression(result, 1, *c, *d, text);
const size_t c9_t = run_compression(result, 9, *c, *d, text);
const size_t c1_s = run_compression(result, 1, *c, *d, short_text);
const size_t c9_s = run_compression(result, 9, *c, *d, short_text);
result.test_gte("Empty input L1 compresses to non-empty output", c1_e, 1);
result.test_gte("Empty input L9 compresses to non-empty output", c9_e, 1);
result.test_gte("Level 9 compresses empty at least as well as level 1", c1_e, c9_e);
result.test_gte("Level 9 compresses zeros at least as well as level 1", c1_z, c9_z);
result.test_gte("Level 9 compresses random at least as well as level 1", c1_r, c9_r);
result.test_gte("Level 9 compresses text at least as well as level 1", c1_t, c9_t);
result.test_gte("Level 9 compresses short text at least as well as level 1", c1_s, c9_s);
result.test_lt("Zeros compresses much better than text", c1_z / 8, c1_t);
result.test_lt("Text compresses much better than random", c1_t / 2, c1_r);
results.emplace_back(result);
}
catch(std::exception& e)
{
results.emplace_back(Test::Result::Failure("testing " + algo, e.what()));
}
}
return results;
}
private:
// Returns # of bytes of compressed message
size_t run_compression(Test::Result& result,
size_t level,
Botan::Compression_Algorithm& c,
Botan::Decompression_Algorithm& d,
const Botan::secure_vector<uint8_t>& msg)
{
Botan::secure_vector<uint8_t> compressed(2*msg.size());
for(bool with_flush : { true, false })
{
try
{
compressed = msg;
c.start(level);
c.update(compressed, 0, false);
if(with_flush)
{
Botan::secure_vector<uint8_t> flush_bits;
c.update(flush_bits, 0, true);
compressed += flush_bits;
}
Botan::secure_vector<uint8_t> final_bits;
c.finish(final_bits);
compressed += final_bits;
Botan::secure_vector<uint8_t> decompressed = compressed;
d.start();
d.update(decompressed);
Botan::secure_vector<uint8_t> final_outputs;
d.finish(final_outputs);
decompressed += final_outputs;
result.test_eq("compression round tripped", msg, decompressed);
}
catch(Botan::Exception& e)
{
result.test_failure(e.what());
}
}
return compressed.size();
}
};
BOTAN_REGISTER_TEST("compression", "compression", Compression_Tests);
class CompressionCreate_Tests final : public Test
{
public:
std::vector<Test::Result> run() override
{
std::vector<Test::Result> results;
for(std::string algo : { "zlib", "deflate", "gzip", "bz2", "lzma" })
{
try
{
Test::Result result(algo + " create compression");
std::unique_ptr<Botan::Compression_Algorithm> c1(Botan::Compression_Algorithm::create(algo));
std::unique_ptr<Botan::Decompression_Algorithm> d1(Botan::Decompression_Algorithm::create(algo));
if(!c1 || !d1)
{
result.note_missing(algo);
continue;
}
result.test_ne("Not the same name after create", c1->name(), d1->name());
std::unique_ptr<Botan::Compression_Algorithm> c2(Botan::Compression_Algorithm::create_or_throw(algo));
std::unique_ptr<Botan::Decompression_Algorithm> d2(Botan::Decompression_Algorithm::create_or_throw(algo));
if(!c2 || !d2)
{
result.note_missing(algo);
continue;
}
result.test_ne("Not the same name after create_or_throw", c2->name(), d2->name());
results.emplace_back(result);
}
catch(std::exception& e)
{
results.emplace_back(Test::Result::Failure("testing " + algo, e.what()));
}
}
{
Test::Result result("create invalid compression");
result.test_throws("lookup error",
"Unavailable Compression bogocompress",
[&]() { Botan::Compression_Algorithm::create_or_throw("bogocompress"); });
result.test_throws("lookup error",
"Unavailable Decompression bogocompress",
[&]() { Botan::Decompression_Algorithm::create_or_throw("bogocompress"); });
results.emplace_back(result);
}
return results;
}
};
BOTAN_REGISTER_TEST("compression", "create_compression", CompressionCreate_Tests);
}
#endif
}
<commit_msg>Time compression tests<commit_after>/*
* (C) 2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_COMPRESSION)
#include <botan/compression.h>
#endif
namespace Botan_Tests {
#if defined(BOTAN_HAS_COMPRESSION)
namespace {
const char* text_str =
"'Twas brillig, and the slithy toves"
"Did gyre and gimble in the wabe:"
"All mimsy were the borogoves,"
"And the mome raths outgrabe."
"'Beware the Jabberwock, my son!"
"The jaws that bite, the claws that catch!"
"Beware the Jubjub bird, and shun"
"The frumious Bandersnatch!'"
"He took his vorpal sword in hand;"
"Long time the manxome foe he sought-"
"So rested he by the Tumtum tree"
"And stood awhile in thought."
"And, as in uffish thought he stood,"
"The Jabberwock, with eyes of flame,"
"Came whiffling through the tulgey wood,"
"And burbled as it came!"
"One, two! One, two! And through and through"
"The vorpal blade went snicker-snack!"
"He left it dead, and with its head"
"He went galumphing back."
"'And hast thou slain the Jabberwock?"
"Come to my arms, my beamish boy!"
"O frabjous day! Callooh! Callay!'"
"He chortled in his joy."
"'Twas brillig, and the slithy toves"
"Did gyre and gimble in the wabe:"
"All mimsy were the borogoves,"
"And the mome raths outgrabe.";
class Compression_Tests final : public Test
{
public:
std::vector<Test::Result> run() override
{
std::vector<Test::Result> results;
const size_t text_len = std::strlen(text_str);
for(std::string algo : { "zlib", "deflate", "gzip", "bz2", "lzma" })
{
try
{
Test::Result result(algo + " compression");
result.start_timer();
std::unique_ptr<Botan::Compression_Algorithm> c(Botan::make_compressor(algo));
std::unique_ptr<Botan::Decompression_Algorithm> d(Botan::make_decompressor(algo));
if(!c || !d)
{
result.note_missing(algo);
continue;
}
result.test_ne("Not the same name", c->name(), d->name());
const Botan::secure_vector<uint8_t> empty;
const Botan::secure_vector<uint8_t> all_zeros(text_len, 0);
const Botan::secure_vector<uint8_t> random_binary = Test::rng().random_vec(text_len);
const Botan::secure_vector<uint8_t> short_text = { 'f', 'o', 'o', '\n' };
const uint8_t* textb = reinterpret_cast<const uint8_t*>(text_str);
const Botan::secure_vector<uint8_t> text(textb, textb + text_len);
const size_t c1_e = run_compression(result, 1, *c, *d, empty);
const size_t c9_e = run_compression(result, 9, *c, *d, empty);
const size_t c1_z = run_compression(result, 1, *c, *d, all_zeros);
const size_t c9_z = run_compression(result, 9, *c, *d, all_zeros);
const size_t c1_r = run_compression(result, 1, *c, *d, random_binary);
const size_t c9_r = run_compression(result, 9, *c, *d, random_binary);
const size_t c1_t = run_compression(result, 1, *c, *d, text);
const size_t c9_t = run_compression(result, 9, *c, *d, text);
const size_t c1_s = run_compression(result, 1, *c, *d, short_text);
const size_t c9_s = run_compression(result, 9, *c, *d, short_text);
result.test_gte("Empty input L1 compresses to non-empty output", c1_e, 1);
result.test_gte("Empty input L9 compresses to non-empty output", c9_e, 1);
result.test_gte("Level 9 compresses empty at least as well as level 1", c1_e, c9_e);
result.test_gte("Level 9 compresses zeros at least as well as level 1", c1_z, c9_z);
result.test_gte("Level 9 compresses random at least as well as level 1", c1_r, c9_r);
result.test_gte("Level 9 compresses text at least as well as level 1", c1_t, c9_t);
result.test_gte("Level 9 compresses short text at least as well as level 1", c1_s, c9_s);
result.test_lt("Zeros compresses much better than text", c1_z / 8, c1_t);
result.test_lt("Text compresses much better than random", c1_t / 2, c1_r);
result.end_timer();
results.emplace_back(result);
}
catch(std::exception& e)
{
results.emplace_back(Test::Result::Failure("testing " + algo, e.what()));
}
}
return results;
}
private:
// Returns # of bytes of compressed message
size_t run_compression(Test::Result& result,
size_t level,
Botan::Compression_Algorithm& c,
Botan::Decompression_Algorithm& d,
const Botan::secure_vector<uint8_t>& msg)
{
Botan::secure_vector<uint8_t> compressed(2*msg.size());
for(bool with_flush : { true, false })
{
try
{
compressed = msg;
c.start(level);
c.update(compressed, 0, false);
if(with_flush)
{
Botan::secure_vector<uint8_t> flush_bits;
c.update(flush_bits, 0, true);
compressed += flush_bits;
}
Botan::secure_vector<uint8_t> final_bits;
c.finish(final_bits);
compressed += final_bits;
Botan::secure_vector<uint8_t> decompressed = compressed;
d.start();
d.update(decompressed);
Botan::secure_vector<uint8_t> final_outputs;
d.finish(final_outputs);
decompressed += final_outputs;
result.test_eq("compression round tripped", msg, decompressed);
}
catch(Botan::Exception& e)
{
result.test_failure(e.what());
}
}
return compressed.size();
}
};
BOTAN_REGISTER_TEST("compression", "compression", Compression_Tests);
class CompressionCreate_Tests final : public Test
{
public:
std::vector<Test::Result> run() override
{
std::vector<Test::Result> results;
for(std::string algo : { "zlib", "deflate", "gzip", "bz2", "lzma" })
{
try
{
Test::Result result(algo + " create compression");
std::unique_ptr<Botan::Compression_Algorithm> c1(Botan::Compression_Algorithm::create(algo));
std::unique_ptr<Botan::Decompression_Algorithm> d1(Botan::Decompression_Algorithm::create(algo));
if(!c1 || !d1)
{
result.note_missing(algo);
continue;
}
result.test_ne("Not the same name after create", c1->name(), d1->name());
std::unique_ptr<Botan::Compression_Algorithm> c2(Botan::Compression_Algorithm::create_or_throw(algo));
std::unique_ptr<Botan::Decompression_Algorithm> d2(Botan::Decompression_Algorithm::create_or_throw(algo));
if(!c2 || !d2)
{
result.note_missing(algo);
continue;
}
result.test_ne("Not the same name after create_or_throw", c2->name(), d2->name());
results.emplace_back(result);
}
catch(std::exception& e)
{
results.emplace_back(Test::Result::Failure("testing " + algo, e.what()));
}
}
{
Test::Result result("create invalid compression");
result.test_throws("lookup error",
"Unavailable Compression bogocompress",
[&]() { Botan::Compression_Algorithm::create_or_throw("bogocompress"); });
result.test_throws("lookup error",
"Unavailable Decompression bogocompress",
[&]() { Botan::Decompression_Algorithm::create_or_throw("bogocompress"); });
results.emplace_back(result);
}
return results;
}
};
BOTAN_REGISTER_TEST("compression", "create_compression", CompressionCreate_Tests);
}
#endif
}
<|endoftext|>
|
<commit_before>/*
* header.cpp
*
* Created on: Aug 24, 2015
* Author: zmij
*/
#include <tip/http/common/header.hpp>
#include <boost/spirit/include/qi.hpp>
#include <tip/http/common/grammar/header_generate.hpp>
namespace tip {
namespace http {
std::ostream&
operator << (std::ostream& out, header const& val)
{
namespace karma = boost::spirit::karma;
typedef std::ostream_iterator<char> output_iterator;
typedef grammar::gen::header_grammar<output_iterator> header_grammar;
std::ostream::sentry s(out);
if (s) {
output_iterator oi(out);
karma::generate(oi, header_grammar(), val);
}
return out;
}
std::ostream&
operator << (std::ostream& out, headers const& val)
{
namespace karma = boost::spirit::karma;
typedef std::ostream_iterator<char> output_iterator;
typedef grammar::gen::headers_grammar<output_iterator> headers_grammar;
std::ostream::sentry s(out);
if (s) {
output_iterator oi(out);
karma::generate(oi, headers_grammar(), val);
}
return out;
}
size_t
content_length(headers const& hdrs)
{
namespace qi = boost::spirit::qi;
typedef std::string::const_iterator string_iterator;
auto p = hdrs.find(ContentLength);
if (p != hdrs.end()) {
string_iterator f = p->second.begin();
string_iterator l = p->second.end();
size_t res;
if (qi::parse(f, l, qi::int_parser<size_t, 10>(), res) && f == l)
return res;
else
throw std::runtime_error("Invalid Content-Length header");
}
return 0;
}
bool
chunked_transfer_encoding(headers const& hdrs)
{
typedef std::string::const_iterator string_iterator;
auto p = hdrs.find(TransferEncoding);
if (p != hdrs.end()) {
return p->second == "chunked";
}
return false;
}
} // namespace http
} // namespace tip
<commit_msg>Pedantic code cleanup<commit_after>/*
* header.cpp
*
* Created on: Aug 24, 2015
* Author: zmij
*/
#include <tip/http/common/header.hpp>
#include <boost/spirit/include/qi.hpp>
#include <tip/http/common/grammar/header_generate.hpp>
namespace tip {
namespace http {
std::ostream&
operator << (std::ostream& out, header const& val)
{
namespace karma = boost::spirit::karma;
typedef std::ostream_iterator<char> output_iterator;
typedef grammar::gen::header_grammar<output_iterator> header_grammar;
std::ostream::sentry s(out);
if (s) {
output_iterator oi(out);
karma::generate(oi, header_grammar(), val);
}
return out;
}
std::ostream&
operator << (std::ostream& out, headers const& val)
{
namespace karma = boost::spirit::karma;
typedef std::ostream_iterator<char> output_iterator;
typedef grammar::gen::headers_grammar<output_iterator> headers_grammar;
std::ostream::sentry s(out);
if (s) {
output_iterator oi(out);
karma::generate(oi, headers_grammar(), val);
}
return out;
}
size_t
content_length(headers const& hdrs)
{
namespace qi = boost::spirit::qi;
typedef std::string::const_iterator string_iterator;
auto p = hdrs.find(ContentLength);
if (p != hdrs.end()) {
string_iterator f = p->second.begin();
string_iterator l = p->second.end();
size_t res;
if (qi::parse(f, l, qi::int_parser<size_t, 10>(), res) && f == l)
return res;
else
throw std::runtime_error("Invalid Content-Length header");
}
return 0;
}
bool
chunked_transfer_encoding(headers const& hdrs)
{
auto p = hdrs.find(TransferEncoding);
if (p != hdrs.end()) {
return p->second == "chunked";
}
return false;
}
} // namespace http
} // namespace tip
<|endoftext|>
|
<commit_before>/*
*
* StellarLikeBlockchainExplorerAccountSynchronizer.cpp
* ledger-core
*
* Created by Pierre Pollastri on 10/07/2019.
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include "StellarLikeBlockchainExplorerAccountSynchronizer.hpp"
#include <common/AccountHelper.hpp>
#include <wallet/stellar/StellarLikeAccount.hpp>
/**
* Current version of the synchronization. Please keep this field up to date to ensure that we have proper migration
* mechanism if the synchronizer needs to save more data in its state in the future (or modify current value). This
* version allow smooth migration.
*/
static const auto SYNCHRONIZATION_ALGORITHM_VERSION = 1;
namespace ledger {
namespace core {
StellarLikeBlockchainExplorerAccountSynchronizer::StellarLikeBlockchainExplorerAccountSynchronizer(
const std::shared_ptr<WalletPool> &pool,
const std::shared_ptr<StellarLikeBlockchainExplorer> &explorer) :
DedicatedContext(pool->getDispatcher()->getSerialExecutionContext("stellar_like_account_synchronizer")),
_explorer(explorer),
_database(pool->getDatabaseSessionPool()) {
}
void StellarLikeBlockchainExplorerAccountSynchronizer::reset(const std::shared_ptr<StellarLikeAccount> &account,
const std::chrono::system_clock::time_point &toDate) {
account->getInternalPreferences()->getSubPreferences("StellarLikeBlockchainExplorerAccountSynchronizer")->editor()->clear();
}
std::shared_ptr<ProgressNotifier<BlockchainExplorerAccountSynchronizationResult>> StellarLikeBlockchainExplorerAccountSynchronizer::synchronize(
const std::shared_ptr<StellarLikeAccount> &account) {
if (_notifier != nullptr) {
return _notifier;
}
_notifier = std::make_shared<ProgressNotifier<BlockchainExplorerAccountSynchronizationResult>>();
synchronizeAccount(account);
return _notifier;
}
bool StellarLikeBlockchainExplorerAccountSynchronizer::isSynchronizing() const {
return _notifier != nullptr;
}
void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr<StellarLikeAccount> &account) {
auto self = shared_from_this();
auto preferences = account->getInternalPreferences()->getSubPreferences("StellarLikeBlockchainExplorerAccountSynchronizer");
auto state = preferences
->template getObject<StellarLikeBlockchainExplorerAccountSynchronizer::SavedState>("state")
// provide default state if none exists yet
.getValueOr(SavedState{});
synchronizeAccount(account, state);
}
void
StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr<StellarLikeAccount>& account,
StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {
auto address = account->getKeychain()->getAddress()->toString();
auto self = shared_from_this();
_explorer->getAccount(address)
.onComplete(account->getContext(), [self, account, state] (const Try<std::shared_ptr<stellar::Account>>& accountInfo) mutable {
if (accountInfo.isFailure() && accountInfo.getFailure().getErrorCode() == api::ErrorCode::ACCOUNT_NOT_FOUND) {
self->endSynchronization(account, state);
} else if (accountInfo.isFailure()) {
self->failSynchronization(accountInfo.getFailure());
} else {
soci::session sql(self->_database->getPool());
account->updateAccountInfo(sql, *accountInfo.getValue());
self->synchronizeTransactions(account, state);
}
});
}
void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeTransactions(
const std::shared_ptr<StellarLikeAccount> &account,
StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {
auto address = account->getKeychain()->getAddress()->toString();
auto self = shared_from_this();
fmt::print("Current paging token: {}\n", state.transactionPagingToken.getValueOr("no paging token"));
_explorer->getTransactions(address, state.transactionPagingToken)
.onComplete(account->getContext(), [self, account, state] (const Try<stellar::TransactionVector>& txs) mutable {
if (txs.isFailure()) {
self->failSynchronization(txs.getFailure());
} else {
{
soci::session sql(self->_database->getPool());
soci::transaction tr(sql);
for (const auto &tx : txs.getValue()) {
account->logger()->debug("XLM transaction hash: {}, paging_token: {}", tx->hash, tx->pagingToken);
auto const flag = account->putTransaction(sql, *tx);
if (::ledger::core::account::isInsertedOperation(flag)) {
++state.insertedOperations;
}
state.lastBlockHeight = std::max(state.lastBlockHeight, tx->ledger);
}
tr.commit();
}
if (!txs.getValue().empty()) {
state.transactionPagingToken = txs.getValue().back()->pagingToken;
fmt::print("Paging token for next round: {}\n", state.transactionPagingToken.getValueOr("no paging token"));
{
auto preferences = account->getInternalPreferences()->getSubPreferences("StellarLikeBlockchainExplorerAccountSynchronizer");
preferences->editor()->putObject("state", state)->commit();
}
self->synchronizeTransactions(account, state);
} else {
self->endSynchronization(account, state);
}
}
});
}
void StellarLikeBlockchainExplorerAccountSynchronizer::endSynchronization(
const std::shared_ptr<StellarLikeAccount>& account,
const StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {
BlockchainExplorerAccountSynchronizationResult result;
soci::session sql(account->getWallet()->getDatabase()->getPool());
result.lastBlockHeight = BlockDatabaseHelper::getLastBlock(sql,
account->getWallet()->getCurrency().name)
.template map<uint64_t>([] (const Block& block) {
return block.height;
}).getValueOr(0);
result.newOperations = state.insertedOperations;
_notifier->success(result);
_notifier = nullptr;
}
void StellarLikeBlockchainExplorerAccountSynchronizer::failSynchronization(const Exception &ex) {
_notifier->failure(ex);
_notifier = nullptr;
}
}
}
<commit_msg>Emit env at the end of batch insertion for XLM<commit_after>/*
*
* StellarLikeBlockchainExplorerAccountSynchronizer.cpp
* ledger-core
*
* Created by Pierre Pollastri on 10/07/2019.
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include "StellarLikeBlockchainExplorerAccountSynchronizer.hpp"
#include <common/AccountHelper.hpp>
#include <wallet/stellar/StellarLikeAccount.hpp>
/**
* Current version of the synchronization. Please keep this field up to date to ensure that we have proper migration
* mechanism if the synchronizer needs to save more data in its state in the future (or modify current value). This
* version allow smooth migration.
*/
static const auto SYNCHRONIZATION_ALGORITHM_VERSION = 1;
namespace ledger {
namespace core {
StellarLikeBlockchainExplorerAccountSynchronizer::StellarLikeBlockchainExplorerAccountSynchronizer(
const std::shared_ptr<WalletPool> &pool,
const std::shared_ptr<StellarLikeBlockchainExplorer> &explorer) :
DedicatedContext(pool->getDispatcher()->getSerialExecutionContext("stellar_like_account_synchronizer")),
_explorer(explorer),
_database(pool->getDatabaseSessionPool()) {
}
void StellarLikeBlockchainExplorerAccountSynchronizer::reset(const std::shared_ptr<StellarLikeAccount> &account,
const std::chrono::system_clock::time_point &toDate) {
account->getInternalPreferences()->getSubPreferences("StellarLikeBlockchainExplorerAccountSynchronizer")->editor()->clear();
}
std::shared_ptr<ProgressNotifier<BlockchainExplorerAccountSynchronizationResult>> StellarLikeBlockchainExplorerAccountSynchronizer::synchronize(
const std::shared_ptr<StellarLikeAccount> &account) {
if (_notifier != nullptr) {
return _notifier;
}
_notifier = std::make_shared<ProgressNotifier<BlockchainExplorerAccountSynchronizationResult>>();
synchronizeAccount(account);
return _notifier;
}
bool StellarLikeBlockchainExplorerAccountSynchronizer::isSynchronizing() const {
return _notifier != nullptr;
}
void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr<StellarLikeAccount> &account) {
auto self = shared_from_this();
auto preferences = account->getInternalPreferences()->getSubPreferences("StellarLikeBlockchainExplorerAccountSynchronizer");
auto state = preferences
->template getObject<StellarLikeBlockchainExplorerAccountSynchronizer::SavedState>("state")
// provide default state if none exists yet
.getValueOr(SavedState{});
synchronizeAccount(account, state);
}
void
StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr<StellarLikeAccount>& account,
StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {
auto address = account->getKeychain()->getAddress()->toString();
auto self = shared_from_this();
_explorer->getAccount(address)
.onComplete(account->getContext(), [self, account, state] (const Try<std::shared_ptr<stellar::Account>>& accountInfo) mutable {
if (accountInfo.isFailure() && accountInfo.getFailure().getErrorCode() == api::ErrorCode::ACCOUNT_NOT_FOUND) {
self->endSynchronization(account, state);
} else if (accountInfo.isFailure()) {
self->failSynchronization(accountInfo.getFailure());
} else {
soci::session sql(self->_database->getPool());
account->updateAccountInfo(sql, *accountInfo.getValue());
self->synchronizeTransactions(account, state);
}
});
}
void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeTransactions(
const std::shared_ptr<StellarLikeAccount> &account,
StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {
auto address = account->getKeychain()->getAddress()->toString();
auto self = shared_from_this();
fmt::print("Current paging token: {}\n", state.transactionPagingToken.getValueOr("no paging token"));
_explorer->getTransactions(address, state.transactionPagingToken)
.onComplete(account->getContext(), [self, account, state] (const Try<stellar::TransactionVector>& txs) mutable {
if (txs.isFailure()) {
self->failSynchronization(txs.getFailure());
} else {
{
for (const auto &tx : txs.getValue()) {
soci::session sql(self->_database->getPool());
soci::transaction tr(sql);
account->logger()->debug("XLM transaction hash: {}, paging_token: {}", tx->hash, tx->pagingToken);
auto const flag = account->putTransaction(sql, *tx);
if (::ledger::core::account::isInsertedOperation(flag)) {
++state.insertedOperations;
}
tr.commit();
state.lastBlockHeight = std::max(state.lastBlockHeight, tx->ledger);
}
}
account->emitEventsNow();
if (!txs.getValue().empty()) {
state.transactionPagingToken = txs.getValue().back()->pagingToken;
fmt::print("Paging token for next round: {}\n", state.transactionPagingToken.getValueOr("no paging token"));
{
auto preferences = account->getInternalPreferences()->getSubPreferences("StellarLikeBlockchainExplorerAccountSynchronizer");
preferences->editor()->putObject("state", state)->commit();
}
self->synchronizeTransactions(account, state);
} else {
self->endSynchronization(account, state);
}
}
});
}
void StellarLikeBlockchainExplorerAccountSynchronizer::endSynchronization(
const std::shared_ptr<StellarLikeAccount>& account,
const StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {
BlockchainExplorerAccountSynchronizationResult result;
soci::session sql(account->getWallet()->getDatabase()->getPool());
result.lastBlockHeight = BlockDatabaseHelper::getLastBlock(sql,
account->getWallet()->getCurrency().name)
.template map<uint64_t>([] (const Block& block) {
return block.height;
}).getValueOr(0);
result.newOperations = state.insertedOperations;
_notifier->success(result);
_notifier = nullptr;
}
void StellarLikeBlockchainExplorerAccountSynchronizer::failSynchronization(const Exception &ex) {
_notifier->failure(ex);
_notifier = nullptr;
}
}
}
<|endoftext|>
|
<commit_before>/*********************************************************************************
*
* Copyright (c) 2017 Josef Adamsson
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
*********************************************************************************/
#include <modules/crystalvisualization/processors/coordinatereader.h>
#include <modules/hdf5/datastructures/hdf5handle.h>
#include <modules/hdf5/datastructures/hdf5path.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo CoordinateReader::processorInfo_{
"envision.CoordinateReader", // Class identifier
"Coordinate Reader", // Display name
"Crystal", // Category
CodeState::Experimental, // Code state
Tags::None, // Tags
};
const ProcessorInfo CoordinateReader::getProcessorInfo() const {
return processorInfo_;
}
CoordinateReader::CoordinateReader()
: Processor()
, outport_("outport")
, inport_("inport")
// New property for animations
, timestep_("timestep", "Time step", false)
, path_("path", "Path", "", InvalidationLevel::InvalidOutput, PropertySemantics::Default) {
addPort(outport_);
addPort(inport_);
// New property for animations
addProperty(timestep_);
addProperty(path_);
}
void CoordinateReader::process() {
const auto h5path = hdf5::Path(path_.get());
const auto data = inport_.getData();
auto vecptr = std::make_shared<std::vector<vec3>>(data->getVectorOfVec3AtPath<float>(h5path));
outport_.setData(vecptr);
}
} // namespace
<commit_msg>Ny branch för coordreader<commit_after>/*********************************************************************************
*
* Copyright (c) 2017 Josef Adamsson
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
*********************************************************************************/
#include <modules/crystalvisualization/processors/coordinatereader.h>
#include <modules/hdf5/datastructures/hdf5handle.h>
#include <modules/hdf5/datastructures/hdf5path.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo CoordinateReader::processorInfo_{
"envision.CoordinateReader", // Class identifier
"Coordinate Reader", // Display name
"Crystal", // Category
CodeState::Experimental, // Code state
Tags::None, // Tags
};
const ProcessorInfo CoordinateReader::getProcessorInfo() const {
return processorInfo_;
}
CoordinateReader::CoordinateReader()
: Processor()
, outport_("outport")
, inport_("inport")
// New property for animations
, timestep_("timestep", "Time step", false)
, path_("path", "Path", "", InvalidationLevel::InvalidOutput, PropertySemantics::Default) {
addPort(outport_);
addPort(inport_);
// New property for animations
addProperty(timestep_);
addProperty(path_);
}
void CoordinateReader::process() {
const auto h5path = hdf5::Path(path_.get());
const auto data = inport_.getData();
/*
if ibrion = 0
timeh5 = h5path.split('/')
else
*/
auto vecptr = std::make_shared<std::vector<vec3>>(data->getVectorOfVec3AtPath<float>(h5path));
outport_.setData(vecptr);
}
} // namespace
<|endoftext|>
|
<commit_before>/*
* caosVM_flow.cpp
* openc2e
*
* Created by Alyssa Milburn on Sun May 30 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* 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 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.
*
*/
#include "caosVM.h"
#include <iostream>
#include "openc2e.h"
#include "World.h" // enum
#include <cmath> // sqrt
#include <sstream>
#include "AgentHelpers.h"
/**
DOIF (command) condition (condition)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
Part of a DOIF/ELIF/ELSE/ENDI block. Jumps to the next part of the block if condition is false,
otherwise continues executing the script.
*/
void caosVM::c_DOIF() {
// handled elsewhere
}
/**
ELIF (command) condition (condition)
%pragma variants all
%status maybe
%cost c1,c2 0
Part of a DOIF/ELIF/ELSE/ENDI block. If none of the previous DOIF/ELIF conditions have been true, and condition evaluates to true, then the code in the ELIF block is executed.
If found outside a DOIF block, it is equivalent to a DOIF. If you take advantage of this behavior, fuzzie is of the opinion that you should be shot.
*/
void caosVM::c_ELIF() {
// handled elsewhere
}
/**
ELSE (command)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
Part of a DOIF/ELIF/ELSE/ENDI block. If ELSE is present, it is jumped to when none of the previous DOIF/ELIF conditions are true.
*/
void caosVM::c_ELSE() {
// handled elsewhere
}
/**
ENDI (command)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
The end of a DOIF/ELIF/ELSE/ENDI block.
*/
void caosVM::c_ENDI() {
// TODO: cost in c2e?
}
/**
REPS (command) reps (integer)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
The start of a REPS...REPE loop. The body of the loop will be executed (reps) times.
*/
void caosVM::c_REPS() {
// Our expression parameter might push on a value that's a pointer
// (or otherwise not an integer); deal with it
VM_PARAM_INTEGER(n);
result.setInt(n+1); // we'll visit the DECJNZ first to handle 0 etc
}
/**
REPE (command)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
The end of a REPS...REPE loop.
*/
void caosVM::c_REPE() {
// handled elsewhere
}
/**
LOOP (command)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
The start of a LOOP...EVER or LOOP...UNTL loop.
*/
void caosVM::c_LOOP() {
// handled elsewhere
}
/**
EVER (command)
%status maybe
%pragma variants c1 c2 cv c3
Jumps back to the matching LOOP, no matter what.
*/
void caosVM::c_EVER() {
// handled elsewhere
}
/**
UNTL (command) condition (condition)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
Jumps back to the matching LOOP unless the condition evaluates to true.
*/
void caosVM::c_UNTL() {
// handled elsewhere
}
/**
GSUB (command) label (label)
%pragma retc -1
%status maybe
%pragma variants c1 c2 cv c3
Jumps to a subroutine defined by SUBR with label (label).
*/
void caosVM::c_GSUB() {
// handled elsewhere
}
/**
SUBR (command) label (label)
%status maybe
%pragma variants c1 c2 cv c3
Defines the start of a subroute to be called with GSUB, with label (label).
If the command is encountered during execution, it acts like a STOP.
*/
void caosVM::c_SUBR() {
// handled elsewhere
}
/**
RETN (command)
%pragma retc -1
%status maybe
%pragma variants c1 c2 cv c3
Returns from a subroutine called with GSUB.
*/
void caosVM::c_RETN() {
if (callStack.empty())
throw creaturesException("RETN with an empty callstack");
nip = callStack.back().nip;
callStack.back().valueStack.swap(valueStack);
callStack.back().valueStack.clear(); // just in case
callStack.pop_back();
}
/**
NEXT (command)
%status maybe
%pragma variants all
%cost c1,c2 0
The end of an ENUM...NEXT loop.
*/
void caosVM::c_NEXT() {
targ = owner;
}
/**
ENUM (command) family (integer) genus (integer) species (integer)
%status maybe
%pragma retc -1
%pragma variants c1 c2 cv c3
%cost c1,c2 0
Loops through all agents with the given classifier. 0 on any field is a
wildcard. The loop body is terminated by a NEXT.
*/
void caosVM::c_ENUM() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
for (std::list<boost::shared_ptr<Agent> >::iterator i
= world.agents.begin(); i != world.agents.end(); i++) {
boost::shared_ptr<Agent> a = (*i);
if (!a) continue;
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
caosVar v; v.setAgent(a);
valueStack.push_back(v);
}
}
/**
ESEE (command) family (integer) genus (integer) species (integer)
%status maybe
%pragma retc -1
%pragma variants c2 cv c3
Simular to ENUM, but iterates through agents visible to OWNR, or visible to TARG in an install script.
An agent can be seen if it is within the range set by RNGE, and is visible (this includes the PERM value
of walls that lie between them, and, if the agent is a Creature, it not having the 'invisible' attribute).
*/
void caosVM::c_ESEE() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
Agent *seeing;
if (owner) seeing = owner; else seeing = targ;
valid_agent(seeing);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
std::vector<boost::shared_ptr<Agent> > agents = getVisibleList(seeing, family, genus, species);
for (std::vector<boost::shared_ptr<Agent> >::iterator i = agents.begin(); i != agents.end(); i++) {
caosVar v; v.setAgent(*i);
valueStack.push_back(v);
}
}
bool agentsTouching(Agent *first, Agent *second); // caosVM_agent.cpp
/**
ETCH (command) family (integer) genus (integer) species (integer)
%pragma retc -1
%status maybe
%pragma variants c2 cv c3
Similar to ENUM, but iterates through the agents OWNR is touching, or TARG is touching in an install script.
*/
void caosVM::c_ETCH() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
Agent *touching;
if (owner) touching = owner; else touching = targ;
valid_agent(touching);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
for (std::list<boost::shared_ptr<Agent> >::iterator i
= world.agents.begin(); i != world.agents.end(); i++) {
boost::shared_ptr<Agent> a = (*i);
if (!a) continue;
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
if (a.get() == touching) continue;
if (agentsTouching(a.get(), touching)) {
caosVar v; v.setAgent(a);
valueStack.push_back(v);
}
}
}
/**
EPAS (command) family (integer) genus (integer) species (integer)
%pragma retc -1
%status stub
Similar to ENUM, but iterates through the OWNR vehicle's passengers.
*/
void caosVM::c_EPAS() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
// TODO: should probably implement this (ESEE)
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
}
/**
ECON (command) agent (agent)
%pragma retc -1
%status stub
Loops through all the agents in the connective system containing the given agent.
*/
void caosVM::c_ECON() {
VM_VERIFY_SIZE(3)
VM_PARAM_VALIDAGENT(agent)
// TODO: should probably implement this (ESEE)
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
}
/**
CALL (command) script_no (integer) p1 (any) p2 (any)
%status maybe
%pragma variants c2 cv c3
Calls script_no on OWNR, then waits for it to return. The invoked script
will inherit the caller's INST setting, but any changes it makes to it will
be reversed once it returns - so eg if you call a script when in INST mode,
it calls OVER and returns, you'll still be in INST.
Script variables (VAxx) will not be preserved - you'll have to use OVxx
for any parameters.
*/
void caosVM::c_CALL() {
VM_PARAM_VALUE(p2)
VM_PARAM_VALUE(p1)
VM_PARAM_INTEGER(script_no)
valid_agent(owner);
caos_assert(script_no >= 0 && script_no < 65536);
shared_ptr<script> s = owner->findScript(script_no);
if (!s) return;
caosVM *newvm = world.getVM(owner);
newvm->trace = trace;
ensure(newvm->fireScript(s, false));
newvm->inst = inst;
newvm->_p_[0] = p1;
newvm->_p_[1] = p2;
owner->pushVM(newvm);
stop_loop = true;
}
/**
CAOS (string) inline (integer) state_trans (integer) p1 (anything) p2 (anything) commands (string) throws (integer) catches (integer) report (variable)
%status maybe
Runs commands as caos code immediately. If inline, copy _IT_ VAxx TARG OWNR, etc. If state_trans, copy FROM and
OWNR. If an error occurs, it catches it and stuffs it in the report. (XXX: non-conforming)
*/
// XXX: exception catching is very broken right now
void caosVM::v_CAOS() {
// XXX: capture output
VM_PARAM_VARIABLE(report)
VM_PARAM_INTEGER(catches)
VM_PARAM_INTEGER(throws)
VM_PARAM_STRING(commands)
VM_PARAM_VALUE(p2)
VM_PARAM_VALUE(p1)
VM_PARAM_INTEGER(state_trans)
VM_PARAM_INTEGER(inl)
caosVM *sub = world.getVM(NULL);
sub->resetCore();
if (inl) {
for (int i = 0; i < 100; i++)
sub->var[i] = var[i];
sub->targ = targ;
sub->_it_ = _it_;
sub->part = part;
sub->owner = owner;
// sub->from = from;
}
if (state_trans) {
sub->owner = owner;
// sub->from = from;
}
sub->_p_[0] = p1;
sub->_p_[1] = p2;
try {
std::istringstream iss(commands);
std::ostringstream oss;
caosScript s("c3", "CAOS command"); // XXX: variant
s.parse(iss);
s.installScripts();
sub->outputstream = &oss;
sub->runEntirely(s.installer);
sub->outputstream = &std::cout;
result.setString(oss.str());
} catch (std::exception &e) {
sub->outputstream = &std::cout;
if (!throws || catches) {
report->setString(e.what());
result.setString("###");
} else {
world.freeVM(sub);
throw;
}
}
world.freeVM(sub);
}
/* vim: set noet: */
<commit_msg>implement EPAS<commit_after>/*
* caosVM_flow.cpp
* openc2e
*
* Created by Alyssa Milburn on Sun May 30 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* 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 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.
*
*/
#include "caosVM.h"
#include <iostream>
#include "openc2e.h"
#include "World.h" // enum
#include <cmath> // sqrt
#include <sstream>
#include "AgentHelpers.h"
#include "Vehicle.h" // EPAS
/**
DOIF (command) condition (condition)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
Part of a DOIF/ELIF/ELSE/ENDI block. Jumps to the next part of the block if condition is false,
otherwise continues executing the script.
*/
void caosVM::c_DOIF() {
// handled elsewhere
}
/**
ELIF (command) condition (condition)
%pragma variants all
%status maybe
%cost c1,c2 0
Part of a DOIF/ELIF/ELSE/ENDI block. If none of the previous DOIF/ELIF conditions have been true, and condition evaluates to true, then the code in the ELIF block is executed.
If found outside a DOIF block, it is equivalent to a DOIF. If you take advantage of this behavior, fuzzie is of the opinion that you should be shot.
*/
void caosVM::c_ELIF() {
// handled elsewhere
}
/**
ELSE (command)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
Part of a DOIF/ELIF/ELSE/ENDI block. If ELSE is present, it is jumped to when none of the previous DOIF/ELIF conditions are true.
*/
void caosVM::c_ELSE() {
// handled elsewhere
}
/**
ENDI (command)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
The end of a DOIF/ELIF/ELSE/ENDI block.
*/
void caosVM::c_ENDI() {
// TODO: cost in c2e?
}
/**
REPS (command) reps (integer)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
The start of a REPS...REPE loop. The body of the loop will be executed (reps) times.
*/
void caosVM::c_REPS() {
// Our expression parameter might push on a value that's a pointer
// (or otherwise not an integer); deal with it
VM_PARAM_INTEGER(n);
result.setInt(n+1); // we'll visit the DECJNZ first to handle 0 etc
}
/**
REPE (command)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
The end of a REPS...REPE loop.
*/
void caosVM::c_REPE() {
// handled elsewhere
}
/**
LOOP (command)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
The start of a LOOP...EVER or LOOP...UNTL loop.
*/
void caosVM::c_LOOP() {
// handled elsewhere
}
/**
EVER (command)
%status maybe
%pragma variants c1 c2 cv c3
Jumps back to the matching LOOP, no matter what.
*/
void caosVM::c_EVER() {
// handled elsewhere
}
/**
UNTL (command) condition (condition)
%status maybe
%pragma variants c1 c2 cv c3
%cost c1,c2 0
Jumps back to the matching LOOP unless the condition evaluates to true.
*/
void caosVM::c_UNTL() {
// handled elsewhere
}
/**
GSUB (command) label (label)
%pragma retc -1
%status maybe
%pragma variants c1 c2 cv c3
Jumps to a subroutine defined by SUBR with label (label).
*/
void caosVM::c_GSUB() {
// handled elsewhere
}
/**
SUBR (command) label (label)
%status maybe
%pragma variants c1 c2 cv c3
Defines the start of a subroute to be called with GSUB, with label (label).
If the command is encountered during execution, it acts like a STOP.
*/
void caosVM::c_SUBR() {
// handled elsewhere
}
/**
RETN (command)
%pragma retc -1
%status maybe
%pragma variants c1 c2 cv c3
Returns from a subroutine called with GSUB.
*/
void caosVM::c_RETN() {
if (callStack.empty())
throw creaturesException("RETN with an empty callstack");
nip = callStack.back().nip;
callStack.back().valueStack.swap(valueStack);
callStack.back().valueStack.clear(); // just in case
callStack.pop_back();
}
/**
NEXT (command)
%status maybe
%pragma variants all
%cost c1,c2 0
The end of an ENUM...NEXT loop.
*/
void caosVM::c_NEXT() {
targ = owner;
}
/**
ENUM (command) family (integer) genus (integer) species (integer)
%status maybe
%pragma retc -1
%pragma variants c1 c2 cv c3
%cost c1,c2 0
Loops through all agents with the given classifier. 0 on any field is a
wildcard. The loop body is terminated by a NEXT.
*/
void caosVM::c_ENUM() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
for (std::list<boost::shared_ptr<Agent> >::iterator i
= world.agents.begin(); i != world.agents.end(); i++) {
boost::shared_ptr<Agent> a = (*i);
if (!a) continue;
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
caosVar v; v.setAgent(a);
valueStack.push_back(v);
}
}
/**
ESEE (command) family (integer) genus (integer) species (integer)
%status maybe
%pragma retc -1
%pragma variants c2 cv c3
Simular to ENUM, but iterates through agents visible to OWNR, or visible to TARG in an install script.
An agent can be seen if it is within the range set by RNGE, and is visible (this includes the PERM value
of walls that lie between them, and, if the agent is a Creature, it not having the 'invisible' attribute).
*/
void caosVM::c_ESEE() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
Agent *seeing;
if (owner) seeing = owner; else seeing = targ;
valid_agent(seeing);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
std::vector<boost::shared_ptr<Agent> > agents = getVisibleList(seeing, family, genus, species);
for (std::vector<boost::shared_ptr<Agent> >::iterator i = agents.begin(); i != agents.end(); i++) {
caosVar v; v.setAgent(*i);
valueStack.push_back(v);
}
}
bool agentsTouching(Agent *first, Agent *second); // caosVM_agent.cpp
/**
ETCH (command) family (integer) genus (integer) species (integer)
%pragma retc -1
%status maybe
%pragma variants c2 cv c3
Similar to ENUM, but iterates through the agents OWNR is touching, or TARG is touching in an install script.
*/
void caosVM::c_ETCH() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
Agent *touching;
if (owner) touching = owner; else touching = targ;
valid_agent(touching);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
for (std::list<boost::shared_ptr<Agent> >::iterator i
= world.agents.begin(); i != world.agents.end(); i++) {
boost::shared_ptr<Agent> a = (*i);
if (!a) continue;
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
if (a.get() == touching) continue;
if (agentsTouching(a.get(), touching)) {
caosVar v; v.setAgent(a);
valueStack.push_back(v);
}
}
}
/**
EPAS (command) family (integer) genus (integer) species (integer)
%pragma retc -1
%status maybe
Similar to ENUM, but iterates through the OWNR vehicle's passengers.
*/
void caosVM::c_EPAS() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
caos_assert(owner);
Vehicle *v = dynamic_cast<Vehicle *>(owner.get());
caos_assert(v);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
for (std::vector<AgentRef>::iterator i = v->passengers.begin(); i != v->passengers.end(); i++) {
AgentRef a = *i;
if (!a) continue; // TODO: hrr
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
caosVar v; v.setAgent(a); valueStack.push_back(v);
}
}
/**
ECON (command) agent (agent)
%pragma retc -1
%status stub
Loops through all the agents in the connective system containing the given agent.
*/
void caosVM::c_ECON() {
VM_VERIFY_SIZE(3)
VM_PARAM_VALIDAGENT(agent)
// TODO: should probably implement this (ECON)
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
}
/**
CALL (command) script_no (integer) p1 (any) p2 (any)
%status maybe
%pragma variants c2 cv c3
Calls script_no on OWNR, then waits for it to return. The invoked script
will inherit the caller's INST setting, but any changes it makes to it will
be reversed once it returns - so eg if you call a script when in INST mode,
it calls OVER and returns, you'll still be in INST.
Script variables (VAxx) will not be preserved - you'll have to use OVxx
for any parameters.
*/
void caosVM::c_CALL() {
VM_PARAM_VALUE(p2)
VM_PARAM_VALUE(p1)
VM_PARAM_INTEGER(script_no)
valid_agent(owner);
caos_assert(script_no >= 0 && script_no < 65536);
shared_ptr<script> s = owner->findScript(script_no);
if (!s) return;
caosVM *newvm = world.getVM(owner);
newvm->trace = trace;
ensure(newvm->fireScript(s, false));
newvm->inst = inst;
newvm->_p_[0] = p1;
newvm->_p_[1] = p2;
owner->pushVM(newvm);
stop_loop = true;
}
/**
CAOS (string) inline (integer) state_trans (integer) p1 (anything) p2 (anything) commands (string) throws (integer) catches (integer) report (variable)
%status maybe
Runs commands as caos code immediately. If inline, copy _IT_ VAxx TARG OWNR, etc. If state_trans, copy FROM and
OWNR. If an error occurs, it catches it and stuffs it in the report. (XXX: non-conforming)
*/
// XXX: exception catching is very broken right now
void caosVM::v_CAOS() {
// XXX: capture output
VM_PARAM_VARIABLE(report)
VM_PARAM_INTEGER(catches)
VM_PARAM_INTEGER(throws)
VM_PARAM_STRING(commands)
VM_PARAM_VALUE(p2)
VM_PARAM_VALUE(p1)
VM_PARAM_INTEGER(state_trans)
VM_PARAM_INTEGER(inl)
caosVM *sub = world.getVM(NULL);
sub->resetCore();
if (inl) {
for (int i = 0; i < 100; i++)
sub->var[i] = var[i];
sub->targ = targ;
sub->_it_ = _it_;
sub->part = part;
sub->owner = owner;
// sub->from = from;
}
if (state_trans) {
sub->owner = owner;
// sub->from = from;
}
sub->_p_[0] = p1;
sub->_p_[1] = p2;
try {
std::istringstream iss(commands);
std::ostringstream oss;
caosScript s("c3", "CAOS command"); // XXX: variant
s.parse(iss);
s.installScripts();
sub->outputstream = &oss;
sub->runEntirely(s.installer);
sub->outputstream = &std::cout;
result.setString(oss.str());
} catch (std::exception &e) {
sub->outputstream = &std::cout;
if (!throws || catches) {
report->setString(e.what());
result.setString("###");
} else {
world.freeVM(sub);
throw;
}
}
world.freeVM(sub);
}
/* vim: set noet: */
<|endoftext|>
|
<commit_before>#pragma once
#include <vector>
#include <cmath>
#include <utility>
#include <algorithm>
#include "command.hpp"
#include "tank.hpp"
#include "state.hpp"
class TankManager {
public:
void Act();
Tank getClosestEnemyTank(Tank tank);
double getDistance(Tank tank1, Tank tank2);
void aimAt(Tank shooter, Tank target);
double getShellTravelTime(Tank tank, Tank tank2);
double getAngle(double x , double y, double x1, double y1);
bool isFriendinLine(Tank shooter, Tank target);
std::pair<double,double> getVector(Tank tank);
std::pair<double, double> getVector(double x, double y, double x1, double y2);
private:
};
void TankManager::Act() {
State &state = State::Instance();
// If we don't have any tanks yet don't act
if(state.getPlayerTanks().empty() || state.getEnemyTanks().empty()) {
std::cout << "we're all out of tanks" << std::endl;
std::cout << "player tanks: " << state.getPlayerTanks().size() << std::endl;
std::cout << "enemy tanks: " << state.getEnemyTanks().size() << std::endl;
return;
}
for (auto tank : state.getPlayerTanks()) {
if(!tank.isAlive()) {
continue;
}
Tank target = getClosestEnemyTank(tank);
aimAt(tank, target);
// tank.Move(FWD, 1);
if ( isFriendinLine(tank,target)) {
}
else {
tank.Fire();
}
std::cout << "tank id: " << tank.getID() << std::endl;
}
}
Tank TankManager::getClosestEnemyTank(Tank shooter) {
State &state = State::Instance();
Tank target = state.getEnemyTanks()[0];
int i = 0;
for (const auto &tank : state.getEnemyTanks()) {
if (getDistance(shooter, target) > getDistance(shooter, tank)) {
std::cout << "i found a closer tank" << std::endl;
target = tank;
}
}
return target;
}
/*void TankManager::aimAt(Tank shooter, Tank target) {
double angle = atan2(target.gety() - shooter.gety(), target.getx() - shooter.getx());
double turn = angle - shooter.getturret();
if (turn > 0) {
shooter.RotateTurret(CCW, turn);
} else {
shooter.RotateTurret(CW, -1 * turn);
}
// shooter.Fire();
}*/
void TankManager::aimAt(Tank shooter, Tank target) {
double angle = atan2(target.gety() - shooter.gety(), target.getx() - shooter.getx());
if(angle < 0) {
angle = angle + (2 * M_PI);
}
double current = shooter.getturret();
double amount = angle - current;
if(amount > 0) {
shooter.RotateTurret(CCW, amount / 2);
shooter.Rotate(CCW, amount / 2);
} else {
shooter.RotateTurret(CW, -amount / 2);
shooter.Rotate(CW, -amount / 2);
}
}
double TankManager::getDistance(Tank tank1, Tank tank2) {
return std::pow(tank1.getx() - tank2.getx(), 2) + std::pow(tank1.gety() - tank2.gety(), 2);
}
double TankManager::getShellTravelTime(Tank tank, Tank tank2) {
double dist = getDistance(tank, tank2);
return dist / 30;
}
std::pair<double,double> TankManager::getVector(Tank tank) {
std::pair<double,double> vec;
vec.first = cos(tank.getturret());
vec.second = sin(tank.getturret());
return vec;
}
std::pair<double, double> TankManager::getVector(double x, double y, double x1, double y1) {
std::pair<double, double> vec;
vec.first = x - x1;
vec.second = y - y1;
return vec;
}
double TankManager::getAngle(double x , double y, double x1, double y1) {
double angle = atan2(x- y, x1 - y1);
if(angle < 0) {
angle = angle + (2 * M_PI);
}
return angle;
}
bool TankManager::isFriendinLine(Tank shooter, Tank target) {
//auto firevec = getVector(tank);
for( auto friendly : State::Instance().getPlayerTanks() ) {
if( friendly.getID() == shooter.getID()) {
continue;
}
double x = friendly.getx();
double y = friendly.gety();
double x1, y1, x2, y2 , x3, y3, x4, y4;
x1 = x - 2; y1 = y - 2; x2 = x + 2; y2 = y + 2; x3 = x - 2; y3 = y + 2; x4 = x + 2; y4 =y - 2;
double angle1, angle2, angle3, angle4, angle2target;
angle2target = getAngle(shooter.getx(), shooter.gety(), target.getx(), target.gety());
angle1 = getAngle(shooter.getx(), shooter.gety(), x1, y1);
angle2 = getAngle(shooter.getx(), shooter.gety(), x2, y2);
angle3 = getAngle(shooter.getx(), shooter.gety(), x3, y3);
angle4 = getAngle(shooter.getx(), shooter.gety(), x4, y4);
auto result = std::minmax({angle1,angle2,angle3,angle4});
auto max = result.second;
auto min = result.first;
if( angle2target < max && angle2target > min ) {
return true;
}
}
return false;
}
<commit_msg>Tanks go ham now.<commit_after>#pragma once
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <utility>
#include <vector>
#include "command.hpp"
#include "tank.hpp"
#include "state.hpp"
class TankManager {
public:
void Act();
Tank getClosestEnemyTank(Tank tank);
double getDistance(Tank tank1, Tank tank2);
void aimAt(Tank shooter, Tank target);
double getShellTravelTime(Tank tank, Tank tank2);
double getAngle(double x , double y, double x1, double y1);
bool isFriendinLine(Tank shooter, Tank target);
std::pair<double,double> getVector(Tank tank);
std::pair<double, double> getVector(double x, double y, double x1, double y2);
};
void TankManager::Act() {
State &state = State::Instance();
// If we don't have any tanks yet don't act
if(state.getPlayerTanks().empty() || state.getEnemyTanks().empty()) {
std::cout << "we're all out of tanks" << std::endl;
std::cout << "player tanks: " << state.getPlayerTanks().size() << std::endl;
std::cout << "enemy tanks: " << state.getEnemyTanks().size() << std::endl;
return;
}
for (auto tank : state.getPlayerTanks()) {
if(!tank.isAlive()) {
continue;
}
Tank target = getClosestEnemyTank(tank);
// Aim!
aimAt(tank, target);
// Fire!
if (isFriendinLine(tank,target)) {
tank.StopFire();
}
else {
tank.Fire();
}
// Move!
srand(time(0));
if(rand() % 2) {
tank.Move(FWD, 10);
} else {
tank.Move(REV, 10);
}
}
}
Tank TankManager::getClosestEnemyTank(Tank shooter) {
State &state = State::Instance();
Tank target = state.getEnemyTanks()[0];
for (const auto &tank : state.getEnemyTanks()) {
if (getDistance(shooter, target) > getDistance(shooter, tank)) {
target = tank;
}
}
return target;
}
void TankManager::aimAt(Tank shooter, Tank target) {
double angle = atan2(target.gety() - shooter.gety(), target.getx() - shooter.getx());
if(angle < 0) {
angle = angle + (2 * M_PI);
}
double current = shooter.getturret();
double amount = angle - current;
if(amount > 0) {
shooter.RotateTurret(CCW, amount / 2);
shooter.Rotate(CCW, amount / 2);
} else {
shooter.RotateTurret(CW, -amount / 2);
shooter.Rotate(CW, -amount / 2);
}
}
double TankManager::getDistance(Tank tank1, Tank tank2) {
return std::pow(tank1.getx() - tank2.getx(), 2) + std::pow(tank1.gety() - tank2.gety(), 2);
}
double TankManager::getShellTravelTime(Tank tank, Tank tank2) {
double dist = getDistance(tank, tank2);
return dist / 30;
}
std::pair<double,double> TankManager::getVector(Tank tank) {
std::pair<double,double> vec;
vec.first = cos(tank.getturret());
vec.second = sin(tank.getturret());
return vec;
}
std::pair<double, double> TankManager::getVector(double x, double y, double x1, double y1) {
std::pair<double, double> vec;
vec.first = x - x1;
vec.second = y - y1;
return vec;
}
double TankManager::getAngle(double x , double y, double x1, double y1) {
double angle = atan2(x- y, x1 - y1);
if(angle < 0) {
angle = angle + (2 * M_PI);
}
return angle;
}
bool TankManager::isFriendinLine(Tank shooter, Tank target) {
//auto firevec = getVector(tank);
for( auto friendly : State::Instance().getPlayerTanks() ) {
if( friendly.getID() == shooter.getID()) {
continue;
}
double x = friendly.getx();
double y = friendly.gety();
double x1, y1, x2, y2 , x3, y3, x4, y4;
x1 = x - 2; y1 = y - 2; x2 = x + 2; y2 = y + 2; x3 = x - 2; y3 = y + 2; x4 = x + 2; y4 =y - 2;
double angle1, angle2, angle3, angle4, angle2target;
angle2target = getAngle(shooter.getx(), shooter.gety(), target.getx(), target.gety());
angle1 = getAngle(shooter.getx(), shooter.gety(), x1, y1);
angle2 = getAngle(shooter.getx(), shooter.gety(), x2, y2);
angle3 = getAngle(shooter.getx(), shooter.gety(), x3, y3);
angle4 = getAngle(shooter.getx(), shooter.gety(), x4, y4);
auto result = std::minmax({angle1,angle2,angle3,angle4});
auto max = result.second;
auto min = result.first;
if( angle2target < max && angle2target > min ) {
return true;
}
}
return false;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 Sacha Refshauge
*
*/
// Blackberry implementation of the framework.
#include <pwd.h>
#include <unistd.h>
#include <string>
#include "BlackberryMain.h"
// Simple implementations of System functions
void SystemToast(const char *text) {
dialog_instance_t dialog = 0;
dialog_create_toast(&dialog);
dialog_set_toast_message_text(dialog, text);
dialog_set_toast_position(dialog, DIALOG_POSITION_TOP_CENTER);
dialog_show(dialog);
}
void ShowAd(int x, int y, bool center_x) {
}
void ShowKeyboard() {
virtualkeyboard_show();
}
void Vibrate(int length_ms) {
vibration_request(VIBRATION_INTENSITY_LOW, 200 /* intensity (1-100), duration (ms) */);
}
void LaunchBrowser(const char *url)
{
char* error;
navigator_invoke(url, &error);
}
void LaunchMarket(const char *url)
{
char* error;
navigator_invoke(url, &error);
}
void LaunchEmail(const char *email_address)
{
char* error;
navigator_invoke((std::string("mailto:") + email_address).c_str(), &error);
}
InputState input_state;
// Input
const unsigned int buttonMappings[18] = {
KEYCODE_K, //Cross
KEYCODE_L, //Circle
KEYCODE_J, //Square
KEYCODE_I, //Triangle
KEYCODE_Q, //LBUMPER
KEYCODE_P, //RBUMPER
KEYCODE_SPACE, //START
KEYCODE_ZERO, //SELECT
KEYCODE_W, //UP
KEYCODE_S, //DOWN
KEYCODE_A, //LEFT
KEYCODE_D, //RIGHT
0, //MENU (SwipeDown)
KEYCODE_BACKSPACE, //BACK
KEYCODE_W, //JOY UP
KEYCODE_S, //JOY DOWN
KEYCODE_A, //JOY LEFT
KEYCODE_D, //JOY RIGHT
};
void SimulateGamepad(InputState *input) {
input->pad_lstick_x = 0;
input->pad_lstick_y = 0;
input->pad_rstick_x = 0;
input->pad_rstick_y = 0;
if (input->pad_buttons & PAD_BUTTON_JOY_UP)
input->pad_lstick_y=1;
else if (input->pad_buttons & PAD_BUTTON_JOY_DOWN)
input->pad_lstick_y=-1;
if (input->pad_buttons & PAD_BUTTON_JOY_LEFT)
input->pad_lstick_x=-1;
else if (input->pad_buttons & PAD_BUTTON_JOY_RIGHT)
input->pad_lstick_x=1;
}
void BlackberryMain::handleInput(screen_event_t screen_event)
{
int val, buttons, pointerId;
int pair[2];
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TYPE, &val);
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_SOURCE_POSITION, pair);
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TOUCH_ID, &pointerId);
input_state.mouse_valid = true;
switch(val)
{
// Touchscreen
case SCREEN_EVENT_MTOUCH_TOUCH:
case SCREEN_EVENT_MTOUCH_RELEASE: // Up, down
input_state.pointer_down[pointerId] = (val == SCREEN_EVENT_MTOUCH_TOUCH);
case SCREEN_EVENT_MTOUCH_MOVE:
input_state.pointer_x[pointerId] = pair[0] * dpi_scale;
input_state.pointer_y[pointerId] = pair[1] * dpi_scale;
break;
// Mouse, Simulator
case SCREEN_EVENT_POINTER:
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_BUTTONS,
&buttons);
if (buttons == SCREEN_LEFT_MOUSE_BUTTON) { // Down
input_state.pointer_x[pointerId] = pair[0] * dpi_scale;
input_state.pointer_y[pointerId] = pair[1] * dpi_scale;
input_state.pointer_down[pointerId] = true;
} else if (input_state.pointer_down[pointerId]) { // Up
input_state.pointer_x[pointerId] = pair[0] * dpi_scale;
input_state.pointer_y[pointerId] = pair[1] * dpi_scale;
input_state.pointer_down[pointerId] = false;
}
break;
// Keyboard
case SCREEN_EVENT_KEYBOARD:
int flags, value;
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_FLAGS, &flags);
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_SYM, &value);
for (int b = 0; b < 14; b++) {
if (value == buttonMappings[b] & 0xFF) {
if (flags & KEY_DOWN)
pad_buttons |= (1<<b);
else
pad_buttons &= ~(1<<b);
}
}
break;
// Gamepad
case SCREEN_EVENT_GAMEPAD:
case SCREEN_EVENT_JOYSTICK:
char device_id[16];
#define DIR_KEYS SCREEN_DPAD_UP_GAME_BUTTON | SCREEN_DPAD_DOWN_GAME_BUTTON | SCREEN_DPAD_LEFT_GAME_BUTTON | SCREEN_DPAD_RIGHT_GAME_BUTTON
screen_device_t device;
screen_get_event_property_pv(screen_event, SCREEN_PROPERTY_DEVICE, (void**)&device);
screen_get_device_property_cv(device, SCREEN_PROPERTY_ID_STRING, sizeof(device_id), device_id);
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_BUTTONS, &buttons);
// Map the buttons integer to our mappings
if (strstr(device_id, "057E-0306")) // Wiimote
controller_buttons = (buttons & (SCREEN_A_GAME_BUTTON | SCREEN_B_GAME_BUTTON)) << 2 |
(buttons & (SCREEN_X_GAME_BUTTON | SCREEN_Y_GAME_BUTTON)) >> 3;
else
controller_buttons = (buttons & (SCREEN_A_GAME_BUTTON | SCREEN_B_GAME_BUTTON)) |
(buttons & (SCREEN_X_GAME_BUTTON | SCREEN_Y_GAME_BUTTON)) >> 1;
controller_buttons |= (buttons & (SCREEN_MENU1_GAME_BUTTON | SCREEN_MENU2_GAME_BUTTON)) |
(buttons & SCREEN_L1_GAME_BUTTON) >> 6 | (buttons & SCREEN_R1_GAME_BUTTON) >> 8 |
(buttons & DIR_KEYS) >> 8 |
(buttons & DIR_KEYS) >> 2;
break;
case SCREEN_EVENT_DISPLAY:
screen_display_t new_dpy = NULL;
screen_get_event_property_pv(screen_event, SCREEN_PROPERTY_DISPLAY, (void **)&new_dpy);
static int hits = 0;
hits++;
for (int i = 0; i < ndisplays; i++) {
if (new_dpy != screen_dpy[i])
continue;
int active = 0;
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_ATTACHED, &active);
if (active) {
int size[2];
screen_get_display_property_iv(screen_dpy[i], SCREEN_PROPERTY_SIZE, size);
if (size[0] == 0 || size[1] == 0)
active = 0;
}
if (active && !displays[i].attached)
realiseDisplay(i);
else if (!active && displays[i].attached && displays[i].realised)
unrealiseDisplay(i);
displays[i].attached = active;
}
break;
}
}
void BlackberryMain::startMain(int argc, char *argv[]) {
// Receive events from window manager
screen_create_context(&screen_cxt, 0);
// Initialise Blackberry Platform Services
bps_initialize();
// TODO: Enable/disable based on setting
sensor_set_rate(SENSOR_TYPE_ACCELEROMETER, 25000);
sensor_request_events(SENSOR_TYPE_ACCELEROMETER);
net::Init();
startDisplays();
//eglMakeCurrent(egl_disp[0], egl_surf[0], egl_surf[0], egl_ctx[0]);
NativeInit(argc, (const char **)argv, "/accounts/1000/shared/misc/", "data/", "BADCOFFEE");
NativeInitGraphics();
screen_request_events(screen_cxt);
navigator_request_events(0);
dialog_request_events(0);
vibration_request_events(0);
audio = new BlackberryAudio();
runMain();
}
void BlackberryMain::runMain() {
bool running = true;
while (running) {
input_state.mouse_valid = false;
input_state.accelerometer_valid = false;
SimulateGamepad(&input_state);
while (true) {
// Handle Blackberry events
bps_event_t *event = NULL;
bps_get_event(&event, 0);
if (event == NULL)
break; // Ran out of events
int domain = bps_event_get_domain(event);
if (domain == screen_get_domain()) {
handleInput(screen_event_get_event(event));
} else if (domain == navigator_get_domain()) {
switch(bps_event_get_code(event))
{
case NAVIGATOR_BACK:
case NAVIGATOR_SWIPE_DOWN:
pad_buttons |= PAD_BUTTON_MENU;
break;
case NAVIGATOR_EXIT:
NativeShutdown();
exit(0);
break;
}
} else if (domain == sensor_get_domain()) {
if (SENSOR_ACCELEROMETER_READING == bps_event_get_code(event)) {
float x, y, z;
sensor_event_get_xyz(event, &x, &y, &z);
if (pixel_xres == 1024 || pixel_xres == 720) // Q10 has this negative and reversed
{
input_state.acc.x = -y;
input_state.acc.y = -x;
} else {
input_state.acc.x = x;
input_state.acc.y = y;
}
input_state.acc.z = z;
}
}
}
input_state.pad_buttons = pad_buttons | controller_buttons;
pad_buttons &= ~PAD_BUTTON_MENU;
UpdateInputState(&input_state);
NativeUpdate(input_state);
EndInputState(&input_state);
// Work in Progress
// Currently: Render to HDMI port (eg. 1080p) when in game. Render to device when in menu.
// Right now, hotswapping displays is not working. Temporarily disable.
// Idea: Render to all displays. Controls go to internal, game goes to external(s).
#if 0
if (globalUIState == UISTATE_INGAME && !emulating)
{
emulating = true;
switchDisplay(screen_emu);
} else if (globalUIState != UISTATE_INGAME && emulating) {
emulating = false;
switchDisplay(screen_ui);
}
#endif
NativeRender();
time_update();
// This handles VSync
if (false && emulating) // Temporarily disable
eglSwapBuffers(egl_disp[screen_emu], egl_surf[screen_emu]);
else
eglSwapBuffers(egl_disp[screen_ui], egl_surf[screen_ui]);
}
endMain();
}
void BlackberryMain::endMain() {
screen_stop_events(screen_cxt);
bps_shutdown();
NativeShutdownGraphics();
delete audio;
NativeShutdown();
killDisplays();
net::Shutdown();
screen_destroy_context(screen_cxt);
}
// Entry Point
int main(int argc, char *argv[]) {
BlackberryMain emu;
emu.startMain(argc, argv);
exit(0);
return 0;
}
<commit_msg>Initialise buttons so we don't get stuck keys.<commit_after>/*
* Copyright (c) 2013 Sacha Refshauge
*
*/
// Blackberry implementation of the framework.
#include <pwd.h>
#include <unistd.h>
#include <string>
#include "BlackberryMain.h"
// Simple implementations of System functions
void SystemToast(const char *text) {
dialog_instance_t dialog = 0;
dialog_create_toast(&dialog);
dialog_set_toast_message_text(dialog, text);
dialog_set_toast_position(dialog, DIALOG_POSITION_TOP_CENTER);
dialog_show(dialog);
}
void ShowAd(int x, int y, bool center_x) {
}
void ShowKeyboard() {
virtualkeyboard_show();
}
void Vibrate(int length_ms) {
vibration_request(VIBRATION_INTENSITY_LOW, 200 /* intensity (1-100), duration (ms) */);
}
void LaunchBrowser(const char *url)
{
char* error;
navigator_invoke(url, &error);
}
void LaunchMarket(const char *url)
{
char* error;
navigator_invoke(url, &error);
}
void LaunchEmail(const char *email_address)
{
char* error;
navigator_invoke((std::string("mailto:") + email_address).c_str(), &error);
}
InputState input_state;
// Input
const unsigned int buttonMappings[18] = {
KEYCODE_K, //Cross
KEYCODE_L, //Circle
KEYCODE_J, //Square
KEYCODE_I, //Triangle
KEYCODE_Q, //LBUMPER
KEYCODE_P, //RBUMPER
KEYCODE_SPACE, //START
KEYCODE_ZERO, //SELECT
KEYCODE_W, //UP
KEYCODE_S, //DOWN
KEYCODE_A, //LEFT
KEYCODE_D, //RIGHT
0, //MENU (SwipeDown)
KEYCODE_BACKSPACE, //BACK
KEYCODE_W, //JOY UP
KEYCODE_S, //JOY DOWN
KEYCODE_A, //JOY LEFT
KEYCODE_D, //JOY RIGHT
};
void SimulateGamepad(InputState *input) {
input->pad_lstick_x = 0;
input->pad_lstick_y = 0;
input->pad_rstick_x = 0;
input->pad_rstick_y = 0;
if (input->pad_buttons & PAD_BUTTON_JOY_UP)
input->pad_lstick_y=1;
else if (input->pad_buttons & PAD_BUTTON_JOY_DOWN)
input->pad_lstick_y=-1;
if (input->pad_buttons & PAD_BUTTON_JOY_LEFT)
input->pad_lstick_x=-1;
else if (input->pad_buttons & PAD_BUTTON_JOY_RIGHT)
input->pad_lstick_x=1;
}
void BlackberryMain::handleInput(screen_event_t screen_event)
{
int val, buttons, pointerId;
int pair[2];
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TYPE, &val);
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_SOURCE_POSITION, pair);
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TOUCH_ID, &pointerId);
input_state.mouse_valid = true;
switch(val)
{
// Touchscreen
case SCREEN_EVENT_MTOUCH_TOUCH:
case SCREEN_EVENT_MTOUCH_RELEASE: // Up, down
input_state.pointer_down[pointerId] = (val == SCREEN_EVENT_MTOUCH_TOUCH);
case SCREEN_EVENT_MTOUCH_MOVE:
input_state.pointer_x[pointerId] = pair[0] * dpi_scale;
input_state.pointer_y[pointerId] = pair[1] * dpi_scale;
break;
// Mouse, Simulator
case SCREEN_EVENT_POINTER:
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_BUTTONS,
&buttons);
if (buttons == SCREEN_LEFT_MOUSE_BUTTON) { // Down
input_state.pointer_x[pointerId] = pair[0] * dpi_scale;
input_state.pointer_y[pointerId] = pair[1] * dpi_scale;
input_state.pointer_down[pointerId] = true;
} else if (input_state.pointer_down[pointerId]) { // Up
input_state.pointer_x[pointerId] = pair[0] * dpi_scale;
input_state.pointer_y[pointerId] = pair[1] * dpi_scale;
input_state.pointer_down[pointerId] = false;
}
break;
// Keyboard
case SCREEN_EVENT_KEYBOARD:
int flags, value;
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_FLAGS, &flags);
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_SYM, &value);
for (int b = 0; b < 14; b++) {
if (value == buttonMappings[b] & 0xFF) {
if (flags & KEY_DOWN)
pad_buttons |= (1<<b);
else
pad_buttons &= ~(1<<b);
}
}
break;
// Gamepad
case SCREEN_EVENT_GAMEPAD:
case SCREEN_EVENT_JOYSTICK:
char device_id[16];
#define DIR_KEYS SCREEN_DPAD_UP_GAME_BUTTON | SCREEN_DPAD_DOWN_GAME_BUTTON | SCREEN_DPAD_LEFT_GAME_BUTTON | SCREEN_DPAD_RIGHT_GAME_BUTTON
screen_device_t device;
screen_get_event_property_pv(screen_event, SCREEN_PROPERTY_DEVICE, (void**)&device);
screen_get_device_property_cv(device, SCREEN_PROPERTY_ID_STRING, sizeof(device_id), device_id);
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_BUTTONS, &buttons);
// Map the buttons integer to our mappings
if (strstr(device_id, "057E-0306")) // Wiimote
controller_buttons = (buttons & (SCREEN_A_GAME_BUTTON | SCREEN_B_GAME_BUTTON)) << 2 |
(buttons & (SCREEN_X_GAME_BUTTON | SCREEN_Y_GAME_BUTTON)) >> 3;
else
controller_buttons = (buttons & (SCREEN_A_GAME_BUTTON | SCREEN_B_GAME_BUTTON)) |
(buttons & (SCREEN_X_GAME_BUTTON | SCREEN_Y_GAME_BUTTON)) >> 1;
controller_buttons |= (buttons & (SCREEN_MENU1_GAME_BUTTON | SCREEN_MENU2_GAME_BUTTON)) |
(buttons & SCREEN_L1_GAME_BUTTON) >> 6 | (buttons & SCREEN_R1_GAME_BUTTON) >> 8 |
(buttons & DIR_KEYS) >> 8 |
(buttons & DIR_KEYS) >> 2;
break;
case SCREEN_EVENT_DISPLAY:
screen_display_t new_dpy = NULL;
screen_get_event_property_pv(screen_event, SCREEN_PROPERTY_DISPLAY, (void **)&new_dpy);
static int hits = 0;
hits++;
for (int i = 0; i < ndisplays; i++) {
if (new_dpy != screen_dpy[i])
continue;
int active = 0;
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_ATTACHED, &active);
if (active) {
int size[2];
screen_get_display_property_iv(screen_dpy[i], SCREEN_PROPERTY_SIZE, size);
if (size[0] == 0 || size[1] == 0)
active = 0;
}
if (active && !displays[i].attached)
realiseDisplay(i);
else if (!active && displays[i].attached && displays[i].realised)
unrealiseDisplay(i);
displays[i].attached = active;
}
break;
}
}
void BlackberryMain::startMain(int argc, char *argv[]) {
// Receive events from window manager
screen_create_context(&screen_cxt, 0);
// Initialise Blackberry Platform Services
bps_initialize();
// TODO: Enable/disable based on setting
sensor_set_rate(SENSOR_TYPE_ACCELEROMETER, 25000);
sensor_request_events(SENSOR_TYPE_ACCELEROMETER);
pad_buttons = 0;
controller_buttons = 0;
net::Init();
startDisplays();
//eglMakeCurrent(egl_disp[0], egl_surf[0], egl_surf[0], egl_ctx[0]);
NativeInit(argc, (const char **)argv, "/accounts/1000/shared/misc/", "data/", "BADCOFFEE");
NativeInitGraphics();
screen_request_events(screen_cxt);
navigator_request_events(0);
dialog_request_events(0);
vibration_request_events(0);
audio = new BlackberryAudio();
runMain();
}
void BlackberryMain::runMain() {
bool running = true;
while (running) {
input_state.mouse_valid = false;
input_state.accelerometer_valid = false;
SimulateGamepad(&input_state);
while (true) {
// Handle Blackberry events
bps_event_t *event = NULL;
bps_get_event(&event, 0);
if (event == NULL)
break; // Ran out of events
int domain = bps_event_get_domain(event);
if (domain == screen_get_domain()) {
handleInput(screen_event_get_event(event));
} else if (domain == navigator_get_domain()) {
switch(bps_event_get_code(event))
{
case NAVIGATOR_BACK:
case NAVIGATOR_SWIPE_DOWN:
pad_buttons |= PAD_BUTTON_MENU;
break;
case NAVIGATOR_EXIT:
NativeShutdown();
exit(0);
break;
}
} else if (domain == sensor_get_domain()) {
if (SENSOR_ACCELEROMETER_READING == bps_event_get_code(event)) {
float x, y, z;
sensor_event_get_xyz(event, &x, &y, &z);
if (pixel_xres == 1024 || pixel_xres == 720) // Q10 has this negative and reversed
{
input_state.acc.x = -y;
input_state.acc.y = -x;
} else {
input_state.acc.x = x;
input_state.acc.y = y;
}
input_state.acc.z = z;
}
}
}
input_state.pad_buttons = pad_buttons | controller_buttons;
pad_buttons &= ~PAD_BUTTON_MENU;
UpdateInputState(&input_state);
NativeUpdate(input_state);
EndInputState(&input_state);
// Work in Progress
// Currently: Render to HDMI port (eg. 1080p) when in game. Render to device when in menu.
// Right now, hotswapping displays is not working. Temporarily disable.
// Idea: Render to all displays. Controls go to internal, game goes to external(s).
#if 0
if (globalUIState == UISTATE_INGAME && !emulating)
{
emulating = true;
switchDisplay(screen_emu);
} else if (globalUIState != UISTATE_INGAME && emulating) {
emulating = false;
switchDisplay(screen_ui);
}
#endif
NativeRender();
time_update();
// This handles VSync
if (false && emulating) // Temporarily disable
eglSwapBuffers(egl_disp[screen_emu], egl_surf[screen_emu]);
else
eglSwapBuffers(egl_disp[screen_ui], egl_surf[screen_ui]);
}
endMain();
}
void BlackberryMain::endMain() {
screen_stop_events(screen_cxt);
bps_shutdown();
NativeShutdownGraphics();
delete audio;
NativeShutdown();
killDisplays();
net::Shutdown();
screen_destroy_context(screen_cxt);
}
// Entry Point
int main(int argc, char *argv[]) {
BlackberryMain emu;
emu.startMain(argc, argv);
exit(0);
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
using std::begin; using std::end; using std::cout; using std::endl; using std::vector; using std::size_t;
bool compare(const int lhs[], size_t lsize, const int rhs[], size_t rsize)
{
if (lsize != rsize) return false;
for (int i = 0; i != lsize; ++i)
if (lhs[i] != rhs[i]) return false;
return true;
}
bool compare(vector<int> const& lhs, vector<int>& rhs)
{
return lhs == rhs;
}
int main()
{
int arr1[3] = { 0, 1, 2 };
int arr2[3] = { 0, 2, 4 };
auto result = compare(arr1, sizeof(arr1) / sizeof(arr2[0]), arr2, sizeof(arr2[0]));
cout << "The two arrays are " << (result ? "equal\n" : "unequal\n");
vector<int> vec1 = { 0, 1, 2 };
vector<int> vec2 = { 0, 1, 2 };
result = compare(vec1, vec2);
cout << "The two vectors are " << (result ? "equal\n" : "unequal\n");
return 0;
}
<commit_msg>Update ex3_36.cpp<commit_after>#include <iostream>
#include <vector>
using std::begin; using std::end; using std::cout; using std::endl; using std::vector; using std::size_t;
size_t array_size(const int arr[])
{
return sizeof(arr) / sizeof(arr[0]);
}
bool compare(const int lhs[], const int rhs[])
{
auto lsize = array_size(lhs);
auto rsize = array_size(rhs);
if (lsize != rsize) return false;
for (int i = 0; i != lsize; ++i)
if (lhs[i] != rhs[i]) return false;
return true;
}
bool compare(vector<int> const& lhs, vector<int>& rhs)
{
return lhs == rhs;
}
int main()
{
int arr1[3] = { 0, 1, 2 };
int arr2[3] = { 0, 1, 2 };
cout << "The two arrays are " << (compare(arr1, arr2) ? "equal\n" : "unequal\n");
vector<int> vec1 = { 0, 1, 2 };
vector<int> vec2 = { 0, 1, 3 };
cout << "The two vectors are " << (compare(vec1, vec2) ? "equal\n" : "unequal\n");
return 0;
}
<|endoftext|>
|
<commit_before>//
// ex9_34.cpp
// Exercise 9.34
//
// Created by pezy on 12/3/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// @Brief Assuming vi is a container of ints that includes even and odd
// values, predict the behavior of the following loop. After you've
// analyzed this loop, write a program to test whether your expectations
// were correct.
//
// iter = vi.begin();
// while (iter != vi.end())
// if (*iter % 2)
// iter = vi.insert(iter, *iter);
// ++iter;
//
// @Answer "infinite loop". Casue the `++iter` out of the `while` loop. But
// even through add brackets it is still infinite loop.
// Fixed following.
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
int main()
{
vector<int> vi = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto iter = vi.begin();
while (iter != vi.end())
{
if (*iter % 2)
{
iter = vi.insert(iter, *iter);
++iter;
}
++iter;
}
for (auto i : vi)
cout << i << " ";
cout << endl;
}
<commit_msg>Update ex9_34.cpp<commit_after>//
// ex9_34.cpp
// Exercise 9.34
//
// Created by pezy on 12/3/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// @Brief Assuming vi is a container of ints that includes even and odd
// values, predict the behavior of the following loop. After you've
// analyzed this loop, write a program to test whether your expectations
// were correct.
//
// iter = vi.begin();
// while (iter != vi.end())
// if (*iter % 2)
// iter = vi.insert(iter, *iter);
// ++iter;
//
// @Answer "infinite loop". Casue the `++iter` out of the `while` loop. But
// even through add brackets it is still infinite loop.
// Fixed following:
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
int main()
{
vector<int> vi = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto iter = vi.begin();
while (iter != vi.end())
{
if (*iter % 2)
{
iter = vi.insert(iter, *iter);
++iter;
}
++iter;
}
for (auto i : vi)
cout << i << " ";
cout << endl;
}
<|endoftext|>
|
<commit_before>//! @file Exercise 9.49
//! @author pezy
//! @date 2014-12-05
//! @Brief A letter has an ascender if, as with d or f, part of the letter
//! extends above the middle of the line.
// A letter has a descender if, as with p or g, part of the letter
// extends below the line.
// Write a program that reads a file containing words and reports the
// longest word that contains
// neither ascenders nor descenders.
#include <string>
#include <fstream>
#include <iostream>
using std::string;
using std::ifstream;
using std::cout;
using std::endl;
int main()
{
ifstream ifs("../data/letter.txt");
if (!ifs) return -1;
string longest_word;
for (string word; ifs >> word;)
if (word.find_first_not_of("aceimnorsuvwxz") == string::npos &&
word.size() > longest_word.size())
longest_word = word;
cout << longest_word << endl;
}
<commit_msg>Update ex9_49.cpp<commit_after>//! @file Exercise 9.49
//! @author pezy
//! @date 2014-12-05
//! @Brief A letter has an ascender if, as with d or f, part of the letter
// extends above the middle of the line.
// A letter has a descender if, as with p or g, part of the letter
// extends below the line.
// Write a program that reads a file containing words and reports the
// longest word that contains neither ascenders nor descenders.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream input("E:\\zzz.txt");
if(input)
{
string longest_word;
for(string word; input>>word; )
if((word.find_first_not_of("aceimnorsuvwxz"))==string::npos&&word.size()>longest_word.size())
longest_word=word;
cout<<longest_word<<endl;
}
}
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief I2C EEPROM ドライバー
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RL78/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include "common/iica_io.hpp"
#include "common/delay.hpp"
namespace chip {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief EEPROM テンプレートクラス
@param[in] I2C_IO i2c I/O クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class I2C_IO>
class EEPROM {
static const uint8_t EEPROM_ADR_ = 0x50;
I2C_IO& i2c_;
uint8_t ds_;
bool exp_;
bool ad_mix_;
uint8_t pagen_;
uint8_t i2c_adr_(uint32_t adr) const {
uint8_t a = EEPROM_ADR_ | ds_;
if(ad_mix_) {
if(adr >> 16) a |= 4;
}
return a;
}
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 256 バイトまでの EEPROM の ID (0 to 7) @n
アドレス指定が1バイトのデバイス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class M256B : uint8_t {
ID0, ///< A0=L(0), A1=L(0), A2=L(0)
ID1, ///< A0=H(1), A1=L(0), A2=L(0)
ID2, ///< A0=L(0), A1=H(1), A2=L(0)
ID3, ///< A0=H(1), A1=H(1), A2=L(0)
ID4, ///< A0=L(0), A1=L(0), A2=H(1)
ID5, ///< A0=H(1), A1=L(0), A2=H(1)
ID6, ///< A0=L(0), A1=H(1), A2=H(1)
ID7, ///< A0=H(1), A1=H(1), A2=H(1)
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 64K バイトまでの EEPROM の ID (0 to 7) @n
アドレス指定が2バイトのデバイス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class M64KB : uint8_t {
ID0, ///< A0=L(0), A1=L(0), A2=L(0)
ID1, ///< A0=H(1), A1=L(0), A2=L(0)
ID2, ///< A0=L(0), A1=H(1), A2=L(0)
ID3, ///< A0=H(1), A1=H(1), A2=L(0)
ID4, ///< A0=L(0), A1=L(0), A2=H(1)
ID5, ///< A0=H(1), A1=L(0), A2=H(1)
ID6, ///< A0=L(0), A1=H(1), A2=H(1)
ID7, ///< A0=H(1), A1=H(1), A2=H(1)
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 128K バイトの EEPROM の ID (0 to 3) @n
アドレス指定が2バイトのデバイス @n
A2 端子が、バンクセレクトに使われるデバイス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class M128KB : uint8_t {
ID0, ///< A0=L(0), A1=L(0)
ID1, ///< A0=H(1), A1=L(0)
ID2, ///< A0=L(0), A1=H(1)
ID3, ///< A0=H(1), A1=H(1)
};
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] i2c i2c_io クラスを参照で渡す
*/
//-----------------------------------------------------------------//
EEPROM(I2C_IO& i2c) : i2c_(i2c), ds_(0),
exp_(false), ad_mix_(false), pagen_(1) { }
//-----------------------------------------------------------------//
/*!
@brief アドレス指定1バイトの EEPROM を開始
@param[in] type デバイスのタイプとID
@param[in] pagen ページサイズ(書き込み一時バッファのサイズ)
*/
//-----------------------------------------------------------------//
void start(M256B type_id, uint8_t pagen) {
ds_ = static_cast<uint8_t>(type_id);
exp_ = false;
ad_mix_ = false;
pagen_ = pagen;
}
//-----------------------------------------------------------------//
/*!
@brief アドレス指定2バイトの EEPROM を開始
@param[in] type デバイスのタイプとID
@param[in] pagen ページサイズ(書き込み一時バッファのサイズ)
*/
//-----------------------------------------------------------------//
void start(M64KB type_id, uint8_t pagen) {
ds_ = static_cast<uint8_t>(type_id);
exp_ = true;
ad_mix_ = false;
pagen_ = pagen;
}
//-----------------------------------------------------------------//
/*!
@brief アドレス指定2バイトで、「A2」がバンクの EEPROM を開始
@param[in] type デバイスのタイプとID
@param[in] pagen ページサイズ(書き込み一時バッファのサイズ)
*/
//-----------------------------------------------------------------//
void start(M128KB type_id, uint8_t pagen) {
ds_ = static_cast<uint8_t>(type_id);
exp_ = true;
ad_mix_ = true;
pagen_ = pagen;
}
//-----------------------------------------------------------------//
/*!
@brief 書き込み状態の検査
@param[in] adr 検査アドレス
@return 「false」なら、書き込み中
*/
//-----------------------------------------------------------------//
bool get_write_state(uint32_t adr) const {
uint8_t tmp[1];
return read(adr, tmp, 1);
}
//-----------------------------------------------------------------//
/*!
@brief 書き込み同期
@param[in] adr 検査アドレス
@param[in] delay 待ち時間(10us単位)
@return デバイスエラーなら「false」
*/
//-----------------------------------------------------------------//
bool sync_write(uint32_t adr, uint16_t delay = 600) const {
bool ok = false;
for(uint16_t i = 0; i < delay; ++i) {
utils::delay::micro_second(10);
uint8_t tmp[1];
if(read(adr, tmp, 1)) {
ok = true;
break;
}
}
return ok;
}
//-----------------------------------------------------------------//
/*!
@brief EEPROM 読み出し
@param[in] adr 読み出しアドレス
@param[out] dst 先
@param[in] len 長さ
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool read(uint32_t adr, uint8_t* dst, uint16_t len) const {
uint8_t tmp[2];
if(exp_) {
tmp[0] = (adr >> 8) & 255;
tmp[1] = adr & 255;
if(!i2c_.send(i2c_adr_(adr), tmp, 2)) {
return false;
}
} else {
tmp[0] = adr & 255;
if(!i2c_.send(i2c_adr_(adr), tmp, 1)) {
return false;
}
}
if(!i2c_.recv(i2c_adr_(adr), dst, len)) {
return false;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief EEPROM 書き込み
@param[in] adr 書き込みアドレス
@param[out] src 元
@param[in] len 長さ
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool write(uint32_t adr, const uint8_t* src, uint16_t len) const {
while(len > 0) {
uint16_t l = pagen_ - (adr & (pagen_ - 1));
if(len < l) l = len;
if(exp_) {
if(!i2c_.send(i2c_adr_(adr), adr >> 8, adr & 255, src, l)) {
return false;
}
} else {
if(!i2c_.send(i2c_adr_(adr), adr & 255, src, l)) {
return false;
}
}
src += l;
len -= l;
if(len) { // 書き込み終了を待つポーリング
if(!sync_write(adr)) {
return false;
}
}
adr += l;
}
return true;
}
};
}
<commit_msg>cleanup include path<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief I2C EEPROM ドライバー
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RL78/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include "common/delay.hpp"
namespace chip {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief EEPROM テンプレートクラス
@param[in] I2C_IO i2c I/O クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class I2C_IO>
class EEPROM {
static const uint8_t EEPROM_ADR_ = 0x50;
I2C_IO& i2c_;
uint8_t ds_;
bool exp_;
bool ad_mix_;
uint8_t pagen_;
uint8_t i2c_adr_(uint32_t adr) const {
uint8_t a = EEPROM_ADR_ | ds_;
if(ad_mix_) {
if(adr >> 16) a |= 4;
}
return a;
}
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 256 バイトまでの EEPROM の ID (0 to 7) @n
アドレス指定が1バイトのデバイス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class M256B : uint8_t {
ID0, ///< A0=L(0), A1=L(0), A2=L(0)
ID1, ///< A0=H(1), A1=L(0), A2=L(0)
ID2, ///< A0=L(0), A1=H(1), A2=L(0)
ID3, ///< A0=H(1), A1=H(1), A2=L(0)
ID4, ///< A0=L(0), A1=L(0), A2=H(1)
ID5, ///< A0=H(1), A1=L(0), A2=H(1)
ID6, ///< A0=L(0), A1=H(1), A2=H(1)
ID7, ///< A0=H(1), A1=H(1), A2=H(1)
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 64K バイトまでの EEPROM の ID (0 to 7) @n
アドレス指定が2バイトのデバイス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class M64KB : uint8_t {
ID0, ///< A0=L(0), A1=L(0), A2=L(0)
ID1, ///< A0=H(1), A1=L(0), A2=L(0)
ID2, ///< A0=L(0), A1=H(1), A2=L(0)
ID3, ///< A0=H(1), A1=H(1), A2=L(0)
ID4, ///< A0=L(0), A1=L(0), A2=H(1)
ID5, ///< A0=H(1), A1=L(0), A2=H(1)
ID6, ///< A0=L(0), A1=H(1), A2=H(1)
ID7, ///< A0=H(1), A1=H(1), A2=H(1)
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 128K バイトの EEPROM の ID (0 to 3) @n
アドレス指定が2バイトのデバイス @n
A2 端子が、バンクセレクトに使われるデバイス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class M128KB : uint8_t {
ID0, ///< A0=L(0), A1=L(0)
ID1, ///< A0=H(1), A1=L(0)
ID2, ///< A0=L(0), A1=H(1)
ID3, ///< A0=H(1), A1=H(1)
};
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] i2c i2c_io クラスを参照で渡す
*/
//-----------------------------------------------------------------//
EEPROM(I2C_IO& i2c) : i2c_(i2c), ds_(0),
exp_(false), ad_mix_(false), pagen_(1) { }
//-----------------------------------------------------------------//
/*!
@brief アドレス指定1バイトの EEPROM を開始
@param[in] type デバイスのタイプとID
@param[in] pagen ページサイズ(書き込み一時バッファのサイズ)
*/
//-----------------------------------------------------------------//
void start(M256B type_id, uint8_t pagen) {
ds_ = static_cast<uint8_t>(type_id);
exp_ = false;
ad_mix_ = false;
pagen_ = pagen;
}
//-----------------------------------------------------------------//
/*!
@brief アドレス指定2バイトの EEPROM を開始
@param[in] type デバイスのタイプとID
@param[in] pagen ページサイズ(書き込み一時バッファのサイズ)
*/
//-----------------------------------------------------------------//
void start(M64KB type_id, uint8_t pagen) {
ds_ = static_cast<uint8_t>(type_id);
exp_ = true;
ad_mix_ = false;
pagen_ = pagen;
}
//-----------------------------------------------------------------//
/*!
@brief アドレス指定2バイトで、「A2」がバンクの EEPROM を開始
@param[in] type デバイスのタイプとID
@param[in] pagen ページサイズ(書き込み一時バッファのサイズ)
*/
//-----------------------------------------------------------------//
void start(M128KB type_id, uint8_t pagen) {
ds_ = static_cast<uint8_t>(type_id);
exp_ = true;
ad_mix_ = true;
pagen_ = pagen;
}
//-----------------------------------------------------------------//
/*!
@brief 書き込み状態の検査
@param[in] adr 検査アドレス
@return 「false」なら、書き込み中
*/
//-----------------------------------------------------------------//
bool get_write_state(uint32_t adr) const {
uint8_t tmp[1];
return read(adr, tmp, 1);
}
//-----------------------------------------------------------------//
/*!
@brief 書き込み同期
@param[in] adr 検査アドレス
@param[in] delay 待ち時間(10us単位)
@return デバイスエラーなら「false」
*/
//-----------------------------------------------------------------//
bool sync_write(uint32_t adr, uint16_t delay = 600) const {
bool ok = false;
for(uint16_t i = 0; i < delay; ++i) {
utils::delay::micro_second(10);
uint8_t tmp[1];
if(read(adr, tmp, 1)) {
ok = true;
break;
}
}
return ok;
}
//-----------------------------------------------------------------//
/*!
@brief EEPROM 読み出し
@param[in] adr 読み出しアドレス
@param[out] dst 先
@param[in] len 長さ
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool read(uint32_t adr, uint8_t* dst, uint16_t len) const {
uint8_t tmp[2];
if(exp_) {
tmp[0] = (adr >> 8) & 255;
tmp[1] = adr & 255;
if(!i2c_.send(i2c_adr_(adr), tmp, 2)) {
return false;
}
} else {
tmp[0] = adr & 255;
if(!i2c_.send(i2c_adr_(adr), tmp, 1)) {
return false;
}
}
if(!i2c_.recv(i2c_adr_(adr), dst, len)) {
return false;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief EEPROM 書き込み
@param[in] adr 書き込みアドレス
@param[out] src 元
@param[in] len 長さ
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool write(uint32_t adr, const uint8_t* src, uint16_t len) const {
while(len > 0) {
uint16_t l = pagen_ - (adr & (pagen_ - 1));
if(len < l) l = len;
if(exp_) {
if(!i2c_.send(i2c_adr_(adr), adr >> 8, adr & 255, src, l)) {
return false;
}
} else {
if(!i2c_.send(i2c_adr_(adr), adr & 255, src, l)) {
return false;
}
}
src += l;
len -= l;
if(len) { // 書き込み終了を待つポーリング
if(!sync_write(adr)) {
return false;
}
}
adr += l;
}
return true;
}
};
}
<|endoftext|>
|
<commit_before>#include "ThermalContactMaterialsAction.h"
#include "ThermalContactAuxVarsAction.h"
#include "Factory.h"
static unsigned int n = 0;
template<>
InputParameters validParams<ThermalContactMaterialsAction>()
{
MooseEnum orders("CONSTANT, FIRST, SECOND, THIRD, FOURTH", "FIRST");
InputParameters params = validParams<Action>();
params.addParam<std::string>("appended_property_name", "", "Name appended to material properties to make them unique");
params.addRequiredParam<std::string>("type", "A string representing the Moose object that will be used for heat conduction over the gap");
params.addRequiredParam<NonlinearVariableName>("variable", "The variable for thermal contact");
params.addRequiredParam<BoundaryName>("master", "The master surface");
params.addRequiredParam<BoundaryName>("slave", "The slave surface");
params.addParam<Real>("gap_conductivity", 1.0, "The thermal conductivity of the gap material");
params.addParam<MooseEnum>("order", orders, "The finite element order");
params.addParam<bool>("warnings", false, "Whether to output warning messages concerning nodes not being found");
params.addParam<bool>("quadrature", false, "Whether or not to use quadrature point based gap heat transfer");
params.addParam<VariableName>("contact_pressure", "The contact pressure variable");
return params;
}
ThermalContactMaterialsAction::ThermalContactMaterialsAction( const std::string & name, InputParameters params ) :
Action(name, params)
{
}
void
ThermalContactMaterialsAction::act()
{
bool quadrature = getParam<bool>("quadrature");
std::string type("GapConductance");
if (getParam<std::string>("type") == "GapHeatTransferLWR")
{
type += "LWR";
}
InputParameters params = _factory.getValidParams(type);
// Extract global params
_app.parser().extractParams(_name, params);
params.print();
params.set<std::vector<VariableName> >("variable") = std::vector<VariableName>(1, getParam<NonlinearVariableName>("variable"));
if(!quadrature)
{
params.set<std::vector<AuxVariableName> >("gap_temp") = std::vector<AuxVariableName>(1, ThermalContactAuxVarsAction::getGapValueName(_pars));
std::vector<AuxVariableName> vars(1);
vars[0] = "penetration";
params.set<std::vector<AuxVariableName> >("gap_distance") = vars;
}
else
{
std::vector<VariableName> vars(1);
vars[0] = getParam<NonlinearVariableName>("variable");
params.set<std::vector<VariableName> >("temp") = vars;
params.set<bool>("quadrature") = true;
params.set<BoundaryName>("paired_boundary") = getParam<BoundaryName>("master");
params.set<MooseEnum>("order") = getParam<MooseEnum>("order");
}
params.set<bool>("warnings") = getParam<bool>("warnings");
params.set<Real>("gap_conductivity") = getParam<Real>("gap_conductivity");
std::vector<BoundaryName> bnds(1, getParam<BoundaryName>("slave"));
params.set<std::vector<BoundaryName> >("boundary") = bnds;
params.set<std::string>("appended_property_name") = getParam<std::string>("appended_property_name");
if (getParam<std::string>("type") == "GapHeatTransferLWR")
{
std::vector<VariableName> v(1, ThermalContactAuxVarsAction::getGapConductivityName(_pars));
params.set<std::vector<VariableName> >("gap_k") = v;
if (isParamValid("contact_pressure"))
{
v[0] = getParam<VariableName>("contact_pressure");
params.set<std::vector<VariableName> >("contact_pressure") = v;
}
}
_problem->addMaterial(type,
"gap_value_" + Moose::stringify(n),
params);
if (quadrature)
{
params.set<BoundaryName>("paired_boundary") = getParam<BoundaryName>("slave");
std::vector<BoundaryName> bnds(1, getParam<BoundaryName>("master"));
params.set<std::vector<BoundaryName> >("boundary") = bnds;
if (getParam<std::string>("type") == "GapHeatTransferLWR")
{
params.set<bool>("slave_side") = false;
}
_problem->addMaterial(type,
"gap_value_master_" + Moose::stringify(n),
params);
}
++n;
}
<commit_msg>Remove debugging statement<commit_after>#include "ThermalContactMaterialsAction.h"
#include "ThermalContactAuxVarsAction.h"
#include "Factory.h"
static unsigned int n = 0;
template<>
InputParameters validParams<ThermalContactMaterialsAction>()
{
MooseEnum orders("CONSTANT, FIRST, SECOND, THIRD, FOURTH", "FIRST");
InputParameters params = validParams<Action>();
params.addParam<std::string>("appended_property_name", "", "Name appended to material properties to make them unique");
params.addRequiredParam<std::string>("type", "A string representing the Moose object that will be used for heat conduction over the gap");
params.addRequiredParam<NonlinearVariableName>("variable", "The variable for thermal contact");
params.addRequiredParam<BoundaryName>("master", "The master surface");
params.addRequiredParam<BoundaryName>("slave", "The slave surface");
params.addParam<Real>("gap_conductivity", 1.0, "The thermal conductivity of the gap material");
params.addParam<MooseEnum>("order", orders, "The finite element order");
params.addParam<bool>("warnings", false, "Whether to output warning messages concerning nodes not being found");
params.addParam<bool>("quadrature", false, "Whether or not to use quadrature point based gap heat transfer");
params.addParam<VariableName>("contact_pressure", "The contact pressure variable");
return params;
}
ThermalContactMaterialsAction::ThermalContactMaterialsAction( const std::string & name, InputParameters params ) :
Action(name, params)
{
}
void
ThermalContactMaterialsAction::act()
{
bool quadrature = getParam<bool>("quadrature");
std::string type("GapConductance");
if (getParam<std::string>("type") == "GapHeatTransferLWR")
{
type += "LWR";
}
InputParameters params = _factory.getValidParams(type);
// Extract global params
_app.parser().extractParams(_name, params);
params.set<std::vector<VariableName> >("variable") = std::vector<VariableName>(1, getParam<NonlinearVariableName>("variable"));
if(!quadrature)
{
params.set<std::vector<AuxVariableName> >("gap_temp") = std::vector<AuxVariableName>(1, ThermalContactAuxVarsAction::getGapValueName(_pars));
std::vector<AuxVariableName> vars(1);
vars[0] = "penetration";
params.set<std::vector<AuxVariableName> >("gap_distance") = vars;
}
else
{
std::vector<VariableName> vars(1);
vars[0] = getParam<NonlinearVariableName>("variable");
params.set<std::vector<VariableName> >("temp") = vars;
params.set<bool>("quadrature") = true;
params.set<BoundaryName>("paired_boundary") = getParam<BoundaryName>("master");
params.set<MooseEnum>("order") = getParam<MooseEnum>("order");
}
params.set<bool>("warnings") = getParam<bool>("warnings");
params.set<Real>("gap_conductivity") = getParam<Real>("gap_conductivity");
std::vector<BoundaryName> bnds(1, getParam<BoundaryName>("slave"));
params.set<std::vector<BoundaryName> >("boundary") = bnds;
params.set<std::string>("appended_property_name") = getParam<std::string>("appended_property_name");
if (getParam<std::string>("type") == "GapHeatTransferLWR")
{
std::vector<VariableName> v(1, ThermalContactAuxVarsAction::getGapConductivityName(_pars));
params.set<std::vector<VariableName> >("gap_k") = v;
if (isParamValid("contact_pressure"))
{
v[0] = getParam<VariableName>("contact_pressure");
params.set<std::vector<VariableName> >("contact_pressure") = v;
}
}
_problem->addMaterial(type,
"gap_value_" + Moose::stringify(n),
params);
if (quadrature)
{
params.set<BoundaryName>("paired_boundary") = getParam<BoundaryName>("slave");
std::vector<BoundaryName> bnds(1, getParam<BoundaryName>("master"));
params.set<std::vector<BoundaryName> >("boundary") = bnds;
if (getParam<std::string>("type") == "GapHeatTransferLWR")
{
params.set<bool>("slave_side") = false;
}
_problem->addMaterial(type,
"gap_value_master_" + Moose::stringify(n),
params);
}
++n;
}
<|endoftext|>
|
<commit_before>#include "terrainedit.h"
#include "terrain.h"
#include <QRect>
inline uint qHash(const QPoint &key, uint seed)
{
return qHash(key.x(), seed) ^ (qHash(key.y(), seed) >> 8 | qHash(~key.y(), seed) << 24);
}
TerrainEdit::TerrainEdit(QObject *parent) :
QObject(parent),
done_(false)
{
}
TerrainEdit::~TerrainEdit()
{
}
void TerrainEdit::beginEdit(const QRect &r, Terrain *t)
{
Q_ASSERT(!done_);
Q_ASSERT(t);
Q_ASSERT(r.isValid());
Q_ASSERT(r.left() >= 0); Q_ASSERT(r.top() >= 0);
Q_ASSERT(r.x() + r.width() <= t->size().width());
Q_ASSERT(r.y() + r.height() <= t->size().height());
int x1 = r.x() >> SubeditSizeBits;
int y1 = r.y() >> SubeditSizeBits;
int x2 = (r.x() + r.width() + SubeditSize - 1) >> SubeditSizeBits;
int y2 = (r.y() + r.height() + SubeditSize - 1) >> SubeditSizeBits;
for (int x = x1; x < x2; ++x) {
for (int y = y1; y < y2; ++y) {
QPoint block(x, y);
TerrainSubedit &subedit = subedits_[block];
if (!subedit.before) {
// initialize subedit
subedit.position = QPoint(x << SubeditSizeBits, y << SubeditSizeBits);
subedit.before = std::make_shared<Terrain>(QSize(SubeditSize, SubeditSize));
subedit.after = std::make_shared<Terrain>(QSize(SubeditSize, SubeditSize));
subedit.before->copyFrom(t, QPoint(0, 0), QRect(subedit.position, QSize(SubeditSize, SubeditSize)));
subedit.editing = false;
}
subedit.editing = true;
}
}
}
void TerrainEdit::endEdit(Terrain *t)
{
Q_ASSERT(!done_);
Q_ASSERT(t);
QRect rt;
for (TerrainSubedit& e: subedits_) {
if (e.editing) {
if (rt.isEmpty()) {
rt = QRect(e.position.x(), e.position.y(), SubeditSize, SubeditSize);
} else {
rt = rt.united(QRect(e.position.x(), e.position.y(), SubeditSize, SubeditSize));
}
e.after->copyFrom(t, QPoint(0, 0), QRect(e.position.x(), e.position.y(), SubeditSize, SubeditSize));
e.editing = false;
}
}
if (!rt.isEmpty()) {
emit edited(rt);
}
}
void TerrainEdit::done()
{
done_ = true;
}
void TerrainEdit::apply(Terrain *t)
{
Q_ASSERT(t);
for (TerrainSubedit& e: subedits_) {
t->copyFrom(e.after.get(), e.position);
}
}
void TerrainEdit::undo(Terrain *t)
{
Q_ASSERT(t);
for (TerrainSubedit& e: subedits_) {
t->copyFrom(e.before.get(), e.position);
}
}
QRect TerrainEdit::modifiedBounds()
{
QRect rt;
for (TerrainSubedit& e: subedits_) {
if (rt.isEmpty()) {
rt = QRect(e.position.x(), e.position.y(), SubeditSize, SubeditSize);
} else {
rt = rt.united(QRect(e.position.x(), e.position.y(), SubeditSize, SubeditSize));
}
}
return rt;
}
void TerrainEdit::copyBeforeTo(const QRect &srcRect, Terrain *after, Terrain *copyTo)
{
Q_ASSERT(after);
Q_ASSERT(copyTo);
QRect r = srcRect;
Q_ASSERT(r.x() >= 0); Q_ASSERT(r.y() >= 0);
Q_ASSERT(r.x() + r.width() < after->size().width());
Q_ASSERT(r.y() + r.height() < after->size().height());
// TODO: clip copy destination size by srcRect
int x1 = r.x() >> SubeditSizeBits;
int y1 = r.y() >> SubeditSizeBits;
int x2 = (r.x() + r.width() + SubeditSize - 1) >> SubeditSizeBits;
int y2 = (r.y() + r.height() + SubeditSize - 1) >> SubeditSizeBits;
for (int x = x1; x < x2; ++x) {
for (int y = y1; y < y2; ++y) {
QPoint block(x, y);
auto it = subedits_.find(block);
if (it == subedits_.end()) {
// unmodified
copyTo->copyFrom(after, QPoint((x << SubeditSizeBits) - srcRect.x(), (y << SubeditSizeBits) - srcRect.y()),
QRect(x << SubeditSizeBits, y << SubeditSizeBits,
SubeditSize, SubeditSize));
} else {
// modified
TerrainSubedit &subedit = *it;
copyTo->copyFrom(subedit.before.get(),
QPoint((x << SubeditSizeBits) - srcRect.x(), (y << SubeditSizeBits) - srcRect.y()));
}
}
}
}
uint TerrainEdit::size() const
{
return subedits_.size() * SubeditSize * SubeditSize * 8;
}
<commit_msg>Fix asserts<commit_after>#include "terrainedit.h"
#include "terrain.h"
#include <QRect>
inline uint qHash(const QPoint &key, uint seed)
{
return qHash(key.x(), seed) ^ (qHash(key.y(), seed) >> 8 | qHash(~key.y(), seed) << 24);
}
TerrainEdit::TerrainEdit(QObject *parent) :
QObject(parent),
done_(false)
{
}
TerrainEdit::~TerrainEdit()
{
}
void TerrainEdit::beginEdit(const QRect &r, Terrain *t)
{
Q_ASSERT(!done_);
Q_ASSERT(t);
if (r.isEmpty()) {
return;
}
Q_ASSERT(r.left() >= 0); Q_ASSERT(r.top() >= 0);
Q_ASSERT(r.x() + r.width() <= t->size().width());
Q_ASSERT(r.y() + r.height() <= t->size().height());
int x1 = r.x() >> SubeditSizeBits;
int y1 = r.y() >> SubeditSizeBits;
int x2 = (r.x() + r.width() + SubeditSize - 1) >> SubeditSizeBits;
int y2 = (r.y() + r.height() + SubeditSize - 1) >> SubeditSizeBits;
for (int x = x1; x < x2; ++x) {
for (int y = y1; y < y2; ++y) {
QPoint block(x, y);
TerrainSubedit &subedit = subedits_[block];
if (!subedit.before) {
// initialize subedit
subedit.position = QPoint(x << SubeditSizeBits, y << SubeditSizeBits);
subedit.before = std::make_shared<Terrain>(QSize(SubeditSize, SubeditSize));
subedit.after = std::make_shared<Terrain>(QSize(SubeditSize, SubeditSize));
subedit.before->copyFrom(t, QPoint(0, 0), QRect(subedit.position, QSize(SubeditSize, SubeditSize)));
subedit.editing = false;
}
subedit.editing = true;
}
}
}
void TerrainEdit::endEdit(Terrain *t)
{
Q_ASSERT(!done_);
Q_ASSERT(t);
QRect rt;
for (TerrainSubedit& e: subedits_) {
if (e.editing) {
if (rt.isEmpty()) {
rt = QRect(e.position.x(), e.position.y(), SubeditSize, SubeditSize);
} else {
rt = rt.united(QRect(e.position.x(), e.position.y(), SubeditSize, SubeditSize));
}
e.after->copyFrom(t, QPoint(0, 0), QRect(e.position.x(), e.position.y(), SubeditSize, SubeditSize));
e.editing = false;
}
}
if (!rt.isEmpty()) {
emit edited(rt);
}
}
void TerrainEdit::done()
{
done_ = true;
}
void TerrainEdit::apply(Terrain *t)
{
Q_ASSERT(t);
for (TerrainSubedit& e: subedits_) {
t->copyFrom(e.after.get(), e.position);
}
}
void TerrainEdit::undo(Terrain *t)
{
Q_ASSERT(t);
for (TerrainSubedit& e: subedits_) {
t->copyFrom(e.before.get(), e.position);
}
}
QRect TerrainEdit::modifiedBounds()
{
QRect rt;
for (TerrainSubedit& e: subedits_) {
if (rt.isEmpty()) {
rt = QRect(e.position.x(), e.position.y(), SubeditSize, SubeditSize);
} else {
rt = rt.united(QRect(e.position.x(), e.position.y(), SubeditSize, SubeditSize));
}
}
return rt;
}
void TerrainEdit::copyBeforeTo(const QRect &srcRect, Terrain *after, Terrain *copyTo)
{
Q_ASSERT(after);
Q_ASSERT(copyTo);
QRect r = srcRect;
Q_ASSERT(r.x() >= 0); Q_ASSERT(r.y() >= 0);
Q_ASSERT(r.x() + r.width() <= after->size().width());
Q_ASSERT(r.y() + r.height() <= after->size().height());
// TODO: clip copy destination size by srcRect
int x1 = r.x() >> SubeditSizeBits;
int y1 = r.y() >> SubeditSizeBits;
int x2 = (r.x() + r.width() + SubeditSize - 1) >> SubeditSizeBits;
int y2 = (r.y() + r.height() + SubeditSize - 1) >> SubeditSizeBits;
for (int x = x1; x < x2; ++x) {
for (int y = y1; y < y2; ++y) {
QPoint block(x, y);
auto it = subedits_.find(block);
if (it == subedits_.end()) {
// unmodified
copyTo->copyFrom(after, QPoint((x << SubeditSizeBits) - srcRect.x(), (y << SubeditSizeBits) - srcRect.y()),
QRect(x << SubeditSizeBits, y << SubeditSizeBits,
SubeditSize, SubeditSize));
} else {
// modified
TerrainSubedit &subedit = *it;
copyTo->copyFrom(subedit.before.get(),
QPoint((x << SubeditSizeBits) - srcRect.x(), (y << SubeditSizeBits) - srcRect.y()));
}
}
}
}
uint TerrainEdit::size() const
{
return subedits_.size() * SubeditSize * SubeditSize * 8;
}
<|endoftext|>
|
<commit_before>// set of classes to compare the performance of STL vector versus
// native Root TClonesArray.
// See main program bench.cxx
#include "TRandom.h"
#include "TFile.h"
#include "TTree.h"
#include "TClass.h"
//the next include must be the last one on systems like Windows/NT
#include "TBench.h"
THit hit;
const char *demofile = "$TEMP/bench.root";
//-------------------------------------------------------------
ClassImp(THit)
//-------------------------------------------------------------
THit::THit() {
fPulses = 0;
}
THit::THit(const THit &hit) {
fX = hit.fX;
fY = hit.fY;
fZ = hit.fZ;
for (Int_t i=0;i<10;i++) fTime[i] = hit.fTime[i];
fPulses = 0;
fNpulses = hit.fNpulses;
if (fNpulses == 0) return;
if (hit.fPulses == 0) return;
fPulses = new int[fNpulses];
for (int j=0;j<fNpulses;j++) fPulses[j] = hit.fPulses[j];
}
THit::THit(int t) {
fPulses = 0;
Set(t);
}
THit::~THit() {
if (fPulses) delete [] fPulses;
fPulses = 0;
}
void THit::Set(int t) {
fX = gRandom->Gaus(0,1);
fY = gRandom->Gaus(0,1);
fZ = gRandom->Gaus(0,10);
if (fPulses && fNpulses > 0) delete [] fPulses;
fNpulses = t%20 + 1;
fPulses = new int[fNpulses];
for (int j=0;j<fNpulses;j++) fPulses[j] = j+1;
for (int i=0; i<10; i++) fTime[i] = t+i;
}
#if 0
#if defined(R__TEMPLATE_OVERLOAD_BUG)
template <>
#endif
TBuffer &operator>>(TBuffer &buf, THit *&obj)
{
obj = new THit();
obj->Streamer(buf);
return buf;
}
#endif
TBuffer &operator<<(TBuffer &buf, const THit *obj)
{
((THit*)obj)->Streamer(buf);
return buf;
}
//-------------------------------------------------------------
ClassImp(TObjHit)
//-------------------------------------------------------------
TObjHit::TObjHit() :THit() {}
TObjHit::TObjHit(int t) :THit(t) {}
//-------------------------------------------------------------
ClassImp(TSTLhit)
//-------------------------------------------------------------
TSTLhit::TSTLhit()
{
}
TSTLhit::TSTLhit(Int_t nmax)
{
fNhits = nmax;
fList1.reserve(nmax);
}
TSTLhit::~TSTLhit() {
}
void TSTLhit::Clear(Option_t *)
{
fList1.erase(fList1.begin(),fList1.end());
}
void TSTLhit::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
hit.Set(j);
fList1.push_back(hit);
}
}
Int_t TSTLhit::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TSTLhit *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","STLhit",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TSTLhit",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TSTLhit::ReadTree()
{
TSTLhit *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
Clear();
}
delete f;
return nbytes;
}
//-------------------------------------------------------------
ClassImp(TSTLhitStar)
//-------------------------------------------------------------
TSTLhitStar::TSTLhitStar()
{
}
TSTLhitStar::TSTLhitStar(Int_t nmax)
{
fNhits = nmax;
fList2.reserve(nmax);
}
TSTLhitStar::~TSTLhitStar() {
}
void TSTLhitStar::Clear(Option_t *)
{
for (vector<THit*>::iterator it = fList2.begin(); it<fList2.end(); it++) {
delete (*it);
}
fList2.erase(fList2.begin(),fList2.end());
}
void TSTLhitStar::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
fList2.push_back(new THit(j));
}
}
Int_t TSTLhitStar::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TSTLhitStar *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","STLhitStar",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TSTLhitStar",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TSTLhitStar::ReadTree()
{
TSTLhitStar *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
Clear();
}
delete f;
return nbytes;
}
//-------------------------------------------------------------
ClassImp(TCloneshit)
//-------------------------------------------------------------
TCloneshit::TCloneshit()
{
fList3 = new TClonesArray("TObjHit");
}
TCloneshit::TCloneshit(Int_t nmax)
{
fNhits = nmax;
fList3 = new TClonesArray("TObjHit",nmax);
TObjHit::Class()->IgnoreTObjectStreamer();
}
TCloneshit::~TCloneshit() {
}
void TCloneshit::Clear(Option_t *)
{
fList3->Delete();
//fList3->Clear();
}
void TCloneshit::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
new((*fList3)[j]) TObjHit(j);
}
}
Int_t TCloneshit::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TCloneshit *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","Cloneshit",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TCloneshit",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TCloneshit::ReadTree()
{
TCloneshit *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
}
delete f;
return nbytes;
}
<commit_msg>Undo Philippe's change in TBench. Use /tmp/bench.root instead of $TEMP.<commit_after>// set of classes to compare the performance of STL vector versus
// native Root TClonesArray.
// See main program bench.cxx
#include "TRandom.h"
#include "TFile.h"
#include "TTree.h"
#include "TClass.h"
//the next include must be the last one on systems like Windows/NT
#include "TBench.h"
THit hit;
const char *demofile = "/tmp/bench.root";
//-------------------------------------------------------------
ClassImp(THit)
//-------------------------------------------------------------
THit::THit() {
fPulses = 0;
}
THit::THit(const THit &hit) {
fX = hit.fX;
fY = hit.fY;
fZ = hit.fZ;
for (Int_t i=0;i<10;i++) fTime[i] = hit.fTime[i];
fPulses = 0;
fNpulses = hit.fNpulses;
if (fNpulses == 0) return;
if (hit.fPulses == 0) return;
fPulses = new int[fNpulses];
for (int j=0;j<fNpulses;j++) fPulses[j] = hit.fPulses[j];
}
THit::THit(int t) {
fPulses = 0;
Set(t);
}
THit::~THit() {
if (fPulses) delete [] fPulses;
fPulses = 0;
}
void THit::Set(int t) {
fX = gRandom->Gaus(0,1);
fY = gRandom->Gaus(0,1);
fZ = gRandom->Gaus(0,10);
if (fPulses && fNpulses > 0) delete [] fPulses;
fNpulses = t%20 + 1;
fPulses = new int[fNpulses];
for (int j=0;j<fNpulses;j++) fPulses[j] = j+1;
for (int i=0; i<10; i++) fTime[i] = t+i;
}
#if 0
#if defined(R__TEMPLATE_OVERLOAD_BUG)
template <>
#endif
TBuffer &operator>>(TBuffer &buf, THit *&obj)
{
obj = new THit();
obj->Streamer(buf);
return buf;
}
#endif
TBuffer &operator<<(TBuffer &buf, const THit *obj)
{
((THit*)obj)->Streamer(buf);
return buf;
}
//-------------------------------------------------------------
ClassImp(TObjHit)
//-------------------------------------------------------------
TObjHit::TObjHit() :THit() {}
TObjHit::TObjHit(int t) :THit(t) {}
//-------------------------------------------------------------
ClassImp(TSTLhit)
//-------------------------------------------------------------
TSTLhit::TSTLhit()
{
}
TSTLhit::TSTLhit(Int_t nmax)
{
fNhits = nmax;
fList1.reserve(nmax);
}
TSTLhit::~TSTLhit() {
}
void TSTLhit::Clear(Option_t *)
{
fList1.erase(fList1.begin(),fList1.end());
}
void TSTLhit::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
hit.Set(j);
fList1.push_back(hit);
}
}
Int_t TSTLhit::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TSTLhit *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","STLhit",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TSTLhit",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TSTLhit::ReadTree()
{
TSTLhit *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
Clear();
}
delete f;
return nbytes;
}
//-------------------------------------------------------------
ClassImp(TSTLhitStar)
//-------------------------------------------------------------
TSTLhitStar::TSTLhitStar()
{
}
TSTLhitStar::TSTLhitStar(Int_t nmax)
{
fNhits = nmax;
fList2.reserve(nmax);
}
TSTLhitStar::~TSTLhitStar() {
}
void TSTLhitStar::Clear(Option_t *)
{
for (vector<THit*>::iterator it = fList2.begin(); it<fList2.end(); it++) {
delete (*it);
}
fList2.erase(fList2.begin(),fList2.end());
}
void TSTLhitStar::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
fList2.push_back(new THit(j));
}
}
Int_t TSTLhitStar::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TSTLhitStar *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","STLhitStar",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TSTLhitStar",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TSTLhitStar::ReadTree()
{
TSTLhitStar *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
Clear();
}
delete f;
return nbytes;
}
//-------------------------------------------------------------
ClassImp(TCloneshit)
//-------------------------------------------------------------
TCloneshit::TCloneshit()
{
fList3 = new TClonesArray("TObjHit");
}
TCloneshit::TCloneshit(Int_t nmax)
{
fNhits = nmax;
fList3 = new TClonesArray("TObjHit",nmax);
TObjHit::Class()->IgnoreTObjectStreamer();
}
TCloneshit::~TCloneshit() {
}
void TCloneshit::Clear(Option_t *)
{
fList3->Delete();
//fList3->Clear();
}
void TCloneshit::MakeEvent(int ievent)
{
Clear();
for (Int_t j=0; j<fNhits; j++) {
new((*fList3)[j]) TObjHit(j);
}
}
Int_t TCloneshit::MakeTree(int mode, int nevents, int compression, int split, float &cx)
{
TFile *f=0;
TTree *T=0;
TCloneshit *top = this;
if (mode > 0) {
f = new TFile(demofile,"recreate","Cloneshit",compression);
T = new TTree("T","Demo tree");
T->Branch("event","TCloneshit",&top,64000,split);
}
for (int ievent=0; ievent<nevents; ievent++) {
MakeEvent(ievent);
if (mode > 0) T->Fill();
}
if (mode == 0) return 0;
T->Write();
delete f;
f = new TFile(demofile);
Int_t nbytes = f->GetEND();
cx = f->GetCompressionFactor();
delete f;
return nbytes;
}
Int_t TCloneshit::ReadTree()
{
TCloneshit *top = this;
TFile *f = new TFile(demofile);
TTree *T = (TTree*)f->Get("T");
T->SetBranchAddress("event",&top);
Int_t nevents = (Int_t)T->GetEntries();
Int_t nbytes = 0;
for (int ievent=0; ievent<nevents; ievent++) {
nbytes += T->GetEntry(ievent);
}
delete f;
return nbytes;
}
<|endoftext|>
|
<commit_before>#include <QtCore/QPair>
#include <QtCore/QStack>
#include "generatorBase/masterGeneratorBase.h"
#include <qrutils/outFile.h>
#include <qrutils/stringUtils.h>
#include <qrtext/languageToolboxInterface.h>
#include "readableControlFlowGenerator.h"
#include "gotoControlFlowGenerator.h"
#include "generatorBase/lua/luaProcessor.h"
#include "generatorBase/parts/variables.h"
#include "generatorBase/parts/subprograms.h"
#include "generatorBase/parts/threads.h"
#include "generatorBase/parts/sensors.h"
#include "generatorBase/parts/initTerminateCodeGenerator.h"
using namespace generatorBase;
using namespace qReal;
MasterGeneratorBase::MasterGeneratorBase(const qrRepo::RepoApi &repo
, ErrorReporterInterface &errorReporter
, const kitBase::robotModel::RobotModelManagerInterface &robotModelManager
, qrtext::LanguageToolboxInterface &textLanguage
, const utils::ParserErrorReporter &parserErrorReporter
, const Id &diagramId)
: mRepo(repo)
, mErrorReporter(errorReporter)
, mRobotModelManager(robotModelManager)
, mTextLanguage(textLanguage)
, mDiagram(diagramId)
, mParserErrorReporter(parserErrorReporter)
{
}
void MasterGeneratorBase::setProjectDir(const QFileInfo &fileInfo)
{
mProjectName = fileInfo.baseName();
mProjectDir = fileInfo.absolutePath();
}
void MasterGeneratorBase::initialize()
{
mCustomizer = createCustomizer();
mCustomizer->factory()->initialize();
setPathToTemplates(mCustomizer->factory()->pathToTemplates());
mValidator = createValidator();
mReadableControlFlowGenerator = new ReadableControlFlowGenerator(mRepo
, mErrorReporter, *mCustomizer, *mValidator, mDiagram, this);
mGotoControlFlowGenerator = new GotoControlFlowGenerator(mRepo
, mErrorReporter, *mCustomizer, *mValidator, mDiagram, this);
}
QString MasterGeneratorBase::generate(const QString &indentString)
{
if (mDiagram.isNull()) {
mErrorReporter.addCritical(QObject::tr("There is no opened diagram"));
return QString();
}
beforeGeneration();
if (!QDir(mProjectDir).exists()) {
QDir().mkpath(mProjectDir);
}
mTextLanguage.clear();
mCustomizer->factory()->setMainDiagramId(mDiagram);
for (parts::InitTerminateCodeGenerator *generator : mCustomizer->factory()->initTerminateGenerators()) {
generator->reinit();
}
QString mainCode;
const semantics::SemanticTree *mainControlFlow = mReadableControlFlowGenerator->generate();
if (mainControlFlow && !mReadableControlFlowGenerator->cantBeGeneratedIntoStructuredCode()) {
mainCode = mainControlFlow->toString(1, indentString);
const bool subprogramsResult = mCustomizer->factory()->subprograms()->generate(mReadableControlFlowGenerator
, indentString);
if (!subprogramsResult) {
if (supportsGotoGeneration()) {
mainCode = QString();
} else {
return QString();
}
}
} else {
if (mReadableControlFlowGenerator->errorsOccured()) {
return QString();
}
}
if (mainCode.isEmpty() && supportsGotoGeneration()) {
mErrorReporter.addInformation(tr("This diagram cannot be generated into the structured code."\
" Generating it into the code with 'goto' statements."));
const semantics::SemanticTree *gotoMainControlFlow = mGotoControlFlowGenerator->generate();
if (gotoMainControlFlow) {
mainCode = gotoMainControlFlow->toString(1, indentString);
const bool gotoSubprogramsResult = mCustomizer->factory()
->subprograms()->generate(mGotoControlFlowGenerator, indentString);
if (!gotoSubprogramsResult) {
mainCode = QString();
}
}
}
if (mainCode.isEmpty()) {
const QString errorMessage = supportsGotoGeneration()
? tr("This diagram cannot be even generated into the code with 'goto'"\
"statements. Please contact the developers (WTF did you do?)")
: tr("This diagram cannot be generated into the structured code.");
mErrorReporter.addError(errorMessage);
return QString();
}
QString resultCode = readTemplate("main.t");
resultCode.replace("@@SUBPROGRAMS_FORWARDING@@", mCustomizer->factory()->subprograms()->forwardDeclarations());
resultCode.replace("@@SUBPROGRAMS@@", mCustomizer->factory()->subprograms()->implementations());
resultCode.replace("@@THREADS_FORWARDING@@", mCustomizer->factory()->threads().generateDeclarations());
resultCode.replace("@@THREADS@@", mCustomizer->factory()->threads().generateImplementations(indentString));
resultCode.replace("@@MAIN_CODE@@", mainCode);
resultCode.replace("@@INITHOOKS@@", utils::StringUtils::addIndent(
mCustomizer->factory()->initCode(), 1, indentString));
resultCode.replace("@@TERMINATEHOOKS@@", utils::StringUtils::addIndent(
mCustomizer->factory()->terminateCode(), 1, indentString));
resultCode.replace("@@USERISRHOOKS@@", utils::StringUtils::addIndent(
mCustomizer->factory()->isrHooksCode(), 1, indentString));
resultCode.replace("@@VARIABLES@@", mCustomizer->factory()->variables()->generateVariableString());
// This will remove too many empty lines
resultCode.replace(QRegExp("\n(\n)+"), "\n\n");
resultCode = generateLinkingInfo(resultCode);
processGeneratedCode(resultCode);
const QString pathToOutput = targetPath();
outputCode(pathToOutput, resultCode);
afterGeneration();
return pathToOutput;
}
QString MasterGeneratorBase::generateLinkingInfo(QString &resultCode)
{
QString const open = "@~(qrm:(/\\w+)+/\\{(\\w+-)+\\w+\\})~@";
QString const close = "@#%1#@";
QRegExp re;
QStack< QPair<QString, int> > stack;
QList< QPair<QString, QPair<int, int>> > results;
int lineNumber = 1;
for (QString const &line : resultCode.split("\n")){
re.setPattern(open);
int const pos = re.indexIn(line);
if (pos > -1) {
QString const id = re.cap(1);
stack.push(QPair<QString, int>(id, lineNumber));
}
if (!stack.isEmpty()) {
QString const id = stack.top().first;
if (line.contains(close.arg(id))) {
results.append(QPair<QString, QPair<int, int>>(id
, QPair<int, int>(stack.top().second, lineNumber)));
stack.pop();
}
}
lineNumber++;
}
QString out;
for (QPair<QString, QPair<int, int>> res : results) {
out += res.first + "@" + QString::number(res.second.first) + "@" + QString::number(res.second.second)
+ "\n";
}
QFileInfo fileInfo = QFileInfo(targetPath());
outputCode(fileInfo.absolutePath() + "/" + fileInfo.completeBaseName() + ".dbg", out);
return resultCode.remove(QRegExp("@(~|#)qrm:(/\\w+)+/\\{(\\w+-)+\\w+\\}(~|#)@"));
}
lua::LuaProcessor *MasterGeneratorBase::createLuaProcessor()
{
return new lua::LuaProcessor(mErrorReporter, mTextLanguage, mParserErrorReporter, this);
}
PrimaryControlFlowValidator *MasterGeneratorBase::createValidator()
{
return new PrimaryControlFlowValidator(mRepo, mErrorReporter, *mCustomizer, this);
}
void MasterGeneratorBase::beforeGeneration()
{
}
void MasterGeneratorBase::processGeneratedCode(QString &generatedCode)
{
Q_UNUSED(generatedCode)
}
void MasterGeneratorBase::afterGeneration()
{
}
void MasterGeneratorBase::outputCode(const QString &path, const QString &code)
{
// File must be removed to leave created and modified timestamps equal.
QFile::remove(path);
utils::OutFile out(path);
out() << code;
}
<commit_msg>little changes in clear regexp<commit_after>#include <QtCore/QPair>
#include <QtCore/QStack>
#include "generatorBase/masterGeneratorBase.h"
#include <qrutils/outFile.h>
#include <qrutils/stringUtils.h>
#include <qrtext/languageToolboxInterface.h>
#include "readableControlFlowGenerator.h"
#include "gotoControlFlowGenerator.h"
#include "generatorBase/lua/luaProcessor.h"
#include "generatorBase/parts/variables.h"
#include "generatorBase/parts/subprograms.h"
#include "generatorBase/parts/threads.h"
#include "generatorBase/parts/sensors.h"
#include "generatorBase/parts/initTerminateCodeGenerator.h"
using namespace generatorBase;
using namespace qReal;
MasterGeneratorBase::MasterGeneratorBase(const qrRepo::RepoApi &repo
, ErrorReporterInterface &errorReporter
, const kitBase::robotModel::RobotModelManagerInterface &robotModelManager
, qrtext::LanguageToolboxInterface &textLanguage
, const utils::ParserErrorReporter &parserErrorReporter
, const Id &diagramId)
: mRepo(repo)
, mErrorReporter(errorReporter)
, mRobotModelManager(robotModelManager)
, mTextLanguage(textLanguage)
, mDiagram(diagramId)
, mParserErrorReporter(parserErrorReporter)
{
}
void MasterGeneratorBase::setProjectDir(const QFileInfo &fileInfo)
{
mProjectName = fileInfo.baseName();
mProjectDir = fileInfo.absolutePath();
}
void MasterGeneratorBase::initialize()
{
mCustomizer = createCustomizer();
mCustomizer->factory()->initialize();
setPathToTemplates(mCustomizer->factory()->pathToTemplates());
mValidator = createValidator();
mReadableControlFlowGenerator = new ReadableControlFlowGenerator(mRepo
, mErrorReporter, *mCustomizer, *mValidator, mDiagram, this);
mGotoControlFlowGenerator = new GotoControlFlowGenerator(mRepo
, mErrorReporter, *mCustomizer, *mValidator, mDiagram, this);
}
QString MasterGeneratorBase::generate(const QString &indentString)
{
if (mDiagram.isNull()) {
mErrorReporter.addCritical(QObject::tr("There is no opened diagram"));
return QString();
}
beforeGeneration();
if (!QDir(mProjectDir).exists()) {
QDir().mkpath(mProjectDir);
}
mTextLanguage.clear();
mCustomizer->factory()->setMainDiagramId(mDiagram);
for (parts::InitTerminateCodeGenerator *generator : mCustomizer->factory()->initTerminateGenerators()) {
generator->reinit();
}
QString mainCode;
const semantics::SemanticTree *mainControlFlow = mReadableControlFlowGenerator->generate();
if (mainControlFlow && !mReadableControlFlowGenerator->cantBeGeneratedIntoStructuredCode()) {
mainCode = mainControlFlow->toString(1, indentString);
const bool subprogramsResult = mCustomizer->factory()->subprograms()->generate(mReadableControlFlowGenerator
, indentString);
if (!subprogramsResult) {
if (supportsGotoGeneration()) {
mainCode = QString();
} else {
return QString();
}
}
} else {
if (mReadableControlFlowGenerator->errorsOccured()) {
return QString();
}
}
if (mainCode.isEmpty() && supportsGotoGeneration()) {
mErrorReporter.addInformation(tr("This diagram cannot be generated into the structured code."\
" Generating it into the code with 'goto' statements."));
const semantics::SemanticTree *gotoMainControlFlow = mGotoControlFlowGenerator->generate();
if (gotoMainControlFlow) {
mainCode = gotoMainControlFlow->toString(1, indentString);
const bool gotoSubprogramsResult = mCustomizer->factory()
->subprograms()->generate(mGotoControlFlowGenerator, indentString);
if (!gotoSubprogramsResult) {
mainCode = QString();
}
}
}
if (mainCode.isEmpty()) {
const QString errorMessage = supportsGotoGeneration()
? tr("This diagram cannot be even generated into the code with 'goto'"\
"statements. Please contact the developers (WTF did you do?)")
: tr("This diagram cannot be generated into the structured code.");
mErrorReporter.addError(errorMessage);
return QString();
}
QString resultCode = readTemplate("main.t");
resultCode.replace("@@SUBPROGRAMS_FORWARDING@@", mCustomizer->factory()->subprograms()->forwardDeclarations());
resultCode.replace("@@SUBPROGRAMS@@", mCustomizer->factory()->subprograms()->implementations());
resultCode.replace("@@THREADS_FORWARDING@@", mCustomizer->factory()->threads().generateDeclarations());
resultCode.replace("@@THREADS@@", mCustomizer->factory()->threads().generateImplementations(indentString));
resultCode.replace("@@MAIN_CODE@@", mainCode);
resultCode.replace("@@INITHOOKS@@", utils::StringUtils::addIndent(
mCustomizer->factory()->initCode(), 1, indentString));
resultCode.replace("@@TERMINATEHOOKS@@", utils::StringUtils::addIndent(
mCustomizer->factory()->terminateCode(), 1, indentString));
resultCode.replace("@@USERISRHOOKS@@", utils::StringUtils::addIndent(
mCustomizer->factory()->isrHooksCode(), 1, indentString));
resultCode.replace("@@VARIABLES@@", mCustomizer->factory()->variables()->generateVariableString());
// This will remove too many empty lines
resultCode.replace(QRegExp("\n(\n)+"), "\n\n");
resultCode = generateLinkingInfo(resultCode);
processGeneratedCode(resultCode);
const QString pathToOutput = targetPath();
outputCode(pathToOutput, resultCode);
afterGeneration();
return pathToOutput;
}
QString MasterGeneratorBase::generateLinkingInfo(QString &resultCode)
{
QString const open = "@~(qrm:(/\\w+)+/\\{(\\w+-)+\\w+\\})~@";
QString const close = "@#%1#@";
QRegExp re;
QStack< QPair<QString, int> > stack;
QList< QPair<QString, QPair<int, int>> > results;
int lineNumber = 1;
for (QString const &line : resultCode.split("\n")){
re.setPattern(open);
int const pos = re.indexIn(line);
if (pos > -1) {
QString const id = re.cap(1);
stack.push(QPair<QString, int>(id, lineNumber));
}
if (!stack.isEmpty()) {
QString const id = stack.top().first;
if (line.contains(close.arg(id))) {
results.append(QPair<QString, QPair<int, int>>(id
, QPair<int, int>(stack.top().second, lineNumber)));
stack.pop();
}
}
lineNumber++;
}
QString out;
for (QPair<QString, QPair<int, int>> res : results) {
out += res.first + "@" + QString::number(res.second.first) + "@" + QString::number(res.second.second)
+ "\n";
}
QFileInfo fileInfo = QFileInfo(targetPath());
outputCode(fileInfo.absolutePath() + "/" + fileInfo.completeBaseName() + ".dbg", out);
return resultCode.remove(QRegExp("@(~|#)qrm:(((/\\w+)+/\\{(\\w+-)+\\w+\\})|(/))(~|#)@"));
}
lua::LuaProcessor *MasterGeneratorBase::createLuaProcessor()
{
return new lua::LuaProcessor(mErrorReporter, mTextLanguage, mParserErrorReporter, this);
}
PrimaryControlFlowValidator *MasterGeneratorBase::createValidator()
{
return new PrimaryControlFlowValidator(mRepo, mErrorReporter, *mCustomizer, this);
}
void MasterGeneratorBase::beforeGeneration()
{
}
void MasterGeneratorBase::processGeneratedCode(QString &generatedCode)
{
Q_UNUSED(generatedCode)
}
void MasterGeneratorBase::afterGeneration()
{
}
void MasterGeneratorBase::outputCode(const QString &path, const QString &code)
{
// File must be removed to leave created and modified timestamps equal.
QFile::remove(path);
utils::OutFile out(path);
out() << code;
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2013 Gauthier Brun <brun.gauthier@gmail.com>
// Copyright (C) 2013 Nicolas Carre <nicolas.carre@ensimag.fr>
// Copyright (C) 2013 Jean Ceccato <jean.ceccato@ensimag.fr>
// Copyright (C) 2013 Pierre Zoppitelli <pierre.zoppitelli@ensimag.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/
// discard stack allocation as that too bypasses malloc
#define EIGEN_STACK_ALLOCATION_LIMIT 0
#define EIGEN_RUNTIME_NO_MALLOC
#include "main.h"
#include <Eigen/SVD>
#include <iostream>
#include <Eigen/LU>
#define SVD_DEFAULT(M) BDCSVD<M>
#define SVD_FOR_MIN_NORM(M) BDCSVD<M>
#include "../../test/svd_common.h"
// Check all variants of JacobiSVD
template<typename MatrixType>
void bdcsvd(const MatrixType& a = MatrixType(), bool pickrandom = true)
{
MatrixType m = a;
if(pickrandom)
svd_fill_random(m);
CALL_SUBTEST(( svd_test_all_computation_options<BDCSVD<MatrixType> >(m, false) ));
}
template<typename MatrixType>
void bdcsvd_method()
{
enum { Size = MatrixType::RowsAtCompileTime };
typedef typename MatrixType::RealScalar RealScalar;
typedef Matrix<RealScalar, Size, 1> RealVecType;
MatrixType m = MatrixType::Identity();
VERIFY_IS_APPROX(m.bdcSvd().singularValues(), RealVecType::Ones());
VERIFY_RAISES_ASSERT(m.bdcSvd().matrixU());
VERIFY_RAISES_ASSERT(m.bdcSvd().matrixV());
VERIFY_IS_APPROX(m.bdcSvd(ComputeFullU|ComputeFullV).solve(m), m);
}
// compare the Singular values returned with Jacobi and Bdc
template<typename MatrixType>
void compare_bdc_jacobi(const MatrixType& a = MatrixType(), unsigned int computationOptions = 0)
{
MatrixType m = MatrixType::Random(a.rows(), a.cols());
BDCSVD<MatrixType> bdc_svd(m);
JacobiSVD<MatrixType> jacobi_svd(m);
VERIFY_IS_APPROX(bdc_svd.singularValues(), jacobi_svd.singularValues());
if(computationOptions & ComputeFullU) VERIFY_IS_APPROX(bdc_svd.matrixU(), jacobi_svd.matrixU());
if(computationOptions & ComputeThinU) VERIFY_IS_APPROX(bdc_svd.matrixU(), jacobi_svd.matrixU());
if(computationOptions & ComputeFullV) VERIFY_IS_APPROX(bdc_svd.matrixV(), jacobi_svd.matrixV());
if(computationOptions & ComputeThinV) VERIFY_IS_APPROX(bdc_svd.matrixV(), jacobi_svd.matrixV());
}
void test_bdcsvd()
{
CALL_SUBTEST_3(( svd_verify_assert<BDCSVD<Matrix3f> >(Matrix3f()) ));
CALL_SUBTEST_4(( svd_verify_assert<BDCSVD<Matrix4d> >(Matrix4d()) ));
CALL_SUBTEST_7(( svd_verify_assert<BDCSVD<MatrixXf> >(MatrixXf(10,12)) ));
CALL_SUBTEST_8(( svd_verify_assert<BDCSVD<MatrixXcd> >(MatrixXcd(7,5)) ));
CALL_SUBTEST_1(( svd_all_trivial_2x2(bdcsvd<Matrix2cd>) ));
CALL_SUBTEST_1(( svd_all_trivial_2x2(bdcsvd<Matrix2d>) ));
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_3(( bdcsvd<Matrix3f>() ));
CALL_SUBTEST_4(( bdcsvd<Matrix4d>() ));
CALL_SUBTEST_5(( bdcsvd<Matrix<float,3,5> >() ));
int r = internal::random<int>(1, EIGEN_TEST_MAX_SIZE/2),
c = internal::random<int>(1, EIGEN_TEST_MAX_SIZE/2);
TEST_SET_BUT_UNUSED_VARIABLE(r)
TEST_SET_BUT_UNUSED_VARIABLE(c)
CALL_SUBTEST_6(( bdcsvd(Matrix<double,Dynamic,2>(r,2)) ));
CALL_SUBTEST_7(( bdcsvd(MatrixXf(r,c)) ));
CALL_SUBTEST_7(( compare_bdc_jacobi(MatrixXf(r,c)) ));
CALL_SUBTEST_10(( bdcsvd(MatrixXd(r,c)) ));
CALL_SUBTEST_10(( compare_bdc_jacobi(MatrixXd(r,c)) ));
CALL_SUBTEST_8(( bdcsvd(MatrixXcd(r,c)) ));
CALL_SUBTEST_8(( compare_bdc_jacobi(MatrixXcd(r,c)) ));
// Test on inf/nan matrix
CALL_SUBTEST_7( (svd_inf_nan<BDCSVD<MatrixXf>, MatrixXf>()) );
CALL_SUBTEST_10( (svd_inf_nan<BDCSVD<MatrixXd>, MatrixXd>()) );
}
// test matrixbase method
CALL_SUBTEST_1(( bdcsvd_method<Matrix2cd>() ));
CALL_SUBTEST_3(( bdcsvd_method<Matrix3f>() ));
// Test problem size constructors
CALL_SUBTEST_7( BDCSVD<MatrixXf>(10,10) );
// Check that preallocation avoids subsequent mallocs
CALL_SUBTEST_9( svd_preallocate() );
CALL_SUBTEST_2( svd_underoverflow() );
}
<commit_msg>Fixed include in bdcsvd.cpp<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2013 Gauthier Brun <brun.gauthier@gmail.com>
// Copyright (C) 2013 Nicolas Carre <nicolas.carre@ensimag.fr>
// Copyright (C) 2013 Jean Ceccato <jean.ceccato@ensimag.fr>
// Copyright (C) 2013 Pierre Zoppitelli <pierre.zoppitelli@ensimag.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/
// discard stack allocation as that too bypasses malloc
#define EIGEN_STACK_ALLOCATION_LIMIT 0
#define EIGEN_RUNTIME_NO_MALLOC
#include "main.h"
#include <Eigen/SVD>
#include <iostream>
#include <Eigen/LU>
#define SVD_DEFAULT(M) BDCSVD<M>
#define SVD_FOR_MIN_NORM(M) BDCSVD<M>
#include "svd_common.h"
// Check all variants of JacobiSVD
template<typename MatrixType>
void bdcsvd(const MatrixType& a = MatrixType(), bool pickrandom = true)
{
MatrixType m = a;
if(pickrandom)
svd_fill_random(m);
CALL_SUBTEST(( svd_test_all_computation_options<BDCSVD<MatrixType> >(m, false) ));
}
template<typename MatrixType>
void bdcsvd_method()
{
enum { Size = MatrixType::RowsAtCompileTime };
typedef typename MatrixType::RealScalar RealScalar;
typedef Matrix<RealScalar, Size, 1> RealVecType;
MatrixType m = MatrixType::Identity();
VERIFY_IS_APPROX(m.bdcSvd().singularValues(), RealVecType::Ones());
VERIFY_RAISES_ASSERT(m.bdcSvd().matrixU());
VERIFY_RAISES_ASSERT(m.bdcSvd().matrixV());
VERIFY_IS_APPROX(m.bdcSvd(ComputeFullU|ComputeFullV).solve(m), m);
}
// compare the Singular values returned with Jacobi and Bdc
template<typename MatrixType>
void compare_bdc_jacobi(const MatrixType& a = MatrixType(), unsigned int computationOptions = 0)
{
MatrixType m = MatrixType::Random(a.rows(), a.cols());
BDCSVD<MatrixType> bdc_svd(m);
JacobiSVD<MatrixType> jacobi_svd(m);
VERIFY_IS_APPROX(bdc_svd.singularValues(), jacobi_svd.singularValues());
if(computationOptions & ComputeFullU) VERIFY_IS_APPROX(bdc_svd.matrixU(), jacobi_svd.matrixU());
if(computationOptions & ComputeThinU) VERIFY_IS_APPROX(bdc_svd.matrixU(), jacobi_svd.matrixU());
if(computationOptions & ComputeFullV) VERIFY_IS_APPROX(bdc_svd.matrixV(), jacobi_svd.matrixV());
if(computationOptions & ComputeThinV) VERIFY_IS_APPROX(bdc_svd.matrixV(), jacobi_svd.matrixV());
}
void test_bdcsvd()
{
CALL_SUBTEST_3(( svd_verify_assert<BDCSVD<Matrix3f> >(Matrix3f()) ));
CALL_SUBTEST_4(( svd_verify_assert<BDCSVD<Matrix4d> >(Matrix4d()) ));
CALL_SUBTEST_7(( svd_verify_assert<BDCSVD<MatrixXf> >(MatrixXf(10,12)) ));
CALL_SUBTEST_8(( svd_verify_assert<BDCSVD<MatrixXcd> >(MatrixXcd(7,5)) ));
CALL_SUBTEST_1(( svd_all_trivial_2x2(bdcsvd<Matrix2cd>) ));
CALL_SUBTEST_1(( svd_all_trivial_2x2(bdcsvd<Matrix2d>) ));
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_3(( bdcsvd<Matrix3f>() ));
CALL_SUBTEST_4(( bdcsvd<Matrix4d>() ));
CALL_SUBTEST_5(( bdcsvd<Matrix<float,3,5> >() ));
int r = internal::random<int>(1, EIGEN_TEST_MAX_SIZE/2),
c = internal::random<int>(1, EIGEN_TEST_MAX_SIZE/2);
TEST_SET_BUT_UNUSED_VARIABLE(r)
TEST_SET_BUT_UNUSED_VARIABLE(c)
CALL_SUBTEST_6(( bdcsvd(Matrix<double,Dynamic,2>(r,2)) ));
CALL_SUBTEST_7(( bdcsvd(MatrixXf(r,c)) ));
CALL_SUBTEST_7(( compare_bdc_jacobi(MatrixXf(r,c)) ));
CALL_SUBTEST_10(( bdcsvd(MatrixXd(r,c)) ));
CALL_SUBTEST_10(( compare_bdc_jacobi(MatrixXd(r,c)) ));
CALL_SUBTEST_8(( bdcsvd(MatrixXcd(r,c)) ));
CALL_SUBTEST_8(( compare_bdc_jacobi(MatrixXcd(r,c)) ));
// Test on inf/nan matrix
CALL_SUBTEST_7( (svd_inf_nan<BDCSVD<MatrixXf>, MatrixXf>()) );
CALL_SUBTEST_10( (svd_inf_nan<BDCSVD<MatrixXd>, MatrixXd>()) );
}
// test matrixbase method
CALL_SUBTEST_1(( bdcsvd_method<Matrix2cd>() ));
CALL_SUBTEST_3(( bdcsvd_method<Matrix3f>() ));
// Test problem size constructors
CALL_SUBTEST_7( BDCSVD<MatrixXf>(10,10) );
// Check that preallocation avoids subsequent mallocs
CALL_SUBTEST_9( svd_preallocate() );
CALL_SUBTEST_2( svd_underoverflow() );
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// TestApp.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Gfx/Util/RawMeshLoader.h"
#include "Gfx/Util/ShapeBuilder.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "shaders.h"
using namespace Oryol;
// derived application class
class TestApp : public App {
public:
AppState::Code OnRunning();
AppState::Code OnInit();
AppState::Code OnCleanup();
private:
glm::mat4 computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos);
GfxId renderTarget;
GfxId offscreenDrawState;
GfxId displayDrawState;
glm::mat4 view;
glm::mat4 offscreenProj;
glm::mat4 displayProj;
float32 angleX = 0.0f;
float32 angleY = 0.0f;
};
OryolMain(TestApp);
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnRunning() {
// update angles
this->angleY += 0.01f;
this->angleX += 0.02f;
// render donut to offscreen render target
Gfx::ApplyOffscreenRenderTarget(this->renderTarget);
Gfx::Clear(PixelChannel::All, glm::vec4(0.25f));
Gfx::ApplyDrawState(this->offscreenDrawState);
glm::mat4 donutMVP = this->computeMVP(this->offscreenProj, this->angleX, this->angleY, glm::vec3(0.0f, 0.0f, -3.0f));
Gfx::ApplyVariable(Shaders::RenderTarget::ModelViewProjection, donutMVP);
Gfx::Draw(0);
// render sphere to display, with offscreen render target as texture
Gfx::ApplyDefaultRenderTarget();
Gfx::Clear(PixelChannel::All, glm::vec4(0.25f), 1.0f, 0);
Gfx::ApplyDrawState(this->displayDrawState);
glm::mat4 sphereMVP = this->computeMVP(this->displayProj, -this->angleX * 0.25f, this->angleY * 0.25f, glm::vec3(0.0f, 0.0f, -1.5f));
Gfx::ApplyVariable(Shaders::Main::ModelViewProjection, sphereMVP);
Gfx::ApplyVariable(Shaders::Main::Texture, this->renderTarget);
Gfx::Draw(0);
Gfx::CommitFrame();
// continue running or quit?
return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnInit() {
// setup rendering system
auto gfxSetup = GfxSetup::WindowMSAA4(800, 600, "Oryol Test App");
gfxSetup.Loaders.Add(RawMeshLoader::Creator());
Gfx::Setup(gfxSetup);
// create an offscreen render target, we explicitly want repeat texture wrap mode
// and linear blending...
auto rtSetup = TextureSetup::RenderTarget(128, 128);
rtSetup.ColorFormat = PixelFormat::RGB8;
rtSetup.DepthFormat = PixelFormat::D16;
rtSetup.WrapU = TextureWrapMode::Repeat;
rtSetup.WrapV = TextureWrapMode::Repeat;
rtSetup.MagFilter = TextureFilterMode::Linear;
rtSetup.MinFilter = TextureFilterMode::Linear;
this->renderTarget = Gfx::CreateResource(rtSetup);
// create a donut (this will be rendered into the offscreen render target)
ShapeBuilder shapeBuilder;
shapeBuilder.Layout()
.Add(VertexAttr::Position, VertexFormat::Float3)
.Add(VertexAttr::Normal, VertexFormat::Byte4N);
shapeBuilder.Box(1.0f, 1.0f, 1.0f, 1).Build();
GfxId torus = Gfx::CreateResource(MeshSetup::FromStream(), shapeBuilder.Result());
// create a sphere mesh with normals and uv coords
shapeBuilder.Clear();
shapeBuilder.Layout()
.Add(VertexAttr::Position, VertexFormat::Float3)
.Add(VertexAttr::Normal, VertexFormat::Byte4N)
.Add(VertexAttr::TexCoord0, VertexFormat::Float2);
shapeBuilder.Sphere(0.5f, 72.0f, 40.0f).Build();
GfxId sphere = Gfx::CreateResource(MeshSetup::FromStream(), shapeBuilder.Result());
// create shaders
GfxId offScreenProg = Gfx::CreateResource(Shaders::RenderTarget::CreateSetup());
GfxId dispProg = Gfx::CreateResource(Shaders::Main::CreateSetup());
// create one draw state for offscreen rendering, and one draw state for main target rendering
auto offdsSetup = DrawStateSetup::FromMeshAndProg(torus, offScreenProg);
offdsSetup.DepthStencilState.DepthWriteEnabled = true;
offdsSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
this->offscreenDrawState = Gfx::CreateResource(offdsSetup);
auto dispdsSetup = DrawStateSetup::FromMeshAndProg(sphere, dispProg);
dispdsSetup.DepthStencilState.DepthWriteEnabled = true;
dispdsSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
this->displayDrawState = Gfx::CreateResource(dispdsSetup);
// setup static transform matrices
float32 fbWidth = Gfx::DisplayAttrs().FramebufferWidth;
float32 fbHeight = Gfx::DisplayAttrs().FramebufferHeight;
this->offscreenProj = glm::perspective(glm::radians(45.0f), 1.0f, 0.01f, 20.0f);
this->displayProj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.01f, 100.0f);
this->view = glm::mat4();
return App::OnInit();
}
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnCleanup() {
// cleanup everything
this->offscreenDrawState.Release();
this->displayDrawState.Release();
this->renderTarget.Release();
Gfx::Discard();
return App::OnCleanup();
}
//------------------------------------------------------------------------------
glm::mat4
TestApp::computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos) {
glm::mat4 modelTform = glm::translate(glm::mat4(), pos);
modelTform = glm::rotate(modelTform, rotX, glm::vec3(1.0f, 0.0f, 0.0f));
modelTform = glm::rotate(modelTform, rotY, glm::vec3(0.0f, 1.0f, 0.0f));
return proj * this->view * modelTform;
}
<commit_msg>ShapeBuilder API fixes (to be conform with MeshBuilder)<commit_after>//------------------------------------------------------------------------------
// TestApp.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Gfx/Util/RawMeshLoader.h"
#include "Gfx/Util/ShapeBuilder.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "shaders.h"
using namespace Oryol;
// derived application class
class TestApp : public App {
public:
AppState::Code OnRunning();
AppState::Code OnInit();
AppState::Code OnCleanup();
private:
glm::mat4 computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos);
GfxId renderTarget;
GfxId offscreenDrawState;
GfxId displayDrawState;
glm::mat4 view;
glm::mat4 offscreenProj;
glm::mat4 displayProj;
float32 angleX = 0.0f;
float32 angleY = 0.0f;
};
OryolMain(TestApp);
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnRunning() {
// update angles
this->angleY += 0.01f;
this->angleX += 0.02f;
// render donut to offscreen render target
Gfx::ApplyOffscreenRenderTarget(this->renderTarget);
Gfx::Clear(PixelChannel::All, glm::vec4(0.25f));
Gfx::ApplyDrawState(this->offscreenDrawState);
glm::mat4 donutMVP = this->computeMVP(this->offscreenProj, this->angleX, this->angleY, glm::vec3(0.0f, 0.0f, -3.0f));
Gfx::ApplyVariable(Shaders::RenderTarget::ModelViewProjection, donutMVP);
Gfx::Draw(0);
// render sphere to display, with offscreen render target as texture
Gfx::ApplyDefaultRenderTarget();
Gfx::Clear(PixelChannel::All, glm::vec4(0.25f), 1.0f, 0);
Gfx::ApplyDrawState(this->displayDrawState);
glm::mat4 sphereMVP = this->computeMVP(this->displayProj, -this->angleX * 0.25f, this->angleY * 0.25f, glm::vec3(0.0f, 0.0f, -1.5f));
Gfx::ApplyVariable(Shaders::Main::ModelViewProjection, sphereMVP);
Gfx::ApplyVariable(Shaders::Main::Texture, this->renderTarget);
Gfx::Draw(0);
Gfx::CommitFrame();
// continue running or quit?
return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnInit() {
// setup rendering system
auto gfxSetup = GfxSetup::WindowMSAA4(800, 600, "Oryol Test App");
gfxSetup.Loaders.Add(RawMeshLoader::Creator());
Gfx::Setup(gfxSetup);
// create an offscreen render target, we explicitly want repeat texture wrap mode
// and linear blending...
auto rtSetup = TextureSetup::RenderTarget(128, 128);
rtSetup.ColorFormat = PixelFormat::RGB8;
rtSetup.DepthFormat = PixelFormat::D16;
rtSetup.WrapU = TextureWrapMode::Repeat;
rtSetup.WrapV = TextureWrapMode::Repeat;
rtSetup.MagFilter = TextureFilterMode::Linear;
rtSetup.MinFilter = TextureFilterMode::Linear;
this->renderTarget = Gfx::CreateResource(rtSetup);
// create a donut (this will be rendered into the offscreen render target)
ShapeBuilder shapeBuilder;
shapeBuilder.Layout
.Add(VertexAttr::Position, VertexFormat::Float3)
.Add(VertexAttr::Normal, VertexFormat::Byte4N);
shapeBuilder.Box(1.0f, 1.0f, 1.0f, 1).Build();
GfxId torus = Gfx::CreateResource(MeshSetup::FromStream(), shapeBuilder.Result());
// create a sphere mesh with normals and uv coords
shapeBuilder.Clear();
shapeBuilder.Layout
.Add(VertexAttr::Position, VertexFormat::Float3)
.Add(VertexAttr::Normal, VertexFormat::Byte4N)
.Add(VertexAttr::TexCoord0, VertexFormat::Float2);
shapeBuilder.Sphere(0.5f, 72.0f, 40.0f).Build();
GfxId sphere = Gfx::CreateResource(MeshSetup::FromStream(), shapeBuilder.Result());
// create shaders
GfxId offScreenProg = Gfx::CreateResource(Shaders::RenderTarget::CreateSetup());
GfxId dispProg = Gfx::CreateResource(Shaders::Main::CreateSetup());
// create one draw state for offscreen rendering, and one draw state for main target rendering
auto offdsSetup = DrawStateSetup::FromMeshAndProg(torus, offScreenProg);
offdsSetup.DepthStencilState.DepthWriteEnabled = true;
offdsSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
this->offscreenDrawState = Gfx::CreateResource(offdsSetup);
auto dispdsSetup = DrawStateSetup::FromMeshAndProg(sphere, dispProg);
dispdsSetup.DepthStencilState.DepthWriteEnabled = true;
dispdsSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
this->displayDrawState = Gfx::CreateResource(dispdsSetup);
// setup static transform matrices
float32 fbWidth = Gfx::DisplayAttrs().FramebufferWidth;
float32 fbHeight = Gfx::DisplayAttrs().FramebufferHeight;
this->offscreenProj = glm::perspective(glm::radians(45.0f), 1.0f, 0.01f, 20.0f);
this->displayProj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.01f, 100.0f);
this->view = glm::mat4();
return App::OnInit();
}
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnCleanup() {
// cleanup everything
this->offscreenDrawState.Release();
this->displayDrawState.Release();
this->renderTarget.Release();
Gfx::Discard();
return App::OnCleanup();
}
//------------------------------------------------------------------------------
glm::mat4
TestApp::computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos) {
glm::mat4 modelTform = glm::translate(glm::mat4(), pos);
modelTform = glm::rotate(modelTform, rotX, glm::vec3(1.0f, 0.0f, 0.0f));
modelTform = glm::rotate(modelTform, rotY, glm::vec3(0.0f, 1.0f, 0.0f));
return proj * this->view * modelTform;
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// TestApp.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/Main.h"
#include "Gfx/Gfx.h"
#include "Assets/Gfx/ShapeBuilder.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "shaders.h"
using namespace Oryol;
// derived application class
class TestApp : public App {
public:
AppState::Code OnRunning();
AppState::Code OnInit();
AppState::Code OnCleanup();
private:
glm::mat4 computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos);
Id renderTarget;
DrawState offscrDrawState;
DrawState mainDrawState;
ClearState offscrClearState;
ClearState mainClearState;
OffscreenShader::VSParams offscrVSParams;
MainShader::VSParams mainVSParams;
glm::mat4 view;
glm::mat4 offscreenProj;
glm::mat4 displayProj;
float32 angleX = 0.0f;
float32 angleY = 0.0f;
};
OryolMain(TestApp);
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnRunning() {
// update animated parameters
this->angleY += 0.01f;
this->angleX += 0.02f;
this->offscrVSParams.ModelViewProjection = this->computeMVP(this->offscreenProj, this->angleX, this->angleY, glm::vec3(0.0f, 0.0f, -3.0f));
this->mainVSParams.ModelViewProjection = this->computeMVP(this->displayProj, -this->angleX * 0.25f, this->angleY * 0.25f, glm::vec3(0.0f, 0.0f, -1.5f));;
// render donut to offscreen render target
Gfx::ApplyRenderTarget(this->renderTarget, this->offscrClearState);
Gfx::ApplyDrawState(this->offscrDrawState);
Gfx::ApplyUniformBlock(this->offscrVSParams);
Gfx::Draw(0);
// render sphere to display, with offscreen render target as texture
Gfx::ApplyDefaultRenderTarget(this->mainClearState);
Gfx::ApplyDrawState(this->mainDrawState);
Gfx::ApplyUniformBlock(this->mainVSParams);
Gfx::Draw(0);
Gfx::CommitFrame();
// continue running or quit?
return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnInit() {
// setup rendering system
auto gfxSetup = GfxSetup::WindowMSAA4(800, 600, "Oryol Test App");
Gfx::Setup(gfxSetup);
// create an offscreen render target, we explicitly want repeat texture wrap mode
// and linear blending...
auto rtSetup = TextureSetup::RenderTarget(128, 128);
rtSetup.ColorFormat = PixelFormat::RGBA8;
rtSetup.DepthFormat = PixelFormat::DEPTH;
rtSetup.Sampler.WrapU = TextureWrapMode::Repeat;
rtSetup.Sampler.WrapV = TextureWrapMode::Repeat;
rtSetup.Sampler.MagFilter = TextureFilterMode::Linear;
rtSetup.Sampler.MinFilter = TextureFilterMode::Linear;
this->renderTarget = Gfx::CreateResource(rtSetup);
// create offscreen rendering resources
ShapeBuilder shapeBuilder;
shapeBuilder.Layout
.Add(VertexAttr::Position, VertexFormat::Float3)
.Add(VertexAttr::Normal, VertexFormat::Byte4N);
shapeBuilder.Box(1.0f, 1.0f, 1.0f, 1);
this->offscrDrawState.Mesh[0] = Gfx::CreateResource(shapeBuilder.Build());
Id offScreenShader = Gfx::CreateResource(OffscreenShader::Setup());
auto offPipSetup = PipelineSetup::FromLayoutAndShader(shapeBuilder.Layout, offScreenShader);
offPipSetup.DepthStencilState.DepthWriteEnabled = true;
offPipSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
offPipSetup.BlendState.ColorFormat = rtSetup.ColorFormat;
offPipSetup.BlendState.DepthFormat = rtSetup.DepthFormat;
this->offscrDrawState.Pipeline = Gfx::CreateResource(offPipSetup);
// create display rendering resources
shapeBuilder.Layout
.Clear()
.Add(VertexAttr::Position, VertexFormat::Float3)
.Add(VertexAttr::Normal, VertexFormat::Byte4N)
.Add(VertexAttr::TexCoord0, VertexFormat::Float2);
shapeBuilder.Sphere(0.5f, 72.0f, 40.0f);
this->mainDrawState.Mesh[0] = Gfx::CreateResource(shapeBuilder.Build());
Id dispShader = Gfx::CreateResource(MainShader::Setup());
auto dispPipSetup = PipelineSetup::FromLayoutAndShader(shapeBuilder.Layout, dispShader);
dispPipSetup.DepthStencilState.DepthWriteEnabled = true;
dispPipSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
dispPipSetup.RasterizerState.SampleCount = gfxSetup.SampleCount;
this->mainDrawState.Pipeline = Gfx::CreateResource(dispPipSetup);
this->mainDrawState.FSTexture[Textures::Texture] = this->renderTarget;
// setup clear states
this->offscrClearState.Color = glm::vec4(1.0f, 0.5f, 0.25f, 1.0f);
this->mainClearState.Color = glm::vec4(0.25f, 0.5f, 1.0f, 1.0f);
// setup static transform matrices
float32 fbWidth = Gfx::DisplayAttrs().FramebufferWidth;
float32 fbHeight = Gfx::DisplayAttrs().FramebufferHeight;
this->offscreenProj = glm::perspective(glm::radians(45.0f), 1.0f, 0.01f, 20.0f);
this->displayProj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.01f, 100.0f);
this->view = glm::mat4();
return App::OnInit();
}
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnCleanup() {
Gfx::Discard();
return App::OnCleanup();
}
//------------------------------------------------------------------------------
glm::mat4
TestApp::computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos) {
glm::mat4 modelTform = glm::translate(glm::mat4(), pos);
modelTform = glm::rotate(modelTform, rotX, glm::vec3(1.0f, 0.0f, 0.0f));
modelTform = glm::rotate(modelTform, rotY, glm::vec3(0.0f, 1.0f, 0.0f));
return proj * this->view * modelTform;
}
<commit_msg>Fixes for Oryol render pass changes<commit_after>//------------------------------------------------------------------------------
// TestApp.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/Main.h"
#include "Gfx/Gfx.h"
#include "Assets/Gfx/ShapeBuilder.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "shaders.h"
using namespace Oryol;
// derived application class
class TestApp : public App {
public:
AppState::Code OnRunning();
AppState::Code OnInit();
AppState::Code OnCleanup();
private:
glm::mat4 computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos);
Id renderPass;
DrawState offscrDrawState;
DrawState mainDrawState;
OffscreenShader::VSParams offscrVSParams;
MainShader::VSParams mainVSParams;
glm::mat4 view;
glm::mat4 offscreenProj;
glm::mat4 displayProj;
float32 angleX = 0.0f;
float32 angleY = 0.0f;
};
OryolMain(TestApp);
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnRunning() {
// update animated parameters
this->angleY += 0.01f;
this->angleX += 0.02f;
this->offscrVSParams.ModelViewProjection = this->computeMVP(this->offscreenProj, this->angleX, this->angleY, glm::vec3(0.0f, 0.0f, -3.0f));
this->mainVSParams.ModelViewProjection = this->computeMVP(this->displayProj, -this->angleX * 0.25f, this->angleY * 0.25f, glm::vec3(0.0f, 0.0f, -1.5f));;
// render donut to offscreen render target
Gfx::BeginPass(this->renderPass);
Gfx::ApplyDrawState(this->offscrDrawState);
Gfx::ApplyUniformBlock(this->offscrVSParams);
Gfx::Draw(0);
Gfx::EndPass();
// render sphere to display, with offscreen render target as texture
Gfx::BeginPass();
Gfx::ApplyDrawState(this->mainDrawState);
Gfx::ApplyUniformBlock(this->mainVSParams);
Gfx::Draw(0);
Gfx::EndPass();
Gfx::CommitFrame();
// continue running or quit?
return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnInit() {
// setup rendering system
auto gfxSetup = GfxSetup::WindowMSAA4(800, 600, "Oryol Test App");
gfxSetup.DefaultPassAction = PassAction::Clear(glm::vec4(0.25f, 0.45f, 0.65f, 1.0f));
Gfx::Setup(gfxSetup);
// create an offscreen render target, we explicitly want repeat texture wrap mode
// and linear blending...
auto rtSetup = TextureSetup::RenderTarget2D(128, 128, PixelFormat::RGBA8, PixelFormat::DEPTH);
rtSetup.Sampler.WrapU = TextureWrapMode::Repeat;
rtSetup.Sampler.WrapV = TextureWrapMode::Repeat;
rtSetup.Sampler.MagFilter = TextureFilterMode::Linear;
rtSetup.Sampler.MinFilter = TextureFilterMode::Linear;
Id rtTex = Gfx::CreateResource(rtSetup);
auto passSetup = PassSetup::From(rtTex, rtTex);
passSetup.DefaultAction = PassAction::Clear(glm::vec4(0.25f, 0.65f, 0.45f, 1.0f));
this->renderPass = Gfx::CreateResource(passSetup);
// create offscreen rendering resources
ShapeBuilder shapeBuilder;
shapeBuilder.Layout
.Add(VertexAttr::Position, VertexFormat::Float3)
.Add(VertexAttr::Normal, VertexFormat::Byte4N);
shapeBuilder.Box(1.0f, 1.0f, 1.0f, 1);
this->offscrDrawState.Mesh[0] = Gfx::CreateResource(shapeBuilder.Build());
Id offScreenShader = Gfx::CreateResource(OffscreenShader::Setup());
auto offPipSetup = PipelineSetup::FromLayoutAndShader(shapeBuilder.Layout, offScreenShader);
offPipSetup.DepthStencilState.DepthWriteEnabled = true;
offPipSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
offPipSetup.BlendState.ColorFormat = rtSetup.ColorFormat;
offPipSetup.BlendState.DepthFormat = rtSetup.DepthFormat;
this->offscrDrawState.Pipeline = Gfx::CreateResource(offPipSetup);
// create display rendering resources
shapeBuilder.Layout
.Clear()
.Add(VertexAttr::Position, VertexFormat::Float3)
.Add(VertexAttr::Normal, VertexFormat::Byte4N)
.Add(VertexAttr::TexCoord0, VertexFormat::Float2);
shapeBuilder.Sphere(0.5f, 72.0f, 40.0f);
this->mainDrawState.Mesh[0] = Gfx::CreateResource(shapeBuilder.Build());
Id dispShader = Gfx::CreateResource(MainShader::Setup());
auto dispPipSetup = PipelineSetup::FromLayoutAndShader(shapeBuilder.Layout, dispShader);
dispPipSetup.DepthStencilState.DepthWriteEnabled = true;
dispPipSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual;
dispPipSetup.RasterizerState.SampleCount = gfxSetup.SampleCount;
this->mainDrawState.Pipeline = Gfx::CreateResource(dispPipSetup);
this->mainDrawState.FSTexture[Textures::Texture] = rtTex;
// setup static transform matrices
float32 fbWidth = Gfx::DisplayAttrs().FramebufferWidth;
float32 fbHeight = Gfx::DisplayAttrs().FramebufferHeight;
this->offscreenProj = glm::perspective(glm::radians(45.0f), 1.0f, 0.01f, 20.0f);
this->displayProj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.01f, 100.0f);
this->view = glm::mat4();
return App::OnInit();
}
//------------------------------------------------------------------------------
AppState::Code
TestApp::OnCleanup() {
Gfx::Discard();
return App::OnCleanup();
}
//------------------------------------------------------------------------------
glm::mat4
TestApp::computeMVP(const glm::mat4& proj, float32 rotX, float32 rotY, const glm::vec3& pos) {
glm::mat4 modelTform = glm::translate(glm::mat4(), pos);
modelTform = glm::rotate(modelTform, rotX, glm::vec3(1.0f, 0.0f, 0.0f));
modelTform = glm::rotate(modelTform, rotY, glm::vec3(0.0f, 1.0f, 0.0f));
return proj * this->view * modelTform;
}
<|endoftext|>
|
<commit_before>/***********************************************************************
test/string.cpp - Tests the behavior of mysqlpp::String, particularly
its data conversion methods.
Copyright (c) 2007-2008 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the
CREDITS file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include <mysql++.h>
#include <iostream>
// Does an equality comparison on the value, forcing the string to
// convert itself to T on the way. Note that we do this test in terms
// of greater and less than to avoid pedantic GCC warnings for the
// floating point type tests.
template <typename T>
static bool
test_equality(const mysqlpp::String& s, T value)
{
T converted = s.conv(value);
if ((value < converted) || (value > converted)) {
std::cerr << "Type conversion to " << typeid(T).name() <<
" failed: \"" << s << "\" != \"" << value << "\"." <<
std::endl;
return false;
}
else {
return true;
}
}
// Check that we can convert strings with decimals in them to native
// floating-point values, regardless of locale.
static bool
test_float_conversion()
{
// This stuff should just work
if (!test_equality(mysqlpp::String("123.00"), 123)) return false;
if (!test_equality(mysqlpp::String("123."), 123)) return false;
// This is trickier: MySQL ignores the system locale when it comes
// to decimal separators, always using '.', so ensure the conversion
// stuff in MySQL++ does the right thing regardless. Test against
// this system's current locale, an arbitrary European one where ','
// is the decimal separator, and the "C" locale where it's '.'.
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
std::locale old_locale = std::locale::global(std::locale::classic());
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
std::locale::global(std::locale("de_DE"));
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
std::locale::global(old_locale);
// Check that we choke on silly float-like values
try {
if (test_equality(mysqlpp::String("621.20.0"), 621.2)) {
std::cerr << "Quasi-FP with two decimal points "
"converting without error!" << std::endl;
}
return false;
}
catch (const mysqlpp::BadConversion&) {
return true;
}
}
// Tries to convert the given string to an int. Returns false if we got
// a BadConversion exception and didn't expect it, or didn't get one we
// expected. Returns false on all other exceptions regardless.
static bool
test_int_conversion(const mysqlpp::String& s, bool throw_expected)
{
// Try the conversion
bool conv_threw = false;
try {
int converted = s;
}
catch (const mysqlpp::BadConversion&) {
conv_threw = true;
}
catch (const std::exception& e) {
std::cerr << "Unexpected " << typeid(e).name() <<
" exception in test_int_conv: " << e.what() << std::endl;
return false;
}
catch (...) {
std::cerr << "Like, totally bogus exception in test_int_conv, "
"man!" << std::endl;
return false;
}
// Did it do what we expected?
if (throw_expected == conv_threw) {
return true;
}
else {
std::cerr << "Conversion of \"" << s << "\" to int " <<
(conv_threw ? "did not " : "") << "throw; did " <<
(throw_expected ? "not " : "") << "expect it to." <<
std::endl;
return false;
}
}
// Ensures that the program's locale doesn't affect our floating-point
// conversions. ('.' vs. ',' stuff.)
static bool
test_locale()
{
return true;
}
// Ensures numeric conversions of many different types get handled
// correctly.
static bool
test_numeric(const mysqlpp::String& s, int value)
{
return test_equality(s, static_cast<signed char>(value)) &&
test_equality(s, static_cast<unsigned char>(value)) &&
test_equality(s, static_cast<signed short>(value)) &&
test_equality(s, static_cast<unsigned short>(value)) &&
test_equality(s, static_cast<signed int>(value)) &&
test_equality(s, static_cast<unsigned int>(value)) &&
test_equality(s, static_cast<signed long>(value)) &&
test_equality(s, static_cast<unsigned long>(value)) &&
#if !defined(NO_LONG_LONGS)
test_equality(s, static_cast<mysqlpp::longlong>(value)) &&
test_equality(s, static_cast<mysqlpp::ulonglong>(value)) &&
#endif
test_equality(s, static_cast<float>(value)) &&
test_equality(s, static_cast<double>(value));
}
static bool
test_quote_q(const mysqlpp::String& s, bool expected)
{
if (s.quote_q() == expected) {
return true;
}
else {
std::cerr << s.type().name() << " should" <<
(expected ? "" : " NOT") << " be quoted." << std::endl;
return false;
}
}
int
main(int, char* argv[])
{
try {
int failures = 0;
mysqlpp::String empty;
mysqlpp::String zero("0");
mysqlpp::String nonzero("42");
failures += test_equality(empty, mysqlpp::Date()) == false;
failures += test_equality(empty,
mysqlpp::DateTime(0, 0, 0, 0, 0, 0)) == false;
failures += test_equality(empty, mysqlpp::Time()) == false;
failures += test_equality(empty, false) == false;
failures += test_equality(nonzero, true) == false;
failures += test_numeric(empty, 0) == false;
failures += test_numeric(zero, 0) == false;
failures += test_numeric(nonzero, 42) == false;
failures += test_quote_q(empty, true) == false;
failures += test_quote_q(mysqlpp::String("1", typeid(int)),
false) == false;
failures += test_locale() == false;
failures += test_float_conversion() == false;
failures += test_float_conversion() == false;
return failures;
}
catch (mysqlpp::Exception& e) {
std::cerr << "Unexpected MySQL++ exception caught in " <<
argv[0] << ": " << e.what() << std::endl;
return 1;
}
catch (std::exception& e) {
std::cerr << "Unexpected C++ exception caught in " <<
argv[0] << ": " << e.what() << std::endl;
return 1;
}
}
<commit_msg>Squished a pedantic GCC warning<commit_after>/***********************************************************************
test/string.cpp - Tests the behavior of mysqlpp::String, particularly
its data conversion methods.
Copyright (c) 2007-2008 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the
CREDITS file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include <mysql++.h>
#include <iostream>
// Does an equality comparison on the value, forcing the string to
// convert itself to T on the way. Note that we do this test in terms
// of greater and less than to avoid pedantic GCC warnings for the
// floating point type tests.
template <typename T>
static bool
test_equality(const mysqlpp::String& s, T value)
{
T converted = s.conv(value);
if ((value < converted) || (value > converted)) {
std::cerr << "Type conversion to " << typeid(T).name() <<
" failed: \"" << s << "\" != \"" << value << "\"." <<
std::endl;
return false;
}
else {
return true;
}
}
// Check that we can convert strings with decimals in them to native
// floating-point values, regardless of locale.
static bool
test_float_conversion()
{
// This stuff should just work
if (!test_equality(mysqlpp::String("123.00"), 123)) return false;
if (!test_equality(mysqlpp::String("123."), 123)) return false;
// This is trickier: MySQL ignores the system locale when it comes
// to decimal separators, always using '.', so ensure the conversion
// stuff in MySQL++ does the right thing regardless. Test against
// this system's current locale, an arbitrary European one where ','
// is the decimal separator, and the "C" locale where it's '.'.
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
std::locale old_locale = std::locale::global(std::locale::classic());
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
std::locale::global(std::locale("de_DE"));
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
std::locale::global(old_locale);
// Check that we choke on silly float-like values
try {
if (test_equality(mysqlpp::String("621.20.0"), 621.2)) {
std::cerr << "Quasi-FP with two decimal points "
"converting without error!" << std::endl;
}
return false;
}
catch (const mysqlpp::BadConversion&) {
return true;
}
}
// Tries to convert the given string to an int. Returns false if we got
// a BadConversion exception and didn't expect it, or didn't get one we
// expected. Returns false on all other exceptions regardless.
static bool
test_int_conversion(const mysqlpp::String& s, bool throw_expected)
{
// Try the conversion
bool conv_threw = false;
try {
int converted = s;
(void)converted; // pedantic warning squisher
}
catch (const mysqlpp::BadConversion&) {
conv_threw = true;
}
catch (const std::exception& e) {
std::cerr << "Unexpected " << typeid(e).name() <<
" exception in test_int_conv: " << e.what() << std::endl;
return false;
}
catch (...) {
std::cerr << "Like, totally bogus exception in test_int_conv, "
"man!" << std::endl;
return false;
}
// Did it do what we expected?
if (throw_expected == conv_threw) {
return true;
}
else {
std::cerr << "Conversion of \"" << s << "\" to int " <<
(conv_threw ? "did not " : "") << "throw; did " <<
(throw_expected ? "not " : "") << "expect it to." <<
std::endl;
return false;
}
}
// Ensures that the program's locale doesn't affect our floating-point
// conversions. ('.' vs. ',' stuff.)
static bool
test_locale()
{
return true;
}
// Ensures numeric conversions of many different types get handled
// correctly.
static bool
test_numeric(const mysqlpp::String& s, int value)
{
return test_equality(s, static_cast<signed char>(value)) &&
test_equality(s, static_cast<unsigned char>(value)) &&
test_equality(s, static_cast<signed short>(value)) &&
test_equality(s, static_cast<unsigned short>(value)) &&
test_equality(s, static_cast<signed int>(value)) &&
test_equality(s, static_cast<unsigned int>(value)) &&
test_equality(s, static_cast<signed long>(value)) &&
test_equality(s, static_cast<unsigned long>(value)) &&
#if !defined(NO_LONG_LONGS)
test_equality(s, static_cast<mysqlpp::longlong>(value)) &&
test_equality(s, static_cast<mysqlpp::ulonglong>(value)) &&
#endif
test_equality(s, static_cast<float>(value)) &&
test_equality(s, static_cast<double>(value));
}
static bool
test_quote_q(const mysqlpp::String& s, bool expected)
{
if (s.quote_q() == expected) {
return true;
}
else {
std::cerr << s.type().name() << " should" <<
(expected ? "" : " NOT") << " be quoted." << std::endl;
return false;
}
}
int
main(int, char* argv[])
{
try {
int failures = 0;
mysqlpp::String empty;
mysqlpp::String zero("0");
mysqlpp::String nonzero("42");
failures += test_equality(empty, mysqlpp::Date()) == false;
failures += test_equality(empty,
mysqlpp::DateTime(0, 0, 0, 0, 0, 0)) == false;
failures += test_equality(empty, mysqlpp::Time()) == false;
failures += test_equality(empty, false) == false;
failures += test_equality(nonzero, true) == false;
failures += test_numeric(empty, 0) == false;
failures += test_numeric(zero, 0) == false;
failures += test_numeric(nonzero, 42) == false;
failures += test_quote_q(empty, true) == false;
failures += test_quote_q(mysqlpp::String("1", typeid(int)),
false) == false;
failures += test_locale() == false;
failures += test_float_conversion() == false;
failures += test_float_conversion() == false;
return failures;
}
catch (mysqlpp::Exception& e) {
std::cerr << "Unexpected MySQL++ exception caught in " <<
argv[0] << ": " << e.what() << std::endl;
return 1;
}
catch (std::exception& e) {
std::cerr << "Unexpected C++ exception caught in " <<
argv[0] << ": " << e.what() << std::endl;
return 1;
}
}
<|endoftext|>
|
<commit_before>/***********************************************************************
test/string.cpp - Tests the behavior of mysqlpp::String, particularly
its data conversion methods.
Copyright (c) 2007-2008 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the
CREDITS file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include <mysql++.h>
#include <iostream>
// Does an equality comparison on the value, forcing the string to
// convert itself to T on the way. Note that we do this test in terms
// of greater and less than to avoid pedantic GCC warnings for the
// floating point type tests.
template <typename T>
static bool
test_equality(const mysqlpp::String& s, T value)
{
T converted = s.conv(value);
if ((value < converted) || (value > converted)) {
std::cerr << "Type conversion to " << typeid(T).name() <<
" failed: \"" << s << "\" != \"" << value << "\"." <<
std::endl;
return false;
}
else {
return true;
}
}
// Check that we can convert strings with decimals in them to native
// floating-point values, regardless of locale.
static bool
test_float_conversion()
{
// This stuff should just work
if (!test_equality(mysqlpp::String("123.00"), 123)) return false;
if (!test_equality(mysqlpp::String("123."), 123)) return false;
// This is trickier: MySQL ignores the system locale when it comes
// to decimal separators, always using '.', so ensure the conversion
// stuff in MySQL++ does the right thing regardless. Test against
// this system's current locale, an arbitrary European one where ','
// is the decimal separator, and the "C" locale where it's '.'.
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
std::locale old_locale = std::locale::global(std::locale::classic());
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
try {
std::locale::global(std::locale("de_DE"));
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
}
catch (std::runtime_error& e) {
std::cerr << "WARNING: skipping European locale string "
"conversion test:" << std::endl;
std::cerr << "\t" << e.what() << std::endl;
}
std::locale::global(old_locale);
// Check that we choke on silly float-like values
try {
if (test_equality(mysqlpp::String("621.20.0"), 621.2)) {
std::cerr << "Quasi-FP with two decimal points "
"converting without error!" << std::endl;
}
return false;
}
catch (const mysqlpp::BadConversion&) {
return true;
}
}
// Tries to convert the given string to an int. Returns false if we got
// a BadConversion exception and didn't expect it, or didn't get one we
// expected. Returns false on all other exceptions regardless.
static bool
test_int_conversion(const mysqlpp::String& s, bool throw_expected)
{
// Try the conversion
bool conv_threw = false;
try {
int converted = s;
(void)converted; // pedantic warning squisher
}
catch (const mysqlpp::BadConversion&) {
conv_threw = true;
}
catch (const std::exception& e) {
std::cerr << "Unexpected " << typeid(e).name() <<
" exception in test_int_conv: " << e.what() << std::endl;
return false;
}
catch (...) {
std::cerr << "Like, totally bogus exception in test_int_conv, "
"man!" << std::endl;
return false;
}
// Did it do what we expected?
if (throw_expected == conv_threw) {
return true;
}
else {
std::cerr << "Conversion of \"" << s << "\" to int " <<
(conv_threw ? "did not throw" : "threw") << "; " <<
(throw_expected ? "did not expect" : "expected") <<
" it to." << std::endl;
return false;
}
}
// Checks that String's null comparison methods work right
static bool
test_null()
{
mysqlpp::String not_null("", mysqlpp::mysql_type_info::string_type, false);
mysqlpp::String is_null("", mysqlpp::mysql_type_info::string_type, true);
if (not_null.is_null() == true) {
std::cerr << "not_null.is_null() == true!" << std::endl;
return false;
}
else if (not_null == mysqlpp::null) {
std::cerr << "not_null == mysqlpp:null!" << std::endl;
return false;
}
else if (is_null.is_null() == false) {
std::cerr << "is_null.is_null() == false!" << std::endl;
return false;
}
else if (is_null != mysqlpp::null) {
std::cerr << "is_null != mysqlpp:null!" << std::endl;
return false;
}
else {
return true;
}
}
// Ensures numeric conversions of many different types get handled
// correctly.
static bool
test_numeric(const mysqlpp::String& s, int value)
{
return test_equality(s, static_cast<signed char>(value)) &&
test_equality(s, static_cast<unsigned char>(value)) &&
test_equality(s, static_cast<signed short>(value)) &&
test_equality(s, static_cast<unsigned short>(value)) &&
test_equality(s, static_cast<signed int>(value)) &&
test_equality(s, static_cast<unsigned int>(value)) &&
test_equality(s, static_cast<signed long>(value)) &&
test_equality(s, static_cast<unsigned long>(value)) &&
#if !defined(NO_LONG_LONGS)
test_equality(s, static_cast<mysqlpp::longlong>(value)) &&
test_equality(s, static_cast<mysqlpp::ulonglong>(value)) &&
#endif
test_equality(s, static_cast<float>(value)) &&
test_equality(s, static_cast<double>(value));
}
static bool
test_quote_q(const mysqlpp::String& s, bool expected)
{
if (s.quote_q() == expected) {
return true;
}
else {
std::cerr << s.type().name() << " should" <<
(expected ? "" : " NOT") << " be quoted." << std::endl;
return false;
}
}
// Similar to test_equality, but only works with std::string
// comparisons, which uses String::operator ==()
static bool
test_string_equality(const mysqlpp::String& s, std::string value)
{
if (s == value) {
if (s != value) {
std::cerr << "String(\"" << s << "\") != std::string(\"" <<
value << "\"), case 2!" << std::endl;
return false;
}
else {
return true;
}
}
else {
std::cerr << "String(\"" << s << "\") != std::string(\"" <<
value << "\"), case 1!" << std::endl;
return false;
}
}
int
main(int, char* argv[])
{
try {
int failures = 0;
mysqlpp::String empty;
mysqlpp::String zero("0");
mysqlpp::String nonzero("42");
mysqlpp::String intable1("42.");
mysqlpp::String intable2("42.0");
mysqlpp::String nonint("42.1");
failures += test_equality(empty, mysqlpp::Date()) == false;
failures += test_equality(empty,
mysqlpp::DateTime(0, 0, 0, 0, 0, 0)) == false;
failures += test_equality(empty, mysqlpp::Time()) == false;
failures += test_equality(empty, false) == false;
failures += test_equality(nonzero, true) == false;
failures += test_numeric(empty, 0) == false;
failures += test_numeric(zero, 0) == false;
failures += test_numeric(nonzero, 42) == false;
failures += test_quote_q(empty, true) == false;
failures += test_quote_q(mysqlpp::String("1", typeid(int)),
false) == false;
failures += test_float_conversion() == false;
failures += test_float_conversion() == false;
failures += test_int_conversion(empty, false) == false;
failures += test_int_conversion(zero, false) == false;
failures += test_int_conversion(nonzero, false) == false;
failures += test_int_conversion(intable1, false) == false;
failures += test_int_conversion(intable2, false) == false;
failures += test_int_conversion(nonint, true) == false;
failures += test_null() == false;
failures += test_string_equality(empty, "") == false;
failures += test_string_equality(zero, "0") == false;
return failures;
}
catch (mysqlpp::Exception& e) {
std::cerr << "Unexpected MySQL++ exception caught in " <<
argv[0] << ": " << e.what() << std::endl;
return 1;
}
catch (std::exception& e) {
std::cerr << "Unexpected C++ exception caught in " <<
argv[0] << ": " << e.what() << std::endl;
return 1;
}
}
<commit_msg>Added several more test cases for string equality<commit_after>/***********************************************************************
test/string.cpp - Tests the behavior of mysqlpp::String, particularly
its data conversion methods.
Copyright (c) 2007-2008 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the
CREDITS file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include <mysql++.h>
#include <iostream>
// Does an equality comparison on the value, forcing the string to
// convert itself to T on the way. Note that we do this test in terms
// of greater and less than to avoid pedantic GCC warnings for the
// floating point type tests.
template <typename T>
static bool
test_equality(const mysqlpp::String& s, T value)
{
T converted = s.conv(value);
if ((value < converted) || (value > converted)) {
std::cerr << "Type conversion to " << typeid(T).name() <<
" failed: \"" << s << "\" != \"" << value << "\"." <<
std::endl;
return false;
}
else {
return true;
}
}
// Check that we can convert strings with decimals in them to native
// floating-point values, regardless of locale.
static bool
test_float_conversion()
{
// This stuff should just work
if (!test_equality(mysqlpp::String("123.00"), 123)) return false;
if (!test_equality(mysqlpp::String("123."), 123)) return false;
// This is trickier: MySQL ignores the system locale when it comes
// to decimal separators, always using '.', so ensure the conversion
// stuff in MySQL++ does the right thing regardless. Test against
// this system's current locale, an arbitrary European one where ','
// is the decimal separator, and the "C" locale where it's '.'.
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
std::locale old_locale = std::locale::global(std::locale::classic());
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
try {
std::locale::global(std::locale("de_DE"));
if (!test_equality(mysqlpp::String("621.200"), 621.2)) return false;
}
catch (std::runtime_error& e) {
std::cerr << "WARNING: skipping European locale string "
"conversion test:" << std::endl;
std::cerr << "\t" << e.what() << std::endl;
}
std::locale::global(old_locale);
// Check that we choke on silly float-like values
try {
if (test_equality(mysqlpp::String("621.20.0"), 621.2)) {
std::cerr << "Quasi-FP with two decimal points "
"converting without error!" << std::endl;
}
return false;
}
catch (const mysqlpp::BadConversion&) {
return true;
}
}
// Tries to convert the given string to an int. Returns false if we got
// a BadConversion exception and didn't expect it, or didn't get one we
// expected. Returns false on all other exceptions regardless.
static bool
test_int_conversion(const mysqlpp::String& s, bool throw_expected)
{
// Try the conversion
bool conv_threw = false;
try {
int converted = s;
(void)converted; // pedantic warning squisher
}
catch (const mysqlpp::BadConversion&) {
conv_threw = true;
}
catch (const std::exception& e) {
std::cerr << "Unexpected " << typeid(e).name() <<
" exception in test_int_conv: " << e.what() << std::endl;
return false;
}
catch (...) {
std::cerr << "Like, totally bogus exception in test_int_conv, "
"man!" << std::endl;
return false;
}
// Did it do what we expected?
if (throw_expected == conv_threw) {
return true;
}
else {
std::cerr << "Conversion of \"" << s << "\" to int " <<
(conv_threw ? "did not throw" : "threw") << "; " <<
(throw_expected ? "did not expect" : "expected") <<
" it to." << std::endl;
return false;
}
}
// Checks that String's null comparison methods work right
static bool
test_null()
{
mysqlpp::String not_null("", mysqlpp::mysql_type_info::string_type, false);
mysqlpp::String is_null("", mysqlpp::mysql_type_info::string_type, true);
if (not_null.is_null() == true) {
std::cerr << "not_null.is_null() == true!" << std::endl;
return false;
}
else if (not_null == mysqlpp::null) {
std::cerr << "not_null == mysqlpp:null!" << std::endl;
return false;
}
else if (is_null.is_null() == false) {
std::cerr << "is_null.is_null() == false!" << std::endl;
return false;
}
else if (is_null != mysqlpp::null) {
std::cerr << "is_null != mysqlpp:null!" << std::endl;
return false;
}
else {
return true;
}
}
// Ensures numeric conversions of many different types get handled
// correctly.
static bool
test_numeric(const mysqlpp::String& s, int value)
{
return test_equality(s, static_cast<signed char>(value)) &&
test_equality(s, static_cast<unsigned char>(value)) &&
test_equality(s, static_cast<signed short>(value)) &&
test_equality(s, static_cast<unsigned short>(value)) &&
test_equality(s, static_cast<signed int>(value)) &&
test_equality(s, static_cast<unsigned int>(value)) &&
test_equality(s, static_cast<signed long>(value)) &&
test_equality(s, static_cast<unsigned long>(value)) &&
#if !defined(NO_LONG_LONGS)
test_equality(s, static_cast<mysqlpp::longlong>(value)) &&
test_equality(s, static_cast<mysqlpp::ulonglong>(value)) &&
#endif
test_equality(s, static_cast<float>(value)) &&
test_equality(s, static_cast<double>(value));
}
static bool
test_quote_q(const mysqlpp::String& s, bool expected)
{
if (s.quote_q() == expected) {
return true;
}
else {
std::cerr << s.type().name() << " should" <<
(expected ? "" : " NOT") << " be quoted." << std::endl;
return false;
}
}
// Similar to test_equality, but only works with std::string
// comparisons, which uses String::operator ==()
static bool
test_string_equality(const mysqlpp::String& s, std::string value)
{
if (s == value) {
if (s != value) {
std::cerr << "String(\"" << s << "\") != std::string(\"" <<
value << "\"), case 2!" << std::endl;
return false;
}
else {
return true;
}
}
else {
std::cerr << "String(\"" << s << "\") != std::string(\"" <<
value << "\"), case 1!" << std::endl;
return false;
}
}
// Same as above, but for two String objects
static bool
test_string_equality(const mysqlpp::String& s1,
const mysqlpp::String s2)
{
if (s1 == s2) {
return true;
}
else {
std::cerr << "String(\"" << s1 << "\") != String(\"" <<
s2 << "\"), but should be equal!" << std::endl;
return false;
}
}
// Inverse of above.
static bool
test_string_inequality(const mysqlpp::String& s1,
const mysqlpp::String& s2)
{
if (s1 != s2) {
return true;
}
else {
std::cerr << "String(\"" << s1 << "\") == String(\"" <<
s2 << "\") but shouldn't be!" << std::endl;
return false;
}
}
int
main(int, char* argv[])
{
try {
int failures = 0;
mysqlpp::String definit;
mysqlpp::String empty("");
mysqlpp::String zero("0");
mysqlpp::String nonzero("42");
mysqlpp::String intable1("42.");
mysqlpp::String intable2("42.0");
mysqlpp::String nonint("42.1");
failures += test_equality(definit, mysqlpp::Date()) == false;
failures += test_equality(definit,
mysqlpp::DateTime(0, 0, 0, 0, 0, 0)) == false;
failures += test_equality(definit, mysqlpp::Time()) == false;
failures += test_equality(definit, false) == false;
failures += test_equality(nonzero, true) == false;
failures += test_numeric(definit, 0) == false;
failures += test_numeric(zero, 0) == false;
failures += test_numeric(nonzero, 42) == false;
failures += test_quote_q(definit, true) == false;
failures += test_quote_q(mysqlpp::String("1", typeid(int)),
false) == false;
failures += test_float_conversion() == false;
failures += test_float_conversion() == false;
failures += test_int_conversion(definit, false) == false;
failures += test_int_conversion(zero, false) == false;
failures += test_int_conversion(nonzero, false) == false;
failures += test_int_conversion(intable1, false) == false;
failures += test_int_conversion(intable2, false) == false;
failures += test_int_conversion(nonint, true) == false;
failures += test_null() == false;
failures += test_string_equality(definit, empty) == false;
failures += test_string_equality(empty, definit) == false;
failures += test_string_equality(definit, "") == false;
failures += test_string_equality(zero, "0") == false;
failures += test_string_inequality(definit, zero) == false;
failures += test_string_inequality(zero, definit) == false;
return failures;
}
catch (mysqlpp::Exception& e) {
std::cerr << "Unexpected MySQL++ exception caught in " <<
argv[0] << ": " << e.what() << std::endl;
return 1;
}
catch (std::exception& e) {
std::cerr << "Unexpected C++ exception caught in " <<
argv[0] << ": " << e.what() << std::endl;
return 1;
}
}
<|endoftext|>
|
<commit_before>#include <common/defaults.h>
#include <common/list.h>
#include <common/map.h>
#include <common/log.h>
#include <common/string.h>
#include <gui/gui.h>
#include <gdb/gdb.h>
#include <gdb/result.h>
#include <gdb/memory.h>
#include <gdb/variable.h>
#include <user_cmd/cmd.h>
#include <user_cmd/subcmd.hash.h>
#include <user_cmd/pertypes.h>
#include <user_cmd/per.tab.h>
#include <user_cmd/per.lex.h>
#include <map>
#include <string>
using namespace std;
/* macros */
#define CTOI(c) (unsigned int)((c) - ((c) >= 'a' ? 87 : 48))
#define ALIGN(val, base) ((val) & (~(base - 1)))
/* static variables */
static char* per_file = 0;
static per_range_t* range_lst = 0;
static map<unsigned int, per_range_t*> line_map;
static map<string, per_register_t*> reg_map;
/* global functions */
int cmd_per_exec(int argc, char** argv){
int r;
const struct user_subcmd_t* scmd;
FILE* fp;
per_range_t* range;
per_register_t* reg;
per_bits_t* bits;
map<unsigned int, per_range_t*>::iterator it_range;
map<string, per_register_t*>::iterator it_reg;
if(argc < 2){
USER("invalid number of arguments to command \"%s\"\n", argv[0]);
cmd_per_help(1, argv);
return 0;
}
scmd = user_subcmd::lookup(argv[1], strlen(argv[1]));
if((scmd == 0 && argc < 2) || (scmd != 0 && ((scmd->id == FOLD && argc < 3) || ((scmd->id == SET || scmd->id == COMPLETE || scmd->id == EXPORT) && argc < 4)))){
USER("invalid number of arguments to command \"%s\"\n", argv[0]);
cmd_per_help(2, argv);
return 0;
}
if(scmd == 0){
/* de-initialise */
cmd_per_cleanup();
/* parser peripheral file */
fp = fopen(argv[1], "r");
if(fp == 0){
USER("cannot open file \"%s\"\n", argv[1]);
return -1;
}
r = perparse(fp, &range_lst);
perlex_destroy();
fclose(fp);
if(r != 0){
USER("error parsing peripheral file \"%s\"\n", argv[1]);
return -1;
}
/* initialise memory segments */
list_for_each(range_lst, range){
// read respective memory
range->mem = gdb_memory_t::acquire(range->base, range->size);
if(range->mem == 0){
USER("unable to create memory segment for range \"%s\" (%p, %u)\n", range->name, range->base, range->size);
cmd_per_cleanup();
cmd_per_update();
return -1;
}
list_for_each(range->regs, reg){
if(reg->name)
strdeescape(reg->name);
if(reg->nbytes == 0)
continue;
// check integrity of register to range
if(reg->offset + reg->nbytes > range->size){
USER("error: offset/size of register \"%s\" exceeds size of range \"%s\"\n", reg->name, range->name);
cmd_per_cleanup();
cmd_per_update();
return -1;
}
// check integrity of bits to register
list_for_each(reg->bits, bits){
if(bits->idx + bits->nbits > reg->nbytes * 8){
USER("error: index/size of bits \"%s\" exceeds size of register \"%s\"\n", bits->name, reg->name);
cmd_per_cleanup();
cmd_per_update();
return -1;
}
}
// update list of registers
reg->parent = range;
reg_map[reg->name] = reg;
}
USER("add memory segment for range \"%s\" (%p, %u)\n", range->name, range->base, range->size);
}
delete [] per_file;
per_file = stralloc(argv[1], strlen(argv[1]));
cmd_per_update();
}
else{
switch(scmd->id){
case SET:
reg = MAP_LOOKUP(reg_map, argv[2]);
if(reg == 0){
USER("unknown register name \"%s\"\n", argv[2]);
return 0;
}
if(gdb_memory_t::set((void*)((unsigned long long)reg->parent->base + reg->offset), argv[3], reg->nbytes) != 0)
return -1;
gdb->memory_update();
break;
case FOLD:
range = MAP_LOOKUP(line_map, atoi(argv[2]));
if(range == 0){
USER("no peripheral segment at line %s\n", argv[2]);
return 0;
}
range->expanded = range->expanded ? false : true;
cmd_per_update();
break;
case COMPLETE:
fp = fopen(argv[2], "w");
if(fp == 0)
return -1;
for(it_range=line_map.begin(); it_range!=line_map.end(); it_range++)
fprintf(fp, "%d\\n", it_range->first);
fprintf(fp, "<regs>");
for(it_reg=reg_map.begin(); it_reg!=reg_map.end(); it_reg++)
fprintf(fp, "%s\\n", it_reg->second->name);
fclose(fp);
/* signal data availability */
fp = fopen(argv[3], "w");
if(fp == 0)
return -1;
fprintf(fp, "1\n");
fclose(fp);
break;
case EXPORT:
fp = fopen(argv[2], "w");
if(fp == 0)
return 0;
if(per_file) fprintf(fp, "Per %s\n\n", per_file);
fclose(fp);
USER("export peripheral commands to \"%s\"\n", argv[2]);
/* signal data availability */
fp = fopen(argv[3], "w");
if(fp == 0)
return -1;
fprintf(fp, "1\n");
fclose(fp);
break;
case VIEW:
cmd_per_update();
break;
default:
USER("unhandled sub command \"%s\" to \"%s\"\n", argv[1], argv[0]);
};
}
return 0;
}
void cmd_per_cleanup(){
per_range_t* range;
delete [] per_file;
per_file = 0;
reg_map.clear();
line_map.clear();
list_for_each(range_lst, range){
list_rm(&range_lst, range);
delete range;
}
}
void cmd_per_help(int argc, char** argv){
int i;
const struct user_subcmd_t* scmd;
ui->atomic(true);
if(argc == 1){
USER("usage: %s [sub-command] <args>...\n", argv[0]);
USER(" sub-commands:\n");
USER(" <file> set peripheral file\n");
USER(" set <register> <value> [<cnt>] set register\n");
USER(" fold <line> fold/unfold peripheral segment\n");
USER(" complete <file> <sync> get list of peripheral segments and addresses\n");
USER(" export <file> <sync> export used peripheral file to vim script\n");
USER(" view update per window\n");
USER("\n");
}
else{
for(i=1; i<argc; i++){
scmd = user_subcmd::lookup(argv[i], strlen(argv[i]));
if(scmd == 0){
USER("invalid sub-command \"%s\" to command \"%s\"\n", argv[i], argv[0]);
continue;
}
switch(scmd->id){
case SET:
USER("usage %s %s <register> <value> [<count>]\n", argv[0], argv[i]);
USER(" set register <register> to <value>\n");
USER("\n");
break;
case FOLD:
USER("usage %s %s <line>\n", argv[0], argv[i]);
USER(" fold/unfold peripheral segment at line <line>\n");
USER("\n");
break;
case COMPLETE:
USER("usage %s %s <file> <sync>\n", argv[0], argv[i]);
USER(" print list of line numbers and addresses to file <file>, using file <sync> to sync with vim\n");
USER(" both lists are separated by '<addr>'\n");
USER(" the items of each list are '\\n' separated\n");
USER("\n");
break;
case EXPORT:
USER("usage %s %s <file> <sync>\n", argv[0], argv[1]);
USER(" export peripheral file to vim script <file>, using file <sync> to sync with vim\n");
USER("\n");
break;
case VIEW:
break;
default:
USER("invalid sub-command \"%s\" to command \"%s\"\n", argv[i], argv[0]);
};
}
}
ui->win_cursor_set(ui->win_getid(USERLOG_NAME), -1);
ui->atomic(false);
}
int cmd_per_update(){
char c;
int win_id;
unsigned int line;
unsigned long long reg_val, bit_val;
bool changed;
gdb_memory_t *mem;
per_range_t* range;
per_register_t* reg;
per_bits_t* bits;
win_id = ui->win_getid(PER_NAME);
if(win_id < 0)
return 0;
line_map.clear();
line = 1;
ui->atomic(true);
ui->win_clear(win_id);
list_for_each(range_lst, range){
/* print header */
ui->win_print(win_id, "[%c] %s\n", (range->expanded ? '-' : '+'), range->name);
line_map[line++] = range;
if(!range->expanded){
ui->win_print(win_id, "\n");
line++;
continue;
}
/* get memory content */
mem = range->mem;
if(mem->update() != 0){
ui->atomic(false);
return -1;
}
/* print register values */
list_for_each(range->regs, reg){
if(reg->nbytes == 0){
ui->win_print(win_id, "%s\n", reg->name ? reg->name : "");
line_map[line] = range;
line++;
continue;
}
changed = memcmp(mem->content + reg->offset * 2, mem->content_old + reg->offset * 2, reg->nbytes * 2);
ui->win_print(win_id, " %s = %s%.*s\n", reg->name, (changed ? "`" : ""), reg->nbytes * 2, mem->content + reg->offset * 2);
line_map[line] = range;
line++;
// print bits
if(reg->bits){
c = mem->content[reg->offset * 2 + reg->nbytes * 2];
mem->content[reg->offset * 2 + reg->nbytes * 2] = 0;
reg_val = strtoll(mem->content + reg->offset * 2, 0, 16);
mem->content[reg->offset * 2 + reg->nbytes * 2] = c;
list_for_each(reg->bits, bits){
bit_val = (reg_val & (bits->mask << bits->idx)) >> bits->idx;
changed = (bit_val == bits->value) ? false : true;
bits->value = bit_val;
ui->win_print(win_id, " %s %s%0*.*x", bits->name, (changed ? "`" : ""), bits->nbits / 4, bits->nbits / 4, bit_val);
}
line_map[line] = range;
ui->win_print(win_id, "\n\n");
line += 2;
}
}
}
ui->atomic(false);
return 0;
}
<commit_msg>[user-cmd: per]<commit_after>#include <common/defaults.h>
#include <common/list.h>
#include <common/map.h>
#include <common/log.h>
#include <common/string.h>
#include <gui/gui.h>
#include <gdb/gdb.h>
#include <gdb/result.h>
#include <gdb/memory.h>
#include <gdb/variable.h>
#include <user_cmd/cmd.h>
#include <user_cmd/subcmd.hash.h>
#include <user_cmd/pertypes.h>
#include <user_cmd/per.tab.h>
#include <user_cmd/per.lex.h>
#include <map>
#include <string>
using namespace std;
/* macros */
#define CTOI(c) (unsigned int)((c) - ((c) >= 'a' ? 87 : 48))
#define ALIGN(val, base) ((val) & (~(base - 1)))
/* static variables */
static char* per_file = 0;
static per_range_t* range_lst = 0;
static map<unsigned int, per_range_t*> line_map;
static map<string, per_register_t*> reg_map;
/* global functions */
int cmd_per_exec(int argc, char** argv){
int r;
const struct user_subcmd_t* scmd;
FILE* fp;
per_range_t* range;
per_register_t* reg;
per_bits_t* bits;
map<unsigned int, per_range_t*>::iterator it_range;
map<string, per_register_t*>::iterator it_reg;
if(argc < 2){
USER("invalid number of arguments to command \"%s\"\n", argv[0]);
cmd_per_help(1, argv);
return 0;
}
scmd = user_subcmd::lookup(argv[1], strlen(argv[1]));
if((scmd == 0 && argc < 2) || (scmd != 0 && ((scmd->id == FOLD && argc < 3) || ((scmd->id == SET || scmd->id == COMPLETE || scmd->id == EXPORT) && argc < 4)))){
USER("invalid number of arguments to command \"%s\"\n", argv[0]);
cmd_per_help(2, argv);
return 0;
}
if(scmd == 0){
/* de-initialise */
cmd_per_cleanup();
/* parser peripheral file */
fp = fopen(argv[1], "r");
if(fp == 0){
USER("cannot open file \"%s\"\n", argv[1]);
return -1;
}
r = perparse(fp, &range_lst);
perlex_destroy();
fclose(fp);
if(r != 0){
USER("error parsing peripheral file \"%s\"\n", argv[1]);
return -1;
}
/* initialise memory segments */
list_for_each(range_lst, range){
// read respective memory
range->mem = gdb_memory_t::acquire(range->base, range->size);
if(range->mem == 0){
USER("unable to create memory segment for range \"%s\" (%p, %u)\n", range->name, range->base, range->size);
cmd_per_cleanup();
cmd_per_update();
return -1;
}
list_for_each(range->regs, reg){
if(reg->name)
strdeescape(reg->name);
if(reg->nbytes == 0)
continue;
// check integrity of register to range
if(reg->offset + reg->nbytes > range->size){
USER("error: offset/size of register \"%s\" exceeds size of range \"%s\"\n", reg->name, range->name);
cmd_per_cleanup();
cmd_per_update();
return -1;
}
// check integrity of bits to register
list_for_each(reg->bits, bits){
if(bits->idx + bits->nbits > reg->nbytes * 8){
USER("error: index/size of bits \"%s\" exceeds size of register \"%s\"\n", bits->name, reg->name);
cmd_per_cleanup();
cmd_per_update();
return -1;
}
}
// update list of registers
reg->parent = range;
reg_map[reg->name] = reg;
}
USER("add memory segment for range \"%s\" (%p, %u)\n", range->name, range->base, range->size);
}
delete [] per_file;
per_file = stralloc(argv[1], strlen(argv[1]));
cmd_per_update();
}
else{
switch(scmd->id){
case SET:
reg = MAP_LOOKUP(reg_map, argv[2]);
if(reg == 0){
USER("unknown register name \"%s\"\n", argv[2]);
return 0;
}
if(gdb_memory_t::set((void*)((unsigned long long)reg->parent->base + reg->offset), argv[3], reg->nbytes) != 0)
return -1;
gdb->memory_update();
break;
case FOLD:
range = MAP_LOOKUP(line_map, atoi(argv[2]));
if(range == 0){
USER("no peripheral segment at line %s\n", argv[2]);
return 0;
}
range->expanded = range->expanded ? false : true;
cmd_per_update();
break;
case COMPLETE:
fp = fopen(argv[2], "w");
if(fp == 0)
return -1;
for(it_range=line_map.begin(); it_range!=line_map.end(); it_range++)
fprintf(fp, "%d\\n", it_range->first);
fprintf(fp, "<regs>");
for(it_reg=reg_map.begin(); it_reg!=reg_map.end(); it_reg++)
fprintf(fp, "%s\\n", it_reg->second->name);
fclose(fp);
/* signal data availability */
fp = fopen(argv[3], "w");
if(fp == 0)
return -1;
fprintf(fp, "1\n");
fclose(fp);
break;
case EXPORT:
fp = fopen(argv[2], "w");
if(fp == 0)
return 0;
if(per_file) fprintf(fp, "Per %s\n\n", per_file);
fclose(fp);
USER("export peripheral commands to \"%s\"\n", argv[2]);
/* signal data availability */
fp = fopen(argv[3], "w");
if(fp == 0)
return -1;
fprintf(fp, "1\n");
fclose(fp);
break;
case VIEW:
cmd_per_update();
break;
default:
USER("unhandled sub command \"%s\" to \"%s\"\n", argv[1], argv[0]);
};
}
return 0;
}
void cmd_per_cleanup(){
per_range_t* range;
delete [] per_file;
per_file = 0;
reg_map.clear();
line_map.clear();
list_for_each(range_lst, range){
list_rm(&range_lst, range);
delete range;
}
}
void cmd_per_help(int argc, char** argv){
int i;
const struct user_subcmd_t* scmd;
ui->atomic(true);
if(argc == 1){
USER("usage: %s [sub-command] <args>...\n", argv[0]);
USER(" sub-commands:\n");
USER(" <file> set peripheral file\n");
USER(" set <register> <value> [<cnt>] set register\n");
USER(" fold <line> fold/unfold peripheral segment\n");
USER(" complete <file> <sync> get list of peripheral segments and addresses\n");
USER(" export <file> <sync> export used peripheral file to vim script\n");
USER(" view update per window\n");
USER("\n");
}
else{
for(i=1; i<argc; i++){
scmd = user_subcmd::lookup(argv[i], strlen(argv[i]));
if(scmd == 0){
USER("invalid sub-command \"%s\" to command \"%s\"\n", argv[i], argv[0]);
continue;
}
switch(scmd->id){
case SET:
USER("usage %s %s <register> <value> [<count>]\n", argv[0], argv[i]);
USER(" set register <register> to <value>\n");
USER("\n");
break;
case FOLD:
USER("usage %s %s <line>\n", argv[0], argv[i]);
USER(" fold/unfold peripheral segment at line <line>\n");
USER("\n");
break;
case COMPLETE:
USER("usage %s %s <file> <sync>\n", argv[0], argv[i]);
USER(" print list of line numbers and addresses to file <file>, using file <sync> to sync with vim\n");
USER(" both lists are separated by '<addr>'\n");
USER(" the items of each list are '\\n' separated\n");
USER("\n");
break;
case EXPORT:
USER("usage %s %s <file> <sync>\n", argv[0], argv[1]);
USER(" export peripheral file to vim script <file>, using file <sync> to sync with vim\n");
USER("\n");
break;
case VIEW:
break;
default:
USER("invalid sub-command \"%s\" to command \"%s\"\n", argv[i], argv[0]);
};
}
}
ui->win_cursor_set(ui->win_getid(USERLOG_NAME), -1);
ui->atomic(false);
}
int cmd_per_update(){
char c;
int win_id;
unsigned int line, i;
unsigned long long reg_val, bit_val;
bool changed;
gdb_memory_t *mem;
per_range_t* range;
per_register_t* reg;
per_bits_t* bits;
win_id = ui->win_getid(PER_NAME);
if(win_id < 0)
return 0;
line_map.clear();
line = 1;
ui->atomic(true);
ui->win_clear(win_id);
list_for_each(range_lst, range){
/* print header */
ui->win_print(win_id, "[%c] %s\n", (range->expanded ? '-' : '+'), range->name);
line_map[line++] = range;
if(!range->expanded){
ui->win_print(win_id, "\n");
line++;
continue;
}
/* get memory content */
mem = range->mem;
if(mem->update() != 0){
ui->atomic(false);
return -1;
}
/* print register values */
list_for_each(range->regs, reg){
if(reg->nbytes == 0){
ui->win_print(win_id, "%s\n", reg->name ? reg->name : "");
line_map[line] = range;
line++;
continue;
}
changed = memcmp(mem->content + reg->offset * 2, mem->content_old + reg->offset * 2, reg->nbytes * 2);
ui->win_print(win_id, " %s = %s%.*s\n", reg->name, (changed ? "`" : ""), reg->nbytes * 2, mem->content + reg->offset * 2);
line_map[line] = range;
line++;
// print bits
if(reg->bits){
c = mem->content[reg->offset * 2 + reg->nbytes * 2];
mem->content[reg->offset * 2 + reg->nbytes * 2] = 0;
reg_val = strtoll(mem->content + reg->offset * 2, 0, 16);
mem->content[reg->offset * 2 + reg->nbytes * 2] = c;
i = 0;
list_for_each(reg->bits, bits){
if(i && i % 4 == 0){
line_map[line] = range;
ui->win_print(win_id, "\n");
line++;
}
bit_val = (reg_val & (bits->mask << bits->idx)) >> bits->idx;
changed = (bit_val == bits->value) ? false : true;
bits->value = bit_val;
ui->win_print(win_id, " %s %s%0*.*x", bits->name, (changed ? "`" : ""), bits->nbits / 4, bits->nbits / 4, bit_val);
i++;
}
line_map[line] = range;
ui->win_print(win_id, "\n\n");
line += 2;
}
}
}
ui->atomic(false);
return 0;
}
<|endoftext|>
|
<commit_before>
#include "do_sort.h"
#define DATA_SIZE 20
#define DUMP_DATA 0
using namespace std;
// Check whether the list is correctly sorted.
bool is_sorted(do_sort::sort* ss) {
for (int i = 0; i < ss->size() - 1; ++i)
if ((*ss)[i] > (*ss)[i + 1])
return false;
return true;
}
// Report the testing results.
void report_test_result(do_sort::sort* ss, string sorting_method) {
string test_result = (is_sorted(ss)) ? "\033[32mPASSED" : "\033[31mFAILED";
cout << sorting_method << " test --> " << "[" << test_result << "\033[39m]" << endl;;
}
int main() {
string test_result = "";
cout << endl << endl << "-------------------- \033[34mTesting Results\033[39m --------------------" << endl;
// Unit test for the bubble sort.
do_sort::bubble_sort *bs = new do_sort::bubble_sort();
bs->init(DATA_SIZE);
bs->do_sort();
report_test_result(static_cast<do_sort::sort*>(bs), "Bubble sort");
#if DUMP_DATA
bs->dump("Bubble Sort");
#endif
delete bs;
// Unit test for the selection sort.
do_sort::selection_sort *ss = new do_sort::selection_sort();
ss->init(DATA_SIZE);
ss->do_sort();
report_test_result(static_cast<do_sort::sort*>(ss), "Selection sort");
#if DUMP_DATA
ss->dump("Selection Sort");
#endif
delete ss;
// Unit test for the insertion sort.
do_sort::insertion_sort *is = new do_sort::insertion_sort();
is->init(DATA_SIZE);
is->do_sort();
report_test_result(static_cast<do_sort::sort*>(is), "Insertion sort");
#if DUMP_DATA
is->dump("Insertion Sort");
#endif
delete is;
// Unit test for the merge sort.
do_sort::merge_sort *ms = new do_sort::merge_sort();
ms->init(DATA_SIZE);
ms->do_sort();
report_test_result(static_cast<do_sort::sort*>(ms), "Merge sort");
#if DUMP_DATA
ms->dump("Merge Sort");
#endif
delete ms;
// Unit test for the quick sort.
do_sort::quick_sort *qs = new do_sort::quick_sort();
qs->init(DATA_SIZE);
qs->do_sort();
report_test_result(static_cast<do_sort::sort*>(qs), "Quick sort");
#if DUMP_DATA
qs->dump("Quick Sort");
#endif
delete qs;
cout << "---------------------------------------------------------" << endl << endl;
return 0;
}
<commit_msg>Added some corner cases to the test cases and made the report nicer.<commit_after>
#include "do_sort.h"
#define DATA_SIZE 20
#define DUMP_DATA 0
using namespace std;
// Check whether the list is correctly sorted.
bool is_sorted(do_sort::sort* ss) {
if (ss->size() == 0)
return true;
for (int i = 0; i < ss->size() - 1; ++i)
if ((*ss)[i] > (*ss)[i + 1])
return false;
return true;
}
// Report the testing results.
void report_test_result(do_sort::sort* ss, string sorting_method) {
string test_result = (is_sorted(ss)) ? "\033[32mPASSED" : "\033[31mFAILED";
cout << sorting_method << " test --> " << "[" << test_result << "\033[39m]" << endl;;
}
int main() {
string test_result = "";
cout << endl << endl << "-------------------- \033[34mTesting Results\033[39m --------------------" << endl;
// Unit test for the bubble sort.
do_sort::bubble_sort *bs = new do_sort::bubble_sort();
bs->init(DATA_SIZE);
bs->do_sort();
report_test_result(static_cast<do_sort::sort*>(bs), "Bubble sort");
bs->clear_data();
bs->do_sort();
report_test_result(static_cast<do_sort::sort*>(bs), "Bubble sort [corner case #1]");
bs->init(1);
bs->do_sort();
report_test_result(static_cast<do_sort::sort*>(bs), "Bubble sort [corner case #2]");
cout << "\033[36m---------------------------------------------------------\033[39m" << endl;
#if DUMP_DATA
bs->dump("Bubble Sort");
#endif
delete bs;
// Unit test for the selection sort.
do_sort::selection_sort *ss = new do_sort::selection_sort();
ss->init(DATA_SIZE);
ss->do_sort();
report_test_result(static_cast<do_sort::sort*>(ss), "Selection sort");
ss->clear_data();
ss->do_sort();
report_test_result(static_cast<do_sort::sort*>(ss), "Selection sort [corner case #1]");
ss->init(1);
ss->do_sort();
report_test_result(static_cast<do_sort::sort*>(ss), "Selection sort [corner case #2]");
cout << "\033[36m---------------------------------------------------------\033[39m" << endl;
#if DUMP_DATA
ss->dump("Selection Sort");
#endif
delete ss;
// Unit test for the insertion sort.
do_sort::insertion_sort *is = new do_sort::insertion_sort();
is->init(DATA_SIZE);
is->do_sort();
report_test_result(static_cast<do_sort::sort*>(is), "Insertion sort");
is->clear_data();
is->do_sort();
report_test_result(static_cast<do_sort::sort*>(is), "Insertion sort [corner case #1]");
is->init(1);
is->do_sort();
report_test_result(static_cast<do_sort::sort*>(is), "Insertion sort [corner case #2]");
cout << "\033[36m---------------------------------------------------------\033[39m" << endl;
#if DUMP_DATA
is->dump("Insertion Sort");
#endif
delete is;
// Unit test for the merge sort.
do_sort::merge_sort *ms = new do_sort::merge_sort();
ms->init(DATA_SIZE);
ms->do_sort();
report_test_result(static_cast<do_sort::sort*>(ms), "Merge sort");
ms->clear_data();
ms->do_sort();
report_test_result(static_cast<do_sort::sort*>(ms), "Merge sort [corner case #1]");
ms->init(1);
ms->do_sort();
report_test_result(static_cast<do_sort::sort*>(ms), "Merge sort [corner case #2]");
cout << "\033[36m---------------------------------------------------------\033[39m" << endl;
#if DUMP_DATA
ms->dump("Merge Sort");
#endif
delete ms;
// Unit test for the quick sort.
do_sort::quick_sort *qs = new do_sort::quick_sort();
qs->init(DATA_SIZE);
qs->do_sort();
report_test_result(static_cast<do_sort::sort*>(qs), "Quick sort");
qs->clear_data();
qs->do_sort();
report_test_result(static_cast<do_sort::sort*>(qs), "Quick sort [corner case #1]");
qs->init(1);
qs->do_sort();
report_test_result(static_cast<do_sort::sort*>(qs), "Quick sort [corner case #2]");
#if DUMP_DATA
qs->dump("Quick Sort");
#endif
delete qs;
cout << "---------------------------------------------------------" << endl << endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include <ctre.hpp>
#include <iostream>
static constexpr auto pattern = ctll::fixed_string("(?<first>[0-9])[0-9]++");
int main() {
using namespace std::string_view_literals;
auto input = "123,456,768"sv;
#if __cpp_nontype_template_parameter_class
for (auto match: ctre::range<"(?<first>[0-9])[0-9]++">(input)) {
#else
using namespace ctre::literals;
for (auto match: ctre::range<pattern>(input)) {
#endif
#if __cpp_nontype_template_parameter_class
std::cout << std::string_view(match.get<"firs2t">()) << "\n";
#else
std::cout << std::string_view(match.get<1>()) << "\n";
#endif
}
}
<commit_msg>remove intentional (and forget) typo<commit_after>#include <ctre.hpp>
#include <iostream>
static constexpr auto pattern = ctll::fixed_string("(?<first>[0-9])[0-9]++");
int main() {
using namespace std::string_view_literals;
auto input = "123,456,768"sv;
#if __cpp_nontype_template_parameter_class
for (auto match: ctre::range<"(?<first>[0-9])[0-9]++">(input)) {
#else
using namespace ctre::literals;
for (auto match: ctre::range<pattern>(input)) {
#endif
#if __cpp_nontype_template_parameter_class
std::cout << std::string_view(match.get<"first">()) << "\n";
#else
std::cout << std::string_view(match.get<1>()) << "\n";
#endif
}
}
<|endoftext|>
|
<commit_before>//
// Created by kanairen on 2016/06/14.
//
#include "TestLayer.h"
#include "TestSoftMaxLayer.h"
#include "TestGridLayer.h"
#include "TestConvLayer.h"
#include "TestMaxPoolLayer.h"
#include "TestModel.h"
int main() {
// test Softmax Layer
sm_layer::test_init();
sm_layer::test_forward();
sm_layer::test_backward();
// test Grid Layer
grid_layer::test_init();
grid_layer::test_filter_outsize();
// test Convolution Layer
conv_layer::test_init();
conv_layer::test_backward();
// test MaxPooling Layer
max_pool_layer::test_init();
max_pool_layer::test_forward();
max_pool_layer::test_backward();
// test Model
model::test_init();
model::test_forward();
model::test_backward();
return RUN_ALL_TESTS();
}
<commit_msg>fix GoogleTestのフラグ初期化を追加<commit_after>//
// Created by kanairen on 2016/06/14.
//
#include "TestLayer.h"
#include "TestSoftMaxLayer.h"
#include "TestGridLayer.h"
#include "TestConvLayer.h"
#include "TestMaxPoolLayer.h"
#include "TestModel.h"
int main(int argc, char **argv) {
// Google Test
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>// SPDX-FileCopyrightText: 2014 Félix Robles <felrobelv@gmail.com>
// SPDX-FileCopyrightText: 2021 Eduardo Robles <edulix@nvotes.com>
//
// SPDX-License-Identifier: AGPL-3.0-only
#include <agora-airgap/ElGamal.h>
#include <agora-airgap/encrypt.h>
#include <agora-airgap/sha256.h>
#include <cryptopp/cryptlib.h>
#include <cryptopp/elgamal.h>
#include <cryptopp/files.h>
#include <cryptopp/osrng.h>
#include <cryptopp/secblock.h>
#include <gmock/gmock.h>
#include <gmpxx.h>
#include <gtest/gtest.h>
#include <memory.h>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
using namespace AgoraAirgap::sha256;
using namespace CryptoPP;
using std::function;
using std::string;
using std::stringstream;
using ::testing::HasSubstr;
using ::testing::ThrowsMessage;
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST(Sha256Test, StringOne)
{
BYTE text1[] = {"abc"};
BYTE hash1[SHA256_BLOCK_SIZE] = {
0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40,
0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17,
0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad};
BYTE buf[SHA256_BLOCK_SIZE];
SHA256_CTX ctx;
sha256_init(&ctx);
sha256_update(&ctx, text1, sizeof(text1) - 1);
sha256_final(&ctx, buf);
EXPECT_EQ(0, memcmp(hash1, buf, SHA256_BLOCK_SIZE));
}
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST(Sha256Test, StringTwo)
{
BYTE text2[] = {"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"};
BYTE hash2[SHA256_BLOCK_SIZE] = {
0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26,
0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff,
0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1};
BYTE buf[SHA256_BLOCK_SIZE];
SHA256_CTX ctx;
sha256_init(&ctx);
sha256_update(&ctx, text2, sizeof(text2) - 1);
sha256_final(&ctx, buf);
EXPECT_EQ(0, memcmp(hash2, buf, SHA256_BLOCK_SIZE));
}
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST(Sha256Test, StringLoopTest)
{
BYTE text3[] = {"aaaaaaaaaa"};
BYTE hash3[SHA256_BLOCK_SIZE] = {
0xcd, 0xc7, 0x6e, 0x5c, 0x99, 0x14, 0xfb, 0x92, 0x81, 0xa1, 0xc7,
0xe2, 0x84, 0xd7, 0x3e, 0x67, 0xf1, 0x80, 0x9a, 0x48, 0xa4, 0x97,
0x20, 0x0e, 0x04, 0x6d, 0x39, 0xcc, 0xc7, 0x11, 0x2c, 0xd0};
BYTE buf[SHA256_BLOCK_SIZE];
SHA256_CTX ctx;
sha256_init(&ctx);
for (int idx = 0; idx < 100000; ++idx)
{
sha256_update(&ctx, text3, sizeof(text3) - 1);
}
sha256_final(&ctx, buf);
EXPECT_EQ(0, memcmp(hash3, buf, SHA256_BLOCK_SIZE));
}
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST(AgoraUnitTest, SmallMessageEncryption)
{
mpz_t p, q, g, y, x, m, rand;
mpz_init_set_str(p, "1019", 10);
mpz_init_set_str(q, "509", 10); // q = (p-1)/2 = 509
mpz_init_set_str(g, "3", 10);
mpz_init_set_str(y, "770", 10); // y = (g^x) mod p
mpz_init_set_str(x, "66", 10);
mpz_init_set_str(m, "133", 10);
mpz_init_set_str(rand, "4", 10);
mpz_class p_c(p), q_c(q), g_c(g), x_c(x), y_c(y), rand_c(rand), m_c(m);
AgoraAirgap::ElGamal::PublicKey pk(p_c, q_c, g_c, y_c);
AgoraAirgap::ElGamal::Plaintext plaintext(m_c, pk, true);
AgoraAirgap::ElGamal::Ciphertext ciphertext =
AgoraAirgap::ElGamal::encrypt(pk, plaintext, rand_c);
// alpha = (g^random) mod p = (3^4) mod 1019 = 81
// U = (y^random) mod p = (770^4) mod 1019 = 508
// M = m+1 = 134
// beta = ( U M ) mod p = ( 508 * 134) mod 1019 = 818
EXPECT_EQ(0, ciphertext.alpha.get_str().compare("81"));
EXPECT_EQ(0, ciphertext.beta.get_str().compare("818"));
}
/**
* Groups examples that should not fail
*/
class ExampleDirsTest : public ::testing::Test
{
protected:
void SetUp() override
{
this->exampleDirs = std::vector<std::string>({"example_1"});
}
std::vector<string> exampleDirs;
};
/**
* Executes download_audit with correct data
*/
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST_F(ExampleDirsTest, MockDownloadAudit)
{
for (string & examplePath: exampleDirs)
{
string ballotPath = examplePath + "/ballot.json";
auto getConfig = [&examplePath](stringstream & out, const string &) {
return AgoraAirgap::read_file(out, examplePath + "/config");
};
stringstream out;
EXPECT_NO_THROW(
{ AgoraAirgap::download_audit(out, ballotPath, getConfig); });
EXPECT_EQ(out.str().find("Error"), string::npos)
<< "Error found in output: " << out.str() << std::endl;
}
}
/**
* Executes download_audit with invalid data (/config-bad will yield nothing)
*/
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST_F(ExampleDirsTest, MockBadDownloadAudit)
{
for (string & examplePath: exampleDirs)
{
string ballotPath = examplePath + "/ballot.json";
auto getConfig = [&examplePath](stringstream & out, const string &) {
return AgoraAirgap::read_file(out, examplePath + "/config-bad");
};
stringstream out;
EXPECT_THAT(
[&]() { AgoraAirgap::download_audit(out, ballotPath, getConfig); },
ThrowsMessage<std::runtime_error>(
HasSubstr("!!! Error [read-file]")))
<< std::endl
<< "Error found in output: " << out.str() << std::endl;
}
}
<commit_msg>adding some more unit tests<commit_after>// SPDX-FileCopyrightText: 2014 Félix Robles <felrobelv@gmail.com>
// SPDX-FileCopyrightText: 2021 Eduardo Robles <edulix@nvotes.com>
//
// SPDX-License-Identifier: AGPL-3.0-only
#include <agora-airgap/ElGamal.h>
#include <agora-airgap/encrypt.h>
#include <agora-airgap/sha256.h>
#include <cryptopp/cryptlib.h>
#include <cryptopp/elgamal.h>
#include <cryptopp/files.h>
#include <cryptopp/osrng.h>
#include <cryptopp/secblock.h>
#include <gmock/gmock.h>
#include <gmpxx.h>
#include <gtest/gtest.h>
#include <memory.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
using namespace AgoraAirgap::sha256;
using namespace CryptoPP;
using std::function;
using std::string;
using std::stringstream;
using ::testing::HasSubstr;
using ::testing::Not;
using ::testing::ThrowsMessage;
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST(Sha256Test, StringOne)
{
BYTE text1[] = {"abc"};
BYTE hash1[SHA256_BLOCK_SIZE] = {
0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40,
0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17,
0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad};
BYTE buf[SHA256_BLOCK_SIZE];
SHA256_CTX ctx;
sha256_init(&ctx);
sha256_update(&ctx, text1, sizeof(text1) - 1);
sha256_final(&ctx, buf);
EXPECT_EQ(0, memcmp(hash1, buf, SHA256_BLOCK_SIZE));
}
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST(Sha256Test, StringTwo)
{
BYTE text2[] = {"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"};
BYTE hash2[SHA256_BLOCK_SIZE] = {
0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26,
0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff,
0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1};
BYTE buf[SHA256_BLOCK_SIZE];
SHA256_CTX ctx;
sha256_init(&ctx);
sha256_update(&ctx, text2, sizeof(text2) - 1);
sha256_final(&ctx, buf);
EXPECT_EQ(0, memcmp(hash2, buf, SHA256_BLOCK_SIZE));
}
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST(Sha256Test, StringLoopTest)
{
BYTE text3[] = {"aaaaaaaaaa"};
BYTE hash3[SHA256_BLOCK_SIZE] = {
0xcd, 0xc7, 0x6e, 0x5c, 0x99, 0x14, 0xfb, 0x92, 0x81, 0xa1, 0xc7,
0xe2, 0x84, 0xd7, 0x3e, 0x67, 0xf1, 0x80, 0x9a, 0x48, 0xa4, 0x97,
0x20, 0x0e, 0x04, 0x6d, 0x39, 0xcc, 0xc7, 0x11, 0x2c, 0xd0};
BYTE buf[SHA256_BLOCK_SIZE];
SHA256_CTX ctx;
sha256_init(&ctx);
for (int idx = 0; idx < 100000; ++idx)
{
sha256_update(&ctx, text3, sizeof(text3) - 1);
}
sha256_final(&ctx, buf);
EXPECT_EQ(0, memcmp(hash3, buf, SHA256_BLOCK_SIZE));
}
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST(AgoraUnitTest, SmallMessageEncryption)
{
mpz_t p, q, g, y, x, m, rand;
mpz_init_set_str(p, "1019", 10);
mpz_init_set_str(q, "509", 10); // q = (p-1)/2 = 509
mpz_init_set_str(g, "3", 10);
mpz_init_set_str(y, "770", 10); // y = (g^x) mod p
mpz_init_set_str(x, "66", 10);
mpz_init_set_str(m, "133", 10);
mpz_init_set_str(rand, "4", 10);
mpz_class p_c(p), q_c(q), g_c(g), x_c(x), y_c(y), rand_c(rand), m_c(m);
AgoraAirgap::ElGamal::PublicKey pk(p_c, q_c, g_c, y_c);
AgoraAirgap::ElGamal::Plaintext plaintext(m_c, pk, true);
AgoraAirgap::ElGamal::Ciphertext ciphertext =
AgoraAirgap::ElGamal::encrypt(pk, plaintext, rand_c);
// alpha = (g^random) mod p = (3^4) mod 1019 = 81
// U = (y^random) mod p = (770^4) mod 1019 = 508
// M = m+1 = 134
// beta = ( U M ) mod p = ( 508 * 134) mod 1019 = 818
EXPECT_EQ(0, ciphertext.alpha.get_str().compare("81"));
EXPECT_EQ(0, ciphertext.beta.get_str().compare("818"));
}
/**
* Groups examples that should not fail
*/
class ExampleDirsTest : public ::testing::Test
{
protected:
void SetUp() override
{
this->exampleDirs = std::vector<std::string>({"example_1"});
}
std::vector<string> exampleDirs;
};
/**
* Executes download_audit with correct data
*/
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST_F(ExampleDirsTest, MockDownloadAudit)
{
for (string & examplePath: exampleDirs)
{
string ballotPath = examplePath + "/ballot.json";
auto getConfig = [&examplePath](stringstream & out, const string &) {
return AgoraAirgap::read_file(out, examplePath + "/config");
};
stringstream out;
EXPECT_NO_THROW(
{ AgoraAirgap::download_audit(out, ballotPath, getConfig); });
EXPECT_EQ(out.str().find("Error"), string::npos)
<< "Error found in output: " << out.str() << std::endl;
EXPECT_THAT(out.str(), HasSubstr("\n> Audit PASSED\n"))
<< std::endl
<< "Error found in output: " << out.str() << std::endl;
}
}
/**
* Executes download_audit with invalid data (/config-bad will yield nothing)
*/
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST_F(ExampleDirsTest, MockBadDownloadAudit)
{
for (string & examplePath: exampleDirs)
{
string ballotPath = examplePath + "/ballot.json";
auto getConfig = [&examplePath](stringstream & out, const string &) {
return AgoraAirgap::read_file(out, examplePath + "/config-bad");
};
stringstream out;
EXPECT_THAT(
[&]() { AgoraAirgap::download_audit(out, ballotPath, getConfig); },
ThrowsMessage<std::runtime_error>(
HasSubstr("!!! Error [read-file]")))
<< std::endl
<< "Error found in output: " << out.str() << std::endl;
}
}
/**
* Executes download only and compares downloaded file with original
*/
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST_F(ExampleDirsTest, MockDownload)
{
for (string & examplePath: exampleDirs)
{
string ballotPath = examplePath + "/ballot.json";
auto getConfig = [&examplePath](stringstream & out, const string &) {
return AgoraAirgap::read_file(out, examplePath + "/config");
};
stringstream out;
string election_path = std::tmpnam(nullptr);
AgoraAirgap::download(out, ballotPath, election_path, getConfig);
EXPECT_THAT(out.str(), Not(HasSubstr("!!! Error")))
<< std::endl
<< "Error found in output: " << out.str() << std::endl;
stringstream out2;
string read_election_str = AgoraAirgap::read_file(out, election_path);
string orig_election_str =
AgoraAirgap::read_file(out, examplePath + "/config");
EXPECT_THAT(out2.str(), Not(HasSubstr("!!! Error")))
<< std::endl
<< "Error found in output: " << out2.str() << std::endl;
EXPECT_EQ(read_election_str, orig_election_str)
<< "Read election config does not match original" << std::endl;
}
}
/**
* Executes audit only
*/
// Supress warnings related to using the google test macro
// NOLINTNEXTLINE(misc-unused-parameters, readability-named-parameter)
TEST_F(ExampleDirsTest, MockAudit)
{
for (string & examplePath: exampleDirs)
{
string ballotPath = examplePath + "/ballot.json";
stringstream out;
string election_path = examplePath + "/config";
EXPECT_NO_THROW(
{ AgoraAirgap::audit(out, ballotPath, election_path); });
EXPECT_EQ(out.str().find("Error"), string::npos)
<< "Error found in output: " << out.str() << std::endl;
AgoraAirgap::audit(out, ballotPath, election_path);
EXPECT_THAT(out.str(), HasSubstr("\n> Audit PASSED\n"))
<< std::endl
<< "Error found in output: " << out.str() << std::endl;
}
}<|endoftext|>
|
<commit_before>#include <glog/logging.h>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include "boost/algorithm/string.hpp"
#include "caffe/caffe.hpp"
using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::Timer;
using caffe::vector;
DEFINE_int32(gpu, -1,
"Run in GPU mode on given device ID.");
DEFINE_string(solver, "",
"The solver definition protocol buffer text file.");
DEFINE_string(model, "",
"The model definition protocol buffer text file..");
DEFINE_string(snapshot, "",
"Optional; the snapshot solver state to resume training.");
DEFINE_string(weights, "",
"Optional; the pretrained weights to initialize finetuning. "
"Cannot be set simultaneously with snapshot.");
DEFINE_int32(iterations, 50,
"The number of iterations to run.");
// A simple registry for caffe commands.
typedef int (*BrewFunction)();
typedef std::map<caffe::string, BrewFunction> BrewMap;
BrewMap g_brew_map;
#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \
public: /* NOLINT */ \
__Registerer_##func() { \
g_brew_map[#func] = &func; \
} \
}; \
__Registerer_##func g_registerer_##func; \
}
static BrewFunction GetBrewFunction(const caffe::string& name) {
if (g_brew_map.count(name)) {
return g_brew_map[name];
} else {
LOG(ERROR) << "Available caffe actions:";
for (BrewMap::iterator it = g_brew_map.begin();
it != g_brew_map.end(); ++it) {
LOG(ERROR) << "\t" << it->first;
}
LOG(FATAL) << "Unknown action: " << name;
return NULL; // not reachable, just to suppress old compiler warnings.
}
}
// caffe commands to call by
// caffe <command> <args>
//
// To add a command, define a function "int command()" and register it with
// RegisterBrewFunction(action);
// Device Query: show diagnostic information for a GPU device.
int device_query() {
CHECK_GT(FLAGS_gpu, -1) << "Need a device ID to query.";
LOG(INFO) << "Querying device ID = " << FLAGS_gpu;
caffe::Caffe::SetDevice(FLAGS_gpu);
caffe::Caffe::DeviceQuery();
return 0;
}
RegisterBrewFunction(device_query);
// Load the weights from the specified caffemodel(s) into the train and
// test nets.
void CopyLayers(caffe::Solver<float>* solver, const std::string& model_list) {
std::vector<std::string> model_names;
boost::split(model_names, model_list, boost::is_any_of(",") );
for (int i = 0; i < model_names.size(); ++i) {
LOG(INFO) << "Finetuning from " << model_names[i];
solver->net()->CopyTrainedLayersFrom(model_names[i]);
for (int j = 0; j < solver->test_nets().size(); ++j) {
solver->test_nets()[j]->CopyTrainedLayersFrom(model_names[i]);
}
}
}
// Train / Finetune a model.
int train() {
CHECK_GT(FLAGS_solver.size(), 0) << "Need a solver definition to train.";
CHECK(!FLAGS_snapshot.size() || !FLAGS_weights.size())
<< "Give a snapshot to resume training or weights to finetune "
"but not both.";
caffe::SolverParameter solver_param;
caffe::ReadProtoFromTextFileOrDie(FLAGS_solver, &solver_param);
// If the gpu flag is not provided, allow the mode and device to be set
// in the solver prototxt.
if (FLAGS_gpu < 0
&& solver_param.solver_mode() == caffe::SolverParameter_SolverMode_GPU) {
FLAGS_gpu = solver_param.device_id();
}
// Set device id and mode
if (FLAGS_gpu >= 0) {
LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
Caffe::SetDevice(FLAGS_gpu);
Caffe::set_mode(Caffe::GPU);
} else {
LOG(INFO) << "Use CPU.";
Caffe::set_mode(Caffe::CPU);
}
LOG(INFO) << "Starting Optimization";
shared_ptr<caffe::Solver<float> >
solver(caffe::GetSolver<float>(solver_param));
if (FLAGS_snapshot.size()) {
LOG(INFO) << "Resuming from " << FLAGS_snapshot;
solver->Solve(FLAGS_snapshot);
} else if (FLAGS_weights.size()) {
CopyLayers(&*solver, FLAGS_weights);
solver->Solve();
} else {
solver->Solve();
}
LOG(INFO) << "Optimization Done.";
return 0;
}
RegisterBrewFunction(train);
// Test: score a model.
int test() {
CHECK_GT(FLAGS_model.size(), 0) << "Need a model definition to score.";
CHECK_GT(FLAGS_weights.size(), 0) << "Need model weights to score.";
// Set device id and mode
if (FLAGS_gpu >= 0) {
LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
Caffe::SetDevice(FLAGS_gpu);
Caffe::set_mode(Caffe::GPU);
} else {
LOG(INFO) << "Use CPU.";
Caffe::set_mode(Caffe::CPU);
}
// Instantiate the caffe net.
Net<float> caffe_net(FLAGS_model, caffe::TEST);
caffe_net.CopyTrainedLayersFrom(FLAGS_weights);
LOG(INFO) << "Running for " << FLAGS_iterations << " iterations.";
vector<Blob<float>* > bottom_vec;
vector<int> test_score_output_id;
vector<float> test_score;
float loss = 0;
for (int i = 0; i < FLAGS_iterations; ++i) {
float iter_loss;
const vector<Blob<float>*>& result =
caffe_net.Forward(bottom_vec, &iter_loss);
loss += iter_loss;
int idx = 0;
for (int j = 0; j < result.size(); ++j) {
const float* result_vec = result[j]->cpu_data();
for (int k = 0; k < result[j]->count(); ++k, ++idx) {
const float score = result_vec[k];
if (i == 0) {
test_score.push_back(score);
test_score_output_id.push_back(j);
} else {
test_score[idx] += score;
}
const std::string& output_name = caffe_net.blob_names()[
caffe_net.output_blob_indices()[j]];
LOG(INFO) << "Batch " << i << ", " << output_name << " = " << score;
}
}
}
loss /= FLAGS_iterations;
LOG(INFO) << "Loss: " << loss;
for (int i = 0; i < test_score.size(); ++i) {
const std::string& output_name = caffe_net.blob_names()[
caffe_net.output_blob_indices()[test_score_output_id[i]]];
const float loss_weight =
caffe_net.blob_loss_weights()[caffe_net.output_blob_indices()[i]];
std::ostringstream loss_msg_stream;
const float mean_score = test_score[i] / FLAGS_iterations;
if (loss_weight) {
loss_msg_stream << " (* " << loss_weight
<< " = " << loss_weight * mean_score << " loss)";
}
LOG(INFO) << output_name << " = " << mean_score << loss_msg_stream.str();
}
return 0;
}
RegisterBrewFunction(test);
// Time: benchmark the execution time of a model.
int time() {
CHECK_GT(FLAGS_model.size(), 0) << "Need a model definition to time.";
// Set device id and mode
if (FLAGS_gpu >= 0) {
LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
Caffe::SetDevice(FLAGS_gpu);
Caffe::set_mode(Caffe::GPU);
} else {
LOG(INFO) << "Use CPU.";
Caffe::set_mode(Caffe::CPU);
}
// Instantiate the caffe net.
Net<float> caffe_net(FLAGS_model, caffe::TRAIN);
// Do a clean forward and backward pass, so that memory allocation are done
// and future iterations will be more stable.
LOG(INFO) << "Performing Forward";
// Note that for the speed benchmark, we will assume that the network does
// not take any input blobs.
float initial_loss;
caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
LOG(INFO) << "Initial loss: " << initial_loss;
LOG(INFO) << "Performing Backward";
caffe_net.Backward();
const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
const vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
const vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
const vector<vector<bool> >& bottom_need_backward =
caffe_net.bottom_need_backward();
LOG(INFO) << "*** Benchmark begins ***";
LOG(INFO) << "Testing for " << FLAGS_iterations << " iterations.";
Timer total_timer;
total_timer.Start();
Timer forward_timer;
Timer backward_timer;
Timer timer;
std::vector<double> forward_time_per_layer(layers.size(), 0.0);
std::vector<double> backward_time_per_layer(layers.size(), 0.0);
double forward_time = 0.0;
double backward_time = 0.0;
for (int j = 0; j < FLAGS_iterations; ++j) {
Timer iter_timer;
iter_timer.Start();
forward_timer.Start();
for (int i = 0; i < layers.size(); ++i) {
timer.Start();
layers[i]->Forward(bottom_vecs[i], top_vecs[i]);
forward_time_per_layer[i] += timer.MicroSeconds();
}
forward_time += forward_timer.MicroSeconds();
backward_timer.Start();
for (int i = layers.size() - 1; i >= 0; --i) {
timer.Start();
layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
bottom_vecs[i]);
backward_time_per_layer[i] += timer.MicroSeconds();
}
backward_time += backward_timer.MicroSeconds();
LOG(INFO) << "Iteration: " << j + 1 << " forward-backward time: "
<< iter_timer.MilliSeconds() << " ms.";
}
LOG(INFO) << "Average time per layer: ";
for (int i = 0; i < layers.size(); ++i) {
const caffe::string& layername = layers[i]->layer_param().name();
LOG(INFO) << std::setfill(' ') << std::setw(10) << layername <<
"\tforward: " << forward_time_per_layer[i] / 1000 /
FLAGS_iterations << " ms.";
LOG(INFO) << std::setfill(' ') << std::setw(10) << layername <<
"\tbackward: " << backward_time_per_layer[i] / 1000 /
FLAGS_iterations << " ms.";
}
total_timer.Stop();
LOG(INFO) << "Average Forward pass: " << forward_time / 1000 /
FLAGS_iterations << " ms.";
LOG(INFO) << "Average Backward pass: " << backward_time / 1000 /
FLAGS_iterations << " ms.";
LOG(INFO) << "Average Forward-Backward: " << total_timer.MilliSeconds() /
FLAGS_iterations << " ms.";
LOG(INFO) << "Total Time: " << total_timer.MilliSeconds() << " ms.";
LOG(INFO) << "*** Benchmark ends ***";
return 0;
}
RegisterBrewFunction(time);
int main(int argc, char** argv) {
// Print output to stderr (while still logging).
FLAGS_alsologtostderr = 1;
// Usage message.
gflags::SetUsageMessage("command line brew\n"
"usage: caffe <command> <args>\n\n"
"commands:\n"
" train train or finetune a model\n"
" test score a model\n"
" device_query show GPU diagnostic information\n"
" time benchmark model execution time");
// Run tool or show usage.
caffe::GlobalInit(&argc, &argv);
if (argc == 2) {
return GetBrewFunction(caffe::string(argv[1]))();
} else {
gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/caffe");
}
}
<commit_msg>print Python exceptions when using Python layer with the caffe tool<commit_after>#include <glog/logging.h>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include "boost/algorithm/string.hpp"
#include "caffe/caffe.hpp"
#ifdef WITH_PYTHON_LAYER
#include "boost/python.hpp"
namespace bp = boost::python;
#endif
using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::Timer;
using caffe::vector;
DEFINE_int32(gpu, -1,
"Run in GPU mode on given device ID.");
DEFINE_string(solver, "",
"The solver definition protocol buffer text file.");
DEFINE_string(model, "",
"The model definition protocol buffer text file..");
DEFINE_string(snapshot, "",
"Optional; the snapshot solver state to resume training.");
DEFINE_string(weights, "",
"Optional; the pretrained weights to initialize finetuning. "
"Cannot be set simultaneously with snapshot.");
DEFINE_int32(iterations, 50,
"The number of iterations to run.");
// A simple registry for caffe commands.
typedef int (*BrewFunction)();
typedef std::map<caffe::string, BrewFunction> BrewMap;
BrewMap g_brew_map;
#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \
public: /* NOLINT */ \
__Registerer_##func() { \
g_brew_map[#func] = &func; \
} \
}; \
__Registerer_##func g_registerer_##func; \
}
static BrewFunction GetBrewFunction(const caffe::string& name) {
if (g_brew_map.count(name)) {
return g_brew_map[name];
} else {
LOG(ERROR) << "Available caffe actions:";
for (BrewMap::iterator it = g_brew_map.begin();
it != g_brew_map.end(); ++it) {
LOG(ERROR) << "\t" << it->first;
}
LOG(FATAL) << "Unknown action: " << name;
return NULL; // not reachable, just to suppress old compiler warnings.
}
}
// caffe commands to call by
// caffe <command> <args>
//
// To add a command, define a function "int command()" and register it with
// RegisterBrewFunction(action);
// Device Query: show diagnostic information for a GPU device.
int device_query() {
CHECK_GT(FLAGS_gpu, -1) << "Need a device ID to query.";
LOG(INFO) << "Querying device ID = " << FLAGS_gpu;
caffe::Caffe::SetDevice(FLAGS_gpu);
caffe::Caffe::DeviceQuery();
return 0;
}
RegisterBrewFunction(device_query);
// Load the weights from the specified caffemodel(s) into the train and
// test nets.
void CopyLayers(caffe::Solver<float>* solver, const std::string& model_list) {
std::vector<std::string> model_names;
boost::split(model_names, model_list, boost::is_any_of(",") );
for (int i = 0; i < model_names.size(); ++i) {
LOG(INFO) << "Finetuning from " << model_names[i];
solver->net()->CopyTrainedLayersFrom(model_names[i]);
for (int j = 0; j < solver->test_nets().size(); ++j) {
solver->test_nets()[j]->CopyTrainedLayersFrom(model_names[i]);
}
}
}
// Train / Finetune a model.
int train() {
CHECK_GT(FLAGS_solver.size(), 0) << "Need a solver definition to train.";
CHECK(!FLAGS_snapshot.size() || !FLAGS_weights.size())
<< "Give a snapshot to resume training or weights to finetune "
"but not both.";
caffe::SolverParameter solver_param;
caffe::ReadProtoFromTextFileOrDie(FLAGS_solver, &solver_param);
// If the gpu flag is not provided, allow the mode and device to be set
// in the solver prototxt.
if (FLAGS_gpu < 0
&& solver_param.solver_mode() == caffe::SolverParameter_SolverMode_GPU) {
FLAGS_gpu = solver_param.device_id();
}
// Set device id and mode
if (FLAGS_gpu >= 0) {
LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
Caffe::SetDevice(FLAGS_gpu);
Caffe::set_mode(Caffe::GPU);
} else {
LOG(INFO) << "Use CPU.";
Caffe::set_mode(Caffe::CPU);
}
LOG(INFO) << "Starting Optimization";
shared_ptr<caffe::Solver<float> >
solver(caffe::GetSolver<float>(solver_param));
if (FLAGS_snapshot.size()) {
LOG(INFO) << "Resuming from " << FLAGS_snapshot;
solver->Solve(FLAGS_snapshot);
} else if (FLAGS_weights.size()) {
CopyLayers(&*solver, FLAGS_weights);
solver->Solve();
} else {
solver->Solve();
}
LOG(INFO) << "Optimization Done.";
return 0;
}
RegisterBrewFunction(train);
// Test: score a model.
int test() {
CHECK_GT(FLAGS_model.size(), 0) << "Need a model definition to score.";
CHECK_GT(FLAGS_weights.size(), 0) << "Need model weights to score.";
// Set device id and mode
if (FLAGS_gpu >= 0) {
LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
Caffe::SetDevice(FLAGS_gpu);
Caffe::set_mode(Caffe::GPU);
} else {
LOG(INFO) << "Use CPU.";
Caffe::set_mode(Caffe::CPU);
}
// Instantiate the caffe net.
Net<float> caffe_net(FLAGS_model, caffe::TEST);
caffe_net.CopyTrainedLayersFrom(FLAGS_weights);
LOG(INFO) << "Running for " << FLAGS_iterations << " iterations.";
vector<Blob<float>* > bottom_vec;
vector<int> test_score_output_id;
vector<float> test_score;
float loss = 0;
for (int i = 0; i < FLAGS_iterations; ++i) {
float iter_loss;
const vector<Blob<float>*>& result =
caffe_net.Forward(bottom_vec, &iter_loss);
loss += iter_loss;
int idx = 0;
for (int j = 0; j < result.size(); ++j) {
const float* result_vec = result[j]->cpu_data();
for (int k = 0; k < result[j]->count(); ++k, ++idx) {
const float score = result_vec[k];
if (i == 0) {
test_score.push_back(score);
test_score_output_id.push_back(j);
} else {
test_score[idx] += score;
}
const std::string& output_name = caffe_net.blob_names()[
caffe_net.output_blob_indices()[j]];
LOG(INFO) << "Batch " << i << ", " << output_name << " = " << score;
}
}
}
loss /= FLAGS_iterations;
LOG(INFO) << "Loss: " << loss;
for (int i = 0; i < test_score.size(); ++i) {
const std::string& output_name = caffe_net.blob_names()[
caffe_net.output_blob_indices()[test_score_output_id[i]]];
const float loss_weight =
caffe_net.blob_loss_weights()[caffe_net.output_blob_indices()[i]];
std::ostringstream loss_msg_stream;
const float mean_score = test_score[i] / FLAGS_iterations;
if (loss_weight) {
loss_msg_stream << " (* " << loss_weight
<< " = " << loss_weight * mean_score << " loss)";
}
LOG(INFO) << output_name << " = " << mean_score << loss_msg_stream.str();
}
return 0;
}
RegisterBrewFunction(test);
// Time: benchmark the execution time of a model.
int time() {
CHECK_GT(FLAGS_model.size(), 0) << "Need a model definition to time.";
// Set device id and mode
if (FLAGS_gpu >= 0) {
LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
Caffe::SetDevice(FLAGS_gpu);
Caffe::set_mode(Caffe::GPU);
} else {
LOG(INFO) << "Use CPU.";
Caffe::set_mode(Caffe::CPU);
}
// Instantiate the caffe net.
Net<float> caffe_net(FLAGS_model, caffe::TRAIN);
// Do a clean forward and backward pass, so that memory allocation are done
// and future iterations will be more stable.
LOG(INFO) << "Performing Forward";
// Note that for the speed benchmark, we will assume that the network does
// not take any input blobs.
float initial_loss;
caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
LOG(INFO) << "Initial loss: " << initial_loss;
LOG(INFO) << "Performing Backward";
caffe_net.Backward();
const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
const vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
const vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
const vector<vector<bool> >& bottom_need_backward =
caffe_net.bottom_need_backward();
LOG(INFO) << "*** Benchmark begins ***";
LOG(INFO) << "Testing for " << FLAGS_iterations << " iterations.";
Timer total_timer;
total_timer.Start();
Timer forward_timer;
Timer backward_timer;
Timer timer;
std::vector<double> forward_time_per_layer(layers.size(), 0.0);
std::vector<double> backward_time_per_layer(layers.size(), 0.0);
double forward_time = 0.0;
double backward_time = 0.0;
for (int j = 0; j < FLAGS_iterations; ++j) {
Timer iter_timer;
iter_timer.Start();
forward_timer.Start();
for (int i = 0; i < layers.size(); ++i) {
timer.Start();
layers[i]->Forward(bottom_vecs[i], top_vecs[i]);
forward_time_per_layer[i] += timer.MicroSeconds();
}
forward_time += forward_timer.MicroSeconds();
backward_timer.Start();
for (int i = layers.size() - 1; i >= 0; --i) {
timer.Start();
layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
bottom_vecs[i]);
backward_time_per_layer[i] += timer.MicroSeconds();
}
backward_time += backward_timer.MicroSeconds();
LOG(INFO) << "Iteration: " << j + 1 << " forward-backward time: "
<< iter_timer.MilliSeconds() << " ms.";
}
LOG(INFO) << "Average time per layer: ";
for (int i = 0; i < layers.size(); ++i) {
const caffe::string& layername = layers[i]->layer_param().name();
LOG(INFO) << std::setfill(' ') << std::setw(10) << layername <<
"\tforward: " << forward_time_per_layer[i] / 1000 /
FLAGS_iterations << " ms.";
LOG(INFO) << std::setfill(' ') << std::setw(10) << layername <<
"\tbackward: " << backward_time_per_layer[i] / 1000 /
FLAGS_iterations << " ms.";
}
total_timer.Stop();
LOG(INFO) << "Average Forward pass: " << forward_time / 1000 /
FLAGS_iterations << " ms.";
LOG(INFO) << "Average Backward pass: " << backward_time / 1000 /
FLAGS_iterations << " ms.";
LOG(INFO) << "Average Forward-Backward: " << total_timer.MilliSeconds() /
FLAGS_iterations << " ms.";
LOG(INFO) << "Total Time: " << total_timer.MilliSeconds() << " ms.";
LOG(INFO) << "*** Benchmark ends ***";
return 0;
}
RegisterBrewFunction(time);
int main(int argc, char** argv) {
// Print output to stderr (while still logging).
FLAGS_alsologtostderr = 1;
// Usage message.
gflags::SetUsageMessage("command line brew\n"
"usage: caffe <command> <args>\n\n"
"commands:\n"
" train train or finetune a model\n"
" test score a model\n"
" device_query show GPU diagnostic information\n"
" time benchmark model execution time");
// Run tool or show usage.
caffe::GlobalInit(&argc, &argv);
if (argc == 2) {
#ifdef WITH_PYTHON_LAYER
try {
#endif
return GetBrewFunction(caffe::string(argv[1]))();
#ifdef WITH_PYTHON_LAYER
} catch (bp::error_already_set) {
PyErr_Print();
return 1;
}
#endif
} else {
gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/caffe");
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file transaction.cpp
* @author Dmitrii Khokhlov <winsvega@mail.ru>
* @date 2015
* Transaaction test functions.
*/
#include "TestHelper.h"
using namespace std;
using namespace json_spirit;
using namespace dev;
using namespace dev::eth;
namespace dev { namespace test {
void doTransactionTests(json_spirit::mValue& _v, bool _fillin)
{
for (auto& i: _v.get_obj())
{
cerr << i.first << endl;
mObject& o = i.second.get_obj();
if (_fillin == false)
{
BOOST_REQUIRE(o.count("rlp") > 0);
Transaction txFromRlp;
try
{
bytes stream = importByteArray(o["rlp"].get_str());
RLP rlp(stream);
txFromRlp = Transaction(rlp.data(), CheckSignature::Sender);
if (!txFromRlp.signature().isValid())
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("transaction from RLP signature is invalid") );
}
catch(...)
{
BOOST_CHECK_MESSAGE(o.count("transaction") == 0, "A transaction object should not be defined because the RLP is invalid!");
continue;
}
BOOST_REQUIRE(o.count("transaction") > 0);
mObject tObj = o["transaction"].get_obj();
Transaction txFromFields(createRLPStreamFromTransactionFields(tObj).out(), CheckSignature::Sender);
//Check the fields restored from RLP to original fields
BOOST_CHECK_MESSAGE(txFromFields.data() == txFromRlp.data(), "Data in given RLP not matching the Transaction data!");
BOOST_CHECK_MESSAGE(txFromFields.value() == txFromRlp.value(), "Value in given RLP not matching the Transaction value!");
BOOST_CHECK_MESSAGE(txFromFields.gasPrice() == txFromRlp.gasPrice(), "GasPrice in given RLP not matching the Transaction gasPrice!");
BOOST_CHECK_MESSAGE(txFromFields.gas() == txFromRlp.gas(),"Gas in given RLP not matching the Transaction gas!");
BOOST_CHECK_MESSAGE(txFromFields.nonce() == txFromRlp.nonce(),"Nonce in given RLP not matching the Transaction nonce!");
BOOST_CHECK_MESSAGE(txFromFields.receiveAddress() == txFromRlp.receiveAddress(), "Receive address in given RLP not matching the Transaction 'to' address!");
BOOST_CHECK_MESSAGE(txFromFields.sender() == txFromRlp.sender(), "Transaction sender address in given RLP not matching the Transaction 'vrs' signature!");
BOOST_CHECK_MESSAGE(txFromFields == txFromRlp, "However, txFromFields != txFromRlp!");
BOOST_REQUIRE (o.count("sender") > 0);
Address addressReaded = Address(o["sender"].get_str());
BOOST_CHECK_MESSAGE(txFromFields.sender() == addressReaded || txFromRlp.sender() == addressReaded, "Signature address of sender does not match given sender address!");
}
else
{
BOOST_REQUIRE(o.count("transaction") > 0);
mObject tObj = o["transaction"].get_obj();
//Construct Rlp of the given transaction
RLPStream rlpStream = createRLPStreamFromTransactionFields(tObj);
o["rlp"] = "0x" + toHex(rlpStream.out());
try
{
Transaction txFromFields(rlpStream.out(), CheckSignature::Sender);
if (!txFromFields.signature().isValid())
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("transaction from RLP signature is invalid") );
o["sender"] = toString(txFromFields.sender());
}
catch(Exception const& _e)
{
cnote << "Transaction Exception: " << diagnostic_information(_e);
o.erase(o.find("transaction"));
}
}
}//for
}//doTransactionTests
} }// Namespace Close
BOOST_AUTO_TEST_SUITE(TransactionTests)
BOOST_AUTO_TEST_CASE(ttTransactionTest)
{
dev::test::executeTests("ttTransactionTest", "/TransactionTests", dev::test::doTransactionTests);
}
BOOST_AUTO_TEST_CASE(ttWrongRLPTransaction)
{
dev::test::executeTests("ttWrongRLPTransaction", "/TransactionTests", dev::test::doTransactionTests);
}
BOOST_AUTO_TEST_CASE(tt10mbDataField)
{
if (test::Options::get().bigData)
{
auto start = chrono::steady_clock::now();
dev::test::executeTests("tt10mbDataField", "/TransactionTests", dev::test::doTransactionTests);
auto end = chrono::steady_clock::now();
auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
cnote << "test duration: " << duration.count() << " milliseconds.\n";
}
}
BOOST_AUTO_TEST_CASE(ttCreateTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--createtest")
{
if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
{
cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n";
return;
}
try
{
cnote << "Populating tests...";
json_spirit::mValue v;
string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));
BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty.");
json_spirit::read_string(s, v);
dev::test::doTransactionTests(v, true);
writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));
}
catch (Exception const& _e)
{
BOOST_ERROR("Failed transaction test with Exception: " << diagnostic_information(_e));
}
catch (std::exception const& _e)
{
BOOST_ERROR("Failed transaction test with Exception: " << _e.what());
}
}
}
}
BOOST_AUTO_TEST_CASE(userDefinedFile)
{
dev::test::userDefinedTest("--singletest", dev::test::doTransactionTests);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Exceptions<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file transaction.cpp
* @author Dmitrii Khokhlov <winsvega@mail.ru>
* @date 2015
* Transaaction test functions.
*/
#include "TestHelper.h"
using namespace std;
using namespace json_spirit;
using namespace dev;
using namespace dev::eth;
namespace dev { namespace test {
void doTransactionTests(json_spirit::mValue& _v, bool _fillin)
{
for (auto& i: _v.get_obj())
{
cerr << i.first << endl;
mObject& o = i.second.get_obj();
if (_fillin == false)
{
BOOST_REQUIRE(o.count("rlp") > 0);
Transaction txFromRlp;
try
{
bytes stream = importByteArray(o["rlp"].get_str());
RLP rlp(stream);
txFromRlp = Transaction(rlp.data(), CheckSignature::Sender);
if (!txFromRlp.signature().isValid())
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("transaction from RLP signature is invalid") );
}
catch(Exception const& _e)
{
cnote << i.first;
cnote << "Transaction Exception: " << diagnostic_information(_e);
BOOST_CHECK_MESSAGE(o.count("transaction") == 0, "A transaction object should not be defined because the RLP is invalid!");
continue;
}
catch(...)
{
BOOST_CHECK_MESSAGE(o.count("transaction") == 0, "A transaction object should not be defined because the RLP is invalid!");
continue;
}
BOOST_REQUIRE(o.count("transaction") > 0);
mObject tObj = o["transaction"].get_obj();
Transaction txFromFields(createRLPStreamFromTransactionFields(tObj).out(), CheckSignature::Sender);
//Check the fields restored from RLP to original fields
BOOST_CHECK_MESSAGE(txFromFields.data() == txFromRlp.data(), "Data in given RLP not matching the Transaction data!");
BOOST_CHECK_MESSAGE(txFromFields.value() == txFromRlp.value(), "Value in given RLP not matching the Transaction value!");
BOOST_CHECK_MESSAGE(txFromFields.gasPrice() == txFromRlp.gasPrice(), "GasPrice in given RLP not matching the Transaction gasPrice!");
BOOST_CHECK_MESSAGE(txFromFields.gas() == txFromRlp.gas(),"Gas in given RLP not matching the Transaction gas!");
BOOST_CHECK_MESSAGE(txFromFields.nonce() == txFromRlp.nonce(),"Nonce in given RLP not matching the Transaction nonce!");
BOOST_CHECK_MESSAGE(txFromFields.receiveAddress() == txFromRlp.receiveAddress(), "Receive address in given RLP not matching the Transaction 'to' address!");
BOOST_CHECK_MESSAGE(txFromFields.sender() == txFromRlp.sender(), "Transaction sender address in given RLP not matching the Transaction 'vrs' signature!");
BOOST_CHECK_MESSAGE(txFromFields == txFromRlp, "However, txFromFields != txFromRlp!");
BOOST_REQUIRE (o.count("sender") > 0);
Address addressReaded = Address(o["sender"].get_str());
BOOST_CHECK_MESSAGE(txFromFields.sender() == addressReaded || txFromRlp.sender() == addressReaded, "Signature address of sender does not match given sender address!");
}
else
{
BOOST_REQUIRE(o.count("transaction") > 0);
mObject tObj = o["transaction"].get_obj();
//Construct Rlp of the given transaction
RLPStream rlpStream = createRLPStreamFromTransactionFields(tObj);
o["rlp"] = "0x" + toHex(rlpStream.out());
try
{
Transaction txFromFields(rlpStream.out(), CheckSignature::Sender);
if (!txFromFields.signature().isValid())
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("transaction from RLP signature is invalid") );
o["sender"] = toString(txFromFields.sender());
}
catch(Exception const& _e)
{
cnote << "Transaction Exception: " << diagnostic_information(_e);
o.erase(o.find("transaction"));
}
}
}//for
}//doTransactionTests
} }// Namespace Close
BOOST_AUTO_TEST_SUITE(TransactionTests)
BOOST_AUTO_TEST_CASE(ttTransactionTest)
{
dev::test::executeTests("ttTransactionTest", "/TransactionTests", dev::test::doTransactionTests);
}
BOOST_AUTO_TEST_CASE(ttWrongRLPTransaction)
{
dev::test::executeTests("ttWrongRLPTransaction", "/TransactionTests", dev::test::doTransactionTests);
}
BOOST_AUTO_TEST_CASE(tt10mbDataField)
{
if (test::Options::get().bigData)
{
auto start = chrono::steady_clock::now();
dev::test::executeTests("tt10mbDataField", "/TransactionTests", dev::test::doTransactionTests);
auto end = chrono::steady_clock::now();
auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
cnote << "test duration: " << duration.count() << " milliseconds.\n";
}
}
BOOST_AUTO_TEST_CASE(ttCreateTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--createtest")
{
if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
{
cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n";
return;
}
try
{
cnote << "Populating tests...";
json_spirit::mValue v;
string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));
BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty.");
json_spirit::read_string(s, v);
dev::test::doTransactionTests(v, true);
writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));
}
catch (Exception const& _e)
{
BOOST_ERROR("Failed transaction test with Exception: " << diagnostic_information(_e));
}
catch (std::exception const& _e)
{
BOOST_ERROR("Failed transaction test with Exception: " << _e.what());
}
}
}
}
BOOST_AUTO_TEST_CASE(userDefinedFile)
{
dev::test::userDefinedTest("--singletest", dev::test::doTransactionTests);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "base/basictypes.h"
#include "WTF/ListHashSet.h"
#include "WTF/Vector.h"
#include "SkiaFontWin.h"
#include "SkCanvas.h"
#include "SkPaint.h"
namespace WebCore {
namespace {
struct CachedOutlineKey {
CachedOutlineKey() : font(NULL), glyph(0), path(NULL) {}
CachedOutlineKey(HFONT f, WORD g) : font(f), glyph(g), path(NULL) {}
HFONT font;
WORD glyph;
// The lifetime of this pointer is managed externally to this class. Be sure
// to call DeleteOutline to remove items.
SkPath* path;
};
const bool operator==(const CachedOutlineKey& a, const CachedOutlineKey& b)
{
return a.font == b.font && a.glyph == b.glyph;
}
struct CachedOutlineKeyHash {
static unsigned hash(const CachedOutlineKey& key)
{
return bit_cast<unsigned>(key.font) + key.glyph;
}
static unsigned equal(const CachedOutlineKey& a,
const CachedOutlineKey& b)
{
return a.font == b.font && a.glyph == b.glyph;
}
static const bool safeToCompareToEmptyOrDeleted = true;
};
typedef ListHashSet<CachedOutlineKey, CachedOutlineKeyHash> OutlineCache;
OutlineCache outlineCache;
// The global number of glyph outlines we'll cache.
const int outlineCacheSize = 256;
inline FIXED SkScalarToFIXED(SkScalar x)
{
return bit_cast<FIXED>(SkScalarToFixed(x));
}
inline SkScalar FIXEDToSkScalar(FIXED fixed)
{
return SkFixedToScalar(bit_cast<SkFixed>(fixed));
}
// Removes the given key from the cached outlines, also deleting the path.
void DeleteOutline(OutlineCache::iterator deleteMe)
{
delete deleteMe->path;
outlineCache.remove(deleteMe);
}
void AddPolyCurveToPath(const TTPOLYCURVE* polyCurve, SkPath* path)
{
switch (polyCurve->wType) {
case TT_PRIM_LINE:
for (WORD i = 0; i < polyCurve->cpfx; i++) {
path->lineTo(FIXEDToSkScalar(polyCurve->apfx[i].x),
-FIXEDToSkScalar(polyCurve->apfx[i].y));
}
break;
case TT_PRIM_QSPLINE:
// FIXME(brettw) doesn't this duplicate points if we do the loop > once?
for (WORD i = 0; i < polyCurve->cpfx - 1; i++) {
SkScalar bx = FIXEDToSkScalar(polyCurve->apfx[i].x);
SkScalar by = FIXEDToSkScalar(polyCurve->apfx[i].y);
SkScalar cx = FIXEDToSkScalar(polyCurve->apfx[i + 1].x);
SkScalar cy = FIXEDToSkScalar(polyCurve->apfx[i + 1].y);
if (i < polyCurve->cpfx - 2) {
// We're not the last point, compute C.
cx = SkScalarAve(bx, cx);
cy = SkScalarAve(by, cy);
}
// Need to flip the y coordinates since the font's coordinate system is
// flipped from ours vertically.
path->quadTo(bx, -by, cx, -cy);
}
break;
case TT_PRIM_CSPLINE:
// FIXME
break;
}
}
// Fills the given SkPath with the outline for the given glyph index. The font
// currently selected into the given DC is used. Returns true on success.
bool GetPathForGlyph(HDC dc, WORD glyph, SkPath* path)
{
char buffer[4096];
GLYPHMETRICS gm;
MAT2 mat = {{0, 1}, {0, 0}, {0, 0}, {0, 1}}; // Each one is (fract,value).
DWORD totalSize = GetGlyphOutlineW(dc, glyph, GGO_GLYPH_INDEX | GGO_NATIVE,
&gm, arraysize(buffer), buffer, &mat);
if (totalSize == GDI_ERROR)
return false;
const char* curGlyph = buffer;
const char* endGlyph = &buffer[totalSize];
while (curGlyph < endGlyph) {
const TTPOLYGONHEADER* polyHeader =
reinterpret_cast<const TTPOLYGONHEADER*>(curGlyph);
path->moveTo(FIXEDToSkScalar(polyHeader->pfxStart.x),
-FIXEDToSkScalar(polyHeader->pfxStart.y));
const char* curPoly = curGlyph + sizeof(TTPOLYGONHEADER);
const char* endPoly = curGlyph + polyHeader->cb;
while (curPoly < endPoly) {
const TTPOLYCURVE* polyCurve =
reinterpret_cast<const TTPOLYCURVE*>(curPoly);
AddPolyCurveToPath(polyCurve, path);
curPoly += sizeof(WORD) * 2 + sizeof(POINTFX) * polyCurve->cpfx;
}
curGlyph += polyHeader->cb;
}
path->close();
return true;
}
// Returns a SkPath corresponding to the give glyph in the given font. The font
// should be selected into the given DC. The returned path is owned by the
// hashtable. Returns NULL on error.
const SkPath* GetCachedPathForGlyph(HDC hdc, HFONT font, WORD glyph)
{
CachedOutlineKey key(font, glyph);
OutlineCache::iterator found = outlineCache.find(key);
if (found != outlineCache.end()) {
// Keep in MRU order by removing & reinserting the value.
key = *found;
outlineCache.remove(found);
outlineCache.add(key);
return key.path;
}
key.path = new SkPath;
if (!GetPathForGlyph(hdc, glyph, key.path))
return NULL;
if (outlineCache.size() > outlineCacheSize) {
// The cache is too big, find the oldest value (first in the list).
DeleteOutline(outlineCache.begin());
}
outlineCache.add(key);
return key.path;
}
} // namespace
bool SkiaDrawText(HFONT hfont,
SkCanvas* canvas,
const SkPoint& point,
SkPaint* paint,
const WORD* glyphs,
const int* advances,
int num_glyphs)
{
HDC dc = GetDC(0);
HGDIOBJ old_font = SelectObject(dc, hfont);
canvas->save();
canvas->translate(point.fX, point.fY);
for (int i = 0; i < num_glyphs; i++) {
const SkPath* path = GetCachedPathForGlyph(dc, hfont, glyphs[i]);
if (!path)
return false;
canvas->drawPath(*path, *paint);
canvas->translate(advances[i], 0);
}
canvas->restore();
SelectObject(dc, old_font);
ReleaseDC(0, dc);
return true;
}
/* TODO(brettw) finish this implementation
bool SkiaDrawComplexText(HFONT font,
SkCanvas* canvas,
const SkPoint& point,
SkPaint* paint
UINT fuOptions,
const SCRIPT_ANALYSIS* psa,
const WORD* pwGlyphs,
int cGlyphs,
const int* advances,
const int* justifies,
const GOFFSET* glyph_offsets)
{
HDC dc = GetDC(0);
HGDIOBJ old_font = SelectObject(dc, hfont);
canvas->save();
canvas->translate(point.fX, point.fY);
for (int i = 0; i < cGlyphs; i++) {
canvas->translate(glyph_offsets[i].du, glyph_offsets[i].dv);
// Undo the offset for this glyph.
canvas->translate(-glyph_offsets[i].du, -glyph_offsets[i].dv);
// And advance to where we're drawing the next one. We use the justifies
// run since that is the justified advances for each character, rather than
// the adnvaces one.
canvas->translate(justifies[i], 0);
}
canvas->restore();
SelectObject(dc, old_font);
ReleaseDC(0, dc);
}*/
void RemoveFontFromSkiaFontWinCache(HFONT hfont)
{
// ListHashSet isn't the greatest structure for deleting stuff out of, but
// removing entries will be relatively rare (we don't remove fonts much, nor
// do we draw out own glyphs using these routines much either).
//
// We keep a list of all glyphs we're removing which we do in a separate
// pass.
Vector<CachedOutlineKey> outlinesToDelete;
for (OutlineCache::iterator i = outlineCache.begin();
i != outlineCache.end(); ++i)
outlinesToDelete.append(*i);
for (Vector<CachedOutlineKey>::iterator i = outlinesToDelete.begin();
i != outlinesToDelete.end(); ++i)
DeleteOutline(outlineCache.find(*i));
}
} // namespace WebCore
<commit_msg>De-basify SkiaFontwin<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "WTF/ListHashSet.h"
#include "WTF/Vector.h"
#include "SkiaFontWin.h"
#include "SkCanvas.h"
#include "SkPaint.h"
namespace WebCore {
namespace {
struct CachedOutlineKey {
CachedOutlineKey() : font(NULL), glyph(0), path(NULL) {}
CachedOutlineKey(HFONT f, WORD g) : font(f), glyph(g), path(NULL) {}
HFONT font;
WORD glyph;
// The lifetime of this pointer is managed externally to this class. Be sure
// to call DeleteOutline to remove items.
SkPath* path;
};
const bool operator==(const CachedOutlineKey& a, const CachedOutlineKey& b)
{
return a.font == b.font && a.glyph == b.glyph;
}
struct CachedOutlineKeyHash {
static unsigned hash(const CachedOutlineKey& key)
{
unsigned keyBytes;
memcpy(&keyBytes, &key.font, sizeof(unsigned));
return keyBytes + key.glyph;
}
static unsigned equal(const CachedOutlineKey& a,
const CachedOutlineKey& b)
{
return a.font == b.font && a.glyph == b.glyph;
}
static const bool safeToCompareToEmptyOrDeleted = true;
};
typedef ListHashSet<CachedOutlineKey, CachedOutlineKeyHash> OutlineCache;
OutlineCache outlineCache;
// The global number of glyph outlines we'll cache.
const int outlineCacheSize = 256;
inline FIXED SkScalarToFIXED(SkScalar x)
{
FIXED fixed;
SkFixed skFixed = SkScalarToFixed(x);
memcpy(&fixed, &skFixed, sizeof(FIXED));
return fixed;
}
inline SkScalar FIXEDToSkScalar(FIXED fixed)
{
SkFixed skFixed;
memcpy(&skFixed, &fixed, sizeof(SkFixed));
return SkFixedToScalar(skFixed);
}
// Removes the given key from the cached outlines, also deleting the path.
void DeleteOutline(OutlineCache::iterator deleteMe)
{
delete deleteMe->path;
outlineCache.remove(deleteMe);
}
void AddPolyCurveToPath(const TTPOLYCURVE* polyCurve, SkPath* path)
{
switch (polyCurve->wType) {
case TT_PRIM_LINE:
for (WORD i = 0; i < polyCurve->cpfx; i++) {
path->lineTo(FIXEDToSkScalar(polyCurve->apfx[i].x),
-FIXEDToSkScalar(polyCurve->apfx[i].y));
}
break;
case TT_PRIM_QSPLINE:
// FIXME(brettw) doesn't this duplicate points if we do the loop > once?
for (WORD i = 0; i < polyCurve->cpfx - 1; i++) {
SkScalar bx = FIXEDToSkScalar(polyCurve->apfx[i].x);
SkScalar by = FIXEDToSkScalar(polyCurve->apfx[i].y);
SkScalar cx = FIXEDToSkScalar(polyCurve->apfx[i + 1].x);
SkScalar cy = FIXEDToSkScalar(polyCurve->apfx[i + 1].y);
if (i < polyCurve->cpfx - 2) {
// We're not the last point, compute C.
cx = SkScalarAve(bx, cx);
cy = SkScalarAve(by, cy);
}
// Need to flip the y coordinates since the font's coordinate system is
// flipped from ours vertically.
path->quadTo(bx, -by, cx, -cy);
}
break;
case TT_PRIM_CSPLINE:
// FIXME
break;
}
}
// The size of the glyph outline buffer.
const int glyphPathBufferSize = 4096;
// Fills the given SkPath with the outline for the given glyph index. The font
// currently selected into the given DC is used. Returns true on success.
bool GetPathForGlyph(HDC dc, WORD glyph, SkPath* path)
{
char buffer[glyphPathBufferSize];
GLYPHMETRICS gm;
MAT2 mat = {{0, 1}, {0, 0}, {0, 0}, {0, 1}}; // Each one is (fract,value).
DWORD totalSize = GetGlyphOutlineW(dc, glyph, GGO_GLYPH_INDEX | GGO_NATIVE,
&gm, glyphPathBufferSize, buffer, &mat);
if (totalSize == GDI_ERROR)
return false;
const char* curGlyph = buffer;
const char* endGlyph = &buffer[totalSize];
while (curGlyph < endGlyph) {
const TTPOLYGONHEADER* polyHeader =
reinterpret_cast<const TTPOLYGONHEADER*>(curGlyph);
path->moveTo(FIXEDToSkScalar(polyHeader->pfxStart.x),
-FIXEDToSkScalar(polyHeader->pfxStart.y));
const char* curPoly = curGlyph + sizeof(TTPOLYGONHEADER);
const char* endPoly = curGlyph + polyHeader->cb;
while (curPoly < endPoly) {
const TTPOLYCURVE* polyCurve =
reinterpret_cast<const TTPOLYCURVE*>(curPoly);
AddPolyCurveToPath(polyCurve, path);
curPoly += sizeof(WORD) * 2 + sizeof(POINTFX) * polyCurve->cpfx;
}
curGlyph += polyHeader->cb;
}
path->close();
return true;
}
// Returns a SkPath corresponding to the give glyph in the given font. The font
// should be selected into the given DC. The returned path is owned by the
// hashtable. Returns NULL on error.
const SkPath* GetCachedPathForGlyph(HDC hdc, HFONT font, WORD glyph)
{
CachedOutlineKey key(font, glyph);
OutlineCache::iterator found = outlineCache.find(key);
if (found != outlineCache.end()) {
// Keep in MRU order by removing & reinserting the value.
key = *found;
outlineCache.remove(found);
outlineCache.add(key);
return key.path;
}
key.path = new SkPath;
if (!GetPathForGlyph(hdc, glyph, key.path))
return NULL;
if (outlineCache.size() > outlineCacheSize) {
// The cache is too big, find the oldest value (first in the list).
DeleteOutline(outlineCache.begin());
}
outlineCache.add(key);
return key.path;
}
} // namespace
bool SkiaDrawText(HFONT hfont,
SkCanvas* canvas,
const SkPoint& point,
SkPaint* paint,
const WORD* glyphs,
const int* advances,
int num_glyphs)
{
HDC dc = GetDC(0);
HGDIOBJ old_font = SelectObject(dc, hfont);
canvas->save();
canvas->translate(point.fX, point.fY);
for (int i = 0; i < num_glyphs; i++) {
const SkPath* path = GetCachedPathForGlyph(dc, hfont, glyphs[i]);
if (!path)
return false;
canvas->drawPath(*path, *paint);
canvas->translate(advances[i], 0);
}
canvas->restore();
SelectObject(dc, old_font);
ReleaseDC(0, dc);
return true;
}
/* TODO(brettw) finish this implementation
bool SkiaDrawComplexText(HFONT font,
SkCanvas* canvas,
const SkPoint& point,
SkPaint* paint
UINT fuOptions,
const SCRIPT_ANALYSIS* psa,
const WORD* pwGlyphs,
int cGlyphs,
const int* advances,
const int* justifies,
const GOFFSET* glyph_offsets)
{
HDC dc = GetDC(0);
HGDIOBJ old_font = SelectObject(dc, hfont);
canvas->save();
canvas->translate(point.fX, point.fY);
for (int i = 0; i < cGlyphs; i++) {
canvas->translate(glyph_offsets[i].du, glyph_offsets[i].dv);
// Undo the offset for this glyph.
canvas->translate(-glyph_offsets[i].du, -glyph_offsets[i].dv);
// And advance to where we're drawing the next one. We use the justifies
// run since that is the justified advances for each character, rather than
// the adnvaces one.
canvas->translate(justifies[i], 0);
}
canvas->restore();
SelectObject(dc, old_font);
ReleaseDC(0, dc);
}*/
void RemoveFontFromSkiaFontWinCache(HFONT hfont)
{
// ListHashSet isn't the greatest structure for deleting stuff out of, but
// removing entries will be relatively rare (we don't remove fonts much, nor
// do we draw out own glyphs using these routines much either).
//
// We keep a list of all glyphs we're removing which we do in a separate
// pass.
Vector<CachedOutlineKey> outlinesToDelete;
for (OutlineCache::iterator i = outlineCache.begin();
i != outlineCache.end(); ++i)
outlinesToDelete.append(*i);
for (Vector<CachedOutlineKey>::iterator i = outlinesToDelete.begin();
i != outlinesToDelete.end(); ++i)
DeleteOutline(outlineCache.find(*i));
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/gtk/extensions/native_app_window_gtk.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/gtk/extensions/extension_keybinding_registry_gtk.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/gtk/gtk_window_util.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/base/x/active_window_watcher_x.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/rect.h"
namespace {
// The timeout in milliseconds before we'll get the true window position with
// gtk_window_get_position() after the last GTK configure-event signal.
const int kDebounceTimeoutMilliseconds = 100;
} // namespace
NativeAppWindowGtk::NativeAppWindowGtk(ShellWindow* shell_window,
const ShellWindow::CreateParams& params)
: shell_window_(shell_window),
window_(NULL),
state_(GDK_WINDOW_STATE_WITHDRAWN),
is_active_(false),
content_thinks_its_fullscreen_(false),
frameless_(params.frame == ShellWindow::FRAME_NONE) {
window_ = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
gfx::NativeView native_view =
web_contents()->GetView()->GetNativeView();
gtk_container_add(GTK_CONTAINER(window_), native_view);
if (params.bounds.x() != INT_MIN && params.bounds.y() != INT_MIN)
gtk_window_move(window_, params.bounds.x(), params.bounds.y());
// This is done to avoid a WM "feature" where setting the window size to
// the monitor size causes the WM to set the EWMH for full screen mode.
if (frameless_ &&
gtk_window_util::BoundsMatchMonitorSize(window_, params.bounds)) {
gtk_window_set_default_size(
window_, params.bounds.width(), params.bounds.height() - 1);
} else {
gtk_window_set_default_size(
window_, params.bounds.width(), params.bounds.height());
}
// make sure bounds_ and restored_bounds_ have correct values until we
// get our first configure-event
bounds_ = restored_bounds_ = params.bounds;
gint x, y;
gtk_window_get_position(window_, &x, &y);
bounds_.set_origin(gfx::Point(x, y));
// Hide titlebar when {frame: 'none'} specified on ShellWindow.
if (frameless_)
gtk_window_set_decorated(window_, false);
int min_width = params.minimum_size.width();
int min_height = params.minimum_size.height();
int max_width = params.maximum_size.width();
int max_height = params.maximum_size.height();
GdkGeometry hints;
int hints_mask = 0;
if (min_width || min_height) {
hints.min_height = min_height;
hints.min_width = min_width;
hints_mask |= GDK_HINT_MIN_SIZE;
}
if (max_width || max_height) {
hints.max_height = max_height ? max_height : G_MAXINT;
hints.max_width = max_width ? max_width : G_MAXINT;
hints_mask |= GDK_HINT_MAX_SIZE;
}
if (hints_mask) {
gtk_window_set_geometry_hints(
window_,
GTK_WIDGET(window_),
&hints,
static_cast<GdkWindowHints>(hints_mask));
}
// In some (older) versions of compiz, raising top-level windows when they
// are partially off-screen causes them to get snapped back on screen, not
// always even on the current virtual desktop. If we are running under
// compiz, suppress such raises, as they are not necessary in compiz anyway.
if (ui::GuessWindowManager() == ui::WM_COMPIZ)
suppress_window_raise_ = true;
gtk_window_set_title(window_, extension()->name().c_str());
gtk_window_util::SetWindowCustomClass(window_,
web_app::GetWMClassFromAppName(extension()->name()));
g_signal_connect(window_, "delete-event",
G_CALLBACK(OnMainWindowDeleteEventThunk), this);
g_signal_connect(window_, "configure-event",
G_CALLBACK(OnConfigureThunk), this);
g_signal_connect(window_, "window-state-event",
G_CALLBACK(OnWindowStateThunk), this);
if (frameless_) {
g_signal_connect(window_, "button-press-event",
G_CALLBACK(OnButtonPressThunk), this);
}
// Add the keybinding registry.
extension_keybinding_registry_.reset(new ExtensionKeybindingRegistryGtk(
shell_window_->profile(),
window_,
extensions::ExtensionKeybindingRegistry::PLATFORM_APPS_ONLY,
shell_window_));
ui::ActiveWindowWatcherX::AddObserver(this);
}
NativeAppWindowGtk::~NativeAppWindowGtk() {
ui::ActiveWindowWatcherX::RemoveObserver(this);
}
bool NativeAppWindowGtk::IsActive() const {
if (ui::ActiveWindowWatcherX::WMSupportsActivation())
return is_active_;
// This still works even though we don't get the activation notification.
return gtk_window_is_active(window_);
}
bool NativeAppWindowGtk::IsMaximized() const {
return (state_ & GDK_WINDOW_STATE_MAXIMIZED);
}
bool NativeAppWindowGtk::IsMinimized() const {
return (state_ & GDK_WINDOW_STATE_ICONIFIED);
}
bool NativeAppWindowGtk::IsFullscreen() const {
return false;
}
gfx::NativeWindow NativeAppWindowGtk::GetNativeWindow() {
return window_;
}
gfx::Rect NativeAppWindowGtk::GetRestoredBounds() const {
return restored_bounds_;
}
gfx::Rect NativeAppWindowGtk::GetBounds() const {
return bounds_;
}
void NativeAppWindowGtk::Show() {
gtk_window_present(window_);
}
void NativeAppWindowGtk::ShowInactive() {
gtk_window_set_focus_on_map(window_, false);
gtk_widget_show(GTK_WIDGET(window_));
}
void NativeAppWindowGtk::Hide() {
gtk_widget_hide(GTK_WIDGET(window_));
}
void NativeAppWindowGtk::Close() {
shell_window_->OnNativeWindowChanged();
// Cancel any pending callback from the window configure debounce timer.
window_configure_debounce_timer_.Stop();
GtkWidget* window = GTK_WIDGET(window_);
// To help catch bugs in any event handlers that might get fired during the
// destruction, set window_ to NULL before any handlers will run.
window_ = NULL;
// OnNativeClose does a delete this so no other members should
// be accessed after. gtk_widget_destroy is safe (and must
// be last).
shell_window_->OnNativeClose();
gtk_widget_destroy(window);
}
void NativeAppWindowGtk::Activate() {
gtk_window_present(window_);
}
void NativeAppWindowGtk::Deactivate() {
gdk_window_lower(gtk_widget_get_window(GTK_WIDGET(window_)));
}
void NativeAppWindowGtk::Maximize() {
gtk_window_maximize(window_);
}
void NativeAppWindowGtk::Minimize() {
gtk_window_iconify(window_);
}
void NativeAppWindowGtk::Restore() {
if (IsMaximized())
gtk_window_unmaximize(window_);
else if (IsMinimized())
gtk_window_deiconify(window_);
}
void NativeAppWindowGtk::SetBounds(const gfx::Rect& bounds) {
gtk_window_move(window_, bounds.x(), bounds.y());
gtk_window_util::SetWindowSize(window_,
gfx::Size(bounds.width(), bounds.height()));
}
void NativeAppWindowGtk::FlashFrame(bool flash) {
gtk_window_set_urgency_hint(window_, flash);
}
bool NativeAppWindowGtk::IsAlwaysOnTop() const {
return false;
}
gfx::Insets NativeAppWindowGtk::GetFrameInsets() const {
if (frameless_)
return gfx::Insets();
GdkWindow* gdk_window = gtk_widget_get_window(GTK_WIDGET(window_));
if (!gdk_window)
return gfx::Insets();
gint current_width = 0;
gint current_height = 0;
gtk_window_get_size(window_, ¤t_width, ¤t_height);
gint current_x = 0;
gint current_y = 0;
gdk_window_get_position(gdk_window, ¤t_x, ¤t_y);
GdkRectangle rect_with_decorations = {0};
gdk_window_get_frame_extents(gdk_window,
&rect_with_decorations);
int left_inset = current_x - rect_with_decorations.x;
int top_inset = current_y - rect_with_decorations.y;
return gfx::Insets(
top_inset,
left_inset,
rect_with_decorations.height - current_height - top_inset,
rect_with_decorations.width - current_width - left_inset);
}
void NativeAppWindowGtk::ActiveWindowChanged(GdkWindow* active_window) {
// Do nothing if we're in the process of closing the browser window.
if (!window_)
return;
is_active_ = gtk_widget_get_window(GTK_WIDGET(window_)) == active_window;
}
// Callback for the delete event. This event is fired when the user tries to
// close the window (e.g., clicking on the X in the window manager title bar).
gboolean NativeAppWindowGtk::OnMainWindowDeleteEvent(GtkWidget* widget,
GdkEvent* event) {
Close();
// Return true to prevent the GTK window from being destroyed. Close will
// destroy it for us.
return TRUE;
}
gboolean NativeAppWindowGtk::OnConfigure(GtkWidget* widget,
GdkEventConfigure* event) {
// We update |bounds_| but not |restored_bounds_| here. The latter needs
// to be updated conditionally when the window is non-maximized and non-
// fullscreen, but whether those state updates have been processed yet is
// window-manager specific. We update |restored_bounds_| in the debounced
// handler below, after the window state has been updated.
bounds_.SetRect(event->x, event->y, event->width, event->height);
// The GdkEventConfigure* we get here doesn't have quite the right
// coordinates though (they're relative to the drawable window area, rather
// than any window manager decorations, if enabled), so we need to call
// gtk_window_get_position() to get the right values. (Otherwise session
// restore, if enabled, will restore windows to incorrect positions.) That's
// a round trip to the X server though, so we set a debounce timer and only
// call it (in OnDebouncedBoundsChanged() below) after we haven't seen a
// reconfigure event in a short while.
// We don't use Reset() because the timer may not yet be running.
// (In that case Stop() is a no-op.)
window_configure_debounce_timer_.Stop();
window_configure_debounce_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds), this,
&NativeAppWindowGtk::OnDebouncedBoundsChanged);
return FALSE;
}
void NativeAppWindowGtk::OnDebouncedBoundsChanged() {
gtk_window_util::UpdateWindowPosition(this, &bounds_, &restored_bounds_);
shell_window_->OnNativeWindowChanged();
}
gboolean NativeAppWindowGtk::OnWindowState(GtkWidget* sender,
GdkEventWindowState* event) {
state_ = event->new_window_state;
if (content_thinks_its_fullscreen_ &&
!(state_ & GDK_WINDOW_STATE_FULLSCREEN)) {
content_thinks_its_fullscreen_ = false;
content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
if (rvh)
rvh->ExitFullscreen();
}
return FALSE;
}
gboolean NativeAppWindowGtk::OnButtonPress(GtkWidget* widget,
GdkEventButton* event) {
if (draggable_region_ && draggable_region_->contains(event->x, event->y)) {
if (event->button == 1) {
if (GDK_BUTTON_PRESS == event->type) {
if (!suppress_window_raise_)
gdk_window_raise(GTK_WIDGET(widget)->window);
return gtk_window_util::HandleTitleBarLeftMousePress(
GTK_WINDOW(widget), bounds_, event);
} else if (GDK_2BUTTON_PRESS == event->type) {
bool is_maximized = gdk_window_get_state(GTK_WIDGET(widget)->window) &
GDK_WINDOW_STATE_MAXIMIZED;
if (is_maximized) {
gtk_window_util::UnMaximize(GTK_WINDOW(widget),
bounds_, restored_bounds_);
} else {
gtk_window_maximize(GTK_WINDOW(widget));
}
return TRUE;
}
} else if (event->button == 2) {
gdk_window_lower(GTK_WIDGET(widget)->window);
return TRUE;
}
}
return FALSE;
}
void NativeAppWindowGtk::SetFullscreen(bool fullscreen) {
content_thinks_its_fullscreen_ = fullscreen;
if (fullscreen)
gtk_window_fullscreen(window_);
else
gtk_window_unfullscreen(window_);
}
bool NativeAppWindowGtk::IsFullscreenOrPending() const {
return content_thinks_its_fullscreen_;
}
void NativeAppWindowGtk::UpdateWindowIcon() {
Profile* profile = shell_window_->profile();
gfx::Image app_icon = shell_window_->app_icon();
if (!app_icon.IsEmpty())
gtk_util::SetWindowIcon(window_, profile, app_icon.ToGdkPixbuf());
else
gtk_util::SetWindowIcon(window_, profile);
}
void NativeAppWindowGtk::UpdateWindowTitle() {
string16 title = shell_window_->GetTitle();
gtk_window_set_title(window_, UTF16ToUTF8(title).c_str());
}
void NativeAppWindowGtk::HandleKeyboardEvent(
const content::NativeWebKeyboardEvent& event) {
// No-op.
}
void NativeAppWindowGtk::UpdateDraggableRegions(
const std::vector<extensions::DraggableRegion>& regions) {
// Draggable region is not supported for non-frameless window.
if (!frameless_)
return;
draggable_region_.reset(ShellWindow::RawDraggableRegionsToSkRegion(regions));
}
// static
NativeAppWindow* NativeAppWindow::Create(
ShellWindow* shell_window,
const ShellWindow::CreateParams& params) {
return new NativeAppWindowGtk(shell_window, params);
}
<commit_msg>On Linux, Chrome App windows now set their window class to match the StartupWMClass field of the app shortcuts.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/gtk/extensions/native_app_window_gtk.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/gtk/extensions/extension_keybinding_registry_gtk.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/gtk/gtk_window_util.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/base/x/active_window_watcher_x.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/rect.h"
namespace {
// The timeout in milliseconds before we'll get the true window position with
// gtk_window_get_position() after the last GTK configure-event signal.
const int kDebounceTimeoutMilliseconds = 100;
} // namespace
NativeAppWindowGtk::NativeAppWindowGtk(ShellWindow* shell_window,
const ShellWindow::CreateParams& params)
: shell_window_(shell_window),
window_(NULL),
state_(GDK_WINDOW_STATE_WITHDRAWN),
is_active_(false),
content_thinks_its_fullscreen_(false),
frameless_(params.frame == ShellWindow::FRAME_NONE) {
window_ = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
gfx::NativeView native_view =
web_contents()->GetView()->GetNativeView();
gtk_container_add(GTK_CONTAINER(window_), native_view);
if (params.bounds.x() != INT_MIN && params.bounds.y() != INT_MIN)
gtk_window_move(window_, params.bounds.x(), params.bounds.y());
// This is done to avoid a WM "feature" where setting the window size to
// the monitor size causes the WM to set the EWMH for full screen mode.
if (frameless_ &&
gtk_window_util::BoundsMatchMonitorSize(window_, params.bounds)) {
gtk_window_set_default_size(
window_, params.bounds.width(), params.bounds.height() - 1);
} else {
gtk_window_set_default_size(
window_, params.bounds.width(), params.bounds.height());
}
// make sure bounds_ and restored_bounds_ have correct values until we
// get our first configure-event
bounds_ = restored_bounds_ = params.bounds;
gint x, y;
gtk_window_get_position(window_, &x, &y);
bounds_.set_origin(gfx::Point(x, y));
// Hide titlebar when {frame: 'none'} specified on ShellWindow.
if (frameless_)
gtk_window_set_decorated(window_, false);
int min_width = params.minimum_size.width();
int min_height = params.minimum_size.height();
int max_width = params.maximum_size.width();
int max_height = params.maximum_size.height();
GdkGeometry hints;
int hints_mask = 0;
if (min_width || min_height) {
hints.min_height = min_height;
hints.min_width = min_width;
hints_mask |= GDK_HINT_MIN_SIZE;
}
if (max_width || max_height) {
hints.max_height = max_height ? max_height : G_MAXINT;
hints.max_width = max_width ? max_width : G_MAXINT;
hints_mask |= GDK_HINT_MAX_SIZE;
}
if (hints_mask) {
gtk_window_set_geometry_hints(
window_,
GTK_WIDGET(window_),
&hints,
static_cast<GdkWindowHints>(hints_mask));
}
// In some (older) versions of compiz, raising top-level windows when they
// are partially off-screen causes them to get snapped back on screen, not
// always even on the current virtual desktop. If we are running under
// compiz, suppress such raises, as they are not necessary in compiz anyway.
if (ui::GuessWindowManager() == ui::WM_COMPIZ)
suppress_window_raise_ = true;
gtk_window_set_title(window_, extension()->name().c_str());
std::string app_name = web_app::GenerateApplicationNameFromExtensionId(
extension()->id());
gtk_window_util::SetWindowCustomClass(window_,
web_app::GetWMClassFromAppName(app_name));
g_signal_connect(window_, "delete-event",
G_CALLBACK(OnMainWindowDeleteEventThunk), this);
g_signal_connect(window_, "configure-event",
G_CALLBACK(OnConfigureThunk), this);
g_signal_connect(window_, "window-state-event",
G_CALLBACK(OnWindowStateThunk), this);
if (frameless_) {
g_signal_connect(window_, "button-press-event",
G_CALLBACK(OnButtonPressThunk), this);
}
// Add the keybinding registry.
extension_keybinding_registry_.reset(new ExtensionKeybindingRegistryGtk(
shell_window_->profile(),
window_,
extensions::ExtensionKeybindingRegistry::PLATFORM_APPS_ONLY,
shell_window_));
ui::ActiveWindowWatcherX::AddObserver(this);
}
NativeAppWindowGtk::~NativeAppWindowGtk() {
ui::ActiveWindowWatcherX::RemoveObserver(this);
}
bool NativeAppWindowGtk::IsActive() const {
if (ui::ActiveWindowWatcherX::WMSupportsActivation())
return is_active_;
// This still works even though we don't get the activation notification.
return gtk_window_is_active(window_);
}
bool NativeAppWindowGtk::IsMaximized() const {
return (state_ & GDK_WINDOW_STATE_MAXIMIZED);
}
bool NativeAppWindowGtk::IsMinimized() const {
return (state_ & GDK_WINDOW_STATE_ICONIFIED);
}
bool NativeAppWindowGtk::IsFullscreen() const {
return false;
}
gfx::NativeWindow NativeAppWindowGtk::GetNativeWindow() {
return window_;
}
gfx::Rect NativeAppWindowGtk::GetRestoredBounds() const {
return restored_bounds_;
}
gfx::Rect NativeAppWindowGtk::GetBounds() const {
return bounds_;
}
void NativeAppWindowGtk::Show() {
gtk_window_present(window_);
}
void NativeAppWindowGtk::ShowInactive() {
gtk_window_set_focus_on_map(window_, false);
gtk_widget_show(GTK_WIDGET(window_));
}
void NativeAppWindowGtk::Hide() {
gtk_widget_hide(GTK_WIDGET(window_));
}
void NativeAppWindowGtk::Close() {
shell_window_->OnNativeWindowChanged();
// Cancel any pending callback from the window configure debounce timer.
window_configure_debounce_timer_.Stop();
GtkWidget* window = GTK_WIDGET(window_);
// To help catch bugs in any event handlers that might get fired during the
// destruction, set window_ to NULL before any handlers will run.
window_ = NULL;
// OnNativeClose does a delete this so no other members should
// be accessed after. gtk_widget_destroy is safe (and must
// be last).
shell_window_->OnNativeClose();
gtk_widget_destroy(window);
}
void NativeAppWindowGtk::Activate() {
gtk_window_present(window_);
}
void NativeAppWindowGtk::Deactivate() {
gdk_window_lower(gtk_widget_get_window(GTK_WIDGET(window_)));
}
void NativeAppWindowGtk::Maximize() {
gtk_window_maximize(window_);
}
void NativeAppWindowGtk::Minimize() {
gtk_window_iconify(window_);
}
void NativeAppWindowGtk::Restore() {
if (IsMaximized())
gtk_window_unmaximize(window_);
else if (IsMinimized())
gtk_window_deiconify(window_);
}
void NativeAppWindowGtk::SetBounds(const gfx::Rect& bounds) {
gtk_window_move(window_, bounds.x(), bounds.y());
gtk_window_util::SetWindowSize(window_,
gfx::Size(bounds.width(), bounds.height()));
}
void NativeAppWindowGtk::FlashFrame(bool flash) {
gtk_window_set_urgency_hint(window_, flash);
}
bool NativeAppWindowGtk::IsAlwaysOnTop() const {
return false;
}
gfx::Insets NativeAppWindowGtk::GetFrameInsets() const {
if (frameless_)
return gfx::Insets();
GdkWindow* gdk_window = gtk_widget_get_window(GTK_WIDGET(window_));
if (!gdk_window)
return gfx::Insets();
gint current_width = 0;
gint current_height = 0;
gtk_window_get_size(window_, ¤t_width, ¤t_height);
gint current_x = 0;
gint current_y = 0;
gdk_window_get_position(gdk_window, ¤t_x, ¤t_y);
GdkRectangle rect_with_decorations = {0};
gdk_window_get_frame_extents(gdk_window,
&rect_with_decorations);
int left_inset = current_x - rect_with_decorations.x;
int top_inset = current_y - rect_with_decorations.y;
return gfx::Insets(
top_inset,
left_inset,
rect_with_decorations.height - current_height - top_inset,
rect_with_decorations.width - current_width - left_inset);
}
void NativeAppWindowGtk::ActiveWindowChanged(GdkWindow* active_window) {
// Do nothing if we're in the process of closing the browser window.
if (!window_)
return;
is_active_ = gtk_widget_get_window(GTK_WIDGET(window_)) == active_window;
}
// Callback for the delete event. This event is fired when the user tries to
// close the window (e.g., clicking on the X in the window manager title bar).
gboolean NativeAppWindowGtk::OnMainWindowDeleteEvent(GtkWidget* widget,
GdkEvent* event) {
Close();
// Return true to prevent the GTK window from being destroyed. Close will
// destroy it for us.
return TRUE;
}
gboolean NativeAppWindowGtk::OnConfigure(GtkWidget* widget,
GdkEventConfigure* event) {
// We update |bounds_| but not |restored_bounds_| here. The latter needs
// to be updated conditionally when the window is non-maximized and non-
// fullscreen, but whether those state updates have been processed yet is
// window-manager specific. We update |restored_bounds_| in the debounced
// handler below, after the window state has been updated.
bounds_.SetRect(event->x, event->y, event->width, event->height);
// The GdkEventConfigure* we get here doesn't have quite the right
// coordinates though (they're relative to the drawable window area, rather
// than any window manager decorations, if enabled), so we need to call
// gtk_window_get_position() to get the right values. (Otherwise session
// restore, if enabled, will restore windows to incorrect positions.) That's
// a round trip to the X server though, so we set a debounce timer and only
// call it (in OnDebouncedBoundsChanged() below) after we haven't seen a
// reconfigure event in a short while.
// We don't use Reset() because the timer may not yet be running.
// (In that case Stop() is a no-op.)
window_configure_debounce_timer_.Stop();
window_configure_debounce_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds), this,
&NativeAppWindowGtk::OnDebouncedBoundsChanged);
return FALSE;
}
void NativeAppWindowGtk::OnDebouncedBoundsChanged() {
gtk_window_util::UpdateWindowPosition(this, &bounds_, &restored_bounds_);
shell_window_->OnNativeWindowChanged();
}
gboolean NativeAppWindowGtk::OnWindowState(GtkWidget* sender,
GdkEventWindowState* event) {
state_ = event->new_window_state;
if (content_thinks_its_fullscreen_ &&
!(state_ & GDK_WINDOW_STATE_FULLSCREEN)) {
content_thinks_its_fullscreen_ = false;
content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
if (rvh)
rvh->ExitFullscreen();
}
return FALSE;
}
gboolean NativeAppWindowGtk::OnButtonPress(GtkWidget* widget,
GdkEventButton* event) {
if (draggable_region_ && draggable_region_->contains(event->x, event->y)) {
if (event->button == 1) {
if (GDK_BUTTON_PRESS == event->type) {
if (!suppress_window_raise_)
gdk_window_raise(GTK_WIDGET(widget)->window);
return gtk_window_util::HandleTitleBarLeftMousePress(
GTK_WINDOW(widget), bounds_, event);
} else if (GDK_2BUTTON_PRESS == event->type) {
bool is_maximized = gdk_window_get_state(GTK_WIDGET(widget)->window) &
GDK_WINDOW_STATE_MAXIMIZED;
if (is_maximized) {
gtk_window_util::UnMaximize(GTK_WINDOW(widget),
bounds_, restored_bounds_);
} else {
gtk_window_maximize(GTK_WINDOW(widget));
}
return TRUE;
}
} else if (event->button == 2) {
gdk_window_lower(GTK_WIDGET(widget)->window);
return TRUE;
}
}
return FALSE;
}
void NativeAppWindowGtk::SetFullscreen(bool fullscreen) {
content_thinks_its_fullscreen_ = fullscreen;
if (fullscreen)
gtk_window_fullscreen(window_);
else
gtk_window_unfullscreen(window_);
}
bool NativeAppWindowGtk::IsFullscreenOrPending() const {
return content_thinks_its_fullscreen_;
}
void NativeAppWindowGtk::UpdateWindowIcon() {
Profile* profile = shell_window_->profile();
gfx::Image app_icon = shell_window_->app_icon();
if (!app_icon.IsEmpty())
gtk_util::SetWindowIcon(window_, profile, app_icon.ToGdkPixbuf());
else
gtk_util::SetWindowIcon(window_, profile);
}
void NativeAppWindowGtk::UpdateWindowTitle() {
string16 title = shell_window_->GetTitle();
gtk_window_set_title(window_, UTF16ToUTF8(title).c_str());
}
void NativeAppWindowGtk::HandleKeyboardEvent(
const content::NativeWebKeyboardEvent& event) {
// No-op.
}
void NativeAppWindowGtk::UpdateDraggableRegions(
const std::vector<extensions::DraggableRegion>& regions) {
// Draggable region is not supported for non-frameless window.
if (!frameless_)
return;
draggable_region_.reset(ShellWindow::RawDraggableRegionsToSkRegion(regions));
}
// static
NativeAppWindow* NativeAppWindow::Create(
ShellWindow* shell_window,
const ShellWindow::CreateParams& params) {
return new NativeAppWindowGtk(shell_window, params);
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007-2008, Python File Format Interface
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 Python File Format Interface
project 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.
*/
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <fstream>
#include "pyffi/object_models/xml/file_format.hpp"
#include "pyffi/exceptions.hpp"
namespace pyffi
{
namespace object_models
{
namespace xml
{
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
template <typename Iterator>
struct xml_skipper : qi::grammar<Iterator> {
qi::rule<Iterator> start;
xml_skipper()
: xml_skipper::base_type(start) {
start =
qi::space
//[std::cout << phoenix::val("SPACE") << std::endl]
|
qi::lit("<!--")
//[std::cout << phoenix::val("XMLCOMMENT=")]
>> *(!qi::lit("-->")
>> qi::char_
//[std::cout << qi::_1]
)
>> qi::lit("-->");
};
};
template <typename Iterator, typename Skipper = qi::grammar<Iterator> >
struct xml_parser : qi::grammar<Iterator, Skipper> {
qi::rule<Iterator, Skipper> tag_fileformat;
qi::rule<Iterator, Skipper> comment;
qi::rule<Iterator, Skipper> tag_version;
qi::rule<Iterator, Skipper> tag_basic;
qi::rule<Iterator, Skipper> tag_enum;
qi::rule<Iterator, Skipper> tag_option;
qi::rule<Iterator, Skipper> tag_bitflags;
qi::rule<Iterator, Skipper> tag_struct;
qi::rule<Iterator, Skipper> tag_add;
qi::rule<Iterator, std::string(std::string), Skipper> attr_string;
qi::rule<Iterator, unsigned(std::string), Skipper> attr_version;
xml_parser()
: xml_parser::base_type(tag_fileformat, "fileformatxml") {
using phoenix::construct;
using phoenix::val;
using qi::char_;
using qi::eoi;
using qi::eps;
using qi::fail;
using qi::graph;
using qi::lexeme;
using qi::lit;
using qi::on_error;
using qi::space;
using qi::uint_;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::_r1;
using qi::_val;
tag_fileformat =
-(lit("<?xml")
[std::cout << val("XML") << std::endl]
>> *(!lit("?>") >> char_)
>> lit("?>"))
>> -(lit("<!DOCTYPE")
[std::cout << val("DOCTYPE") << std::endl]
>> lit("niftoolsxml")
>> lit(">"))
>> lit("<niftoolsxml")
[std::cout << val("NIFTOOLSXML") << std::endl]
>> -(lit("version") >> lit("=") >> lit("\"0.7.0.0\""))
>> lit(">")
>> *(tag_version | tag_basic | tag_enum)
//>> *(!lit("</niftoolsxml>") >> char_) // temporary skip rule
>> lit("</niftoolsxml>")
>> eoi;
comment = *lexeme[+(!char_('<') >> graph)];
tag_basic =
lit("<basic")
[std::cout << val("BASIC=")]
>> *(
attr_string(std::string("name"))
[std::cout << _1 << std::endl]
| attr_string(std::string("count"))
| attr_string(std::string("niflibtype"))
| attr_string(std::string("nifskopetype"))
| attr_string(std::string("istemplate"))
)
>> char_('>')
>> comment
>> lit("</basic>");
tag_enum =
lit("<enum")
[std::cout << val("ENUM=")]
>> *(
attr_string(std::string("name"))
[std::cout << _1 << std::endl]
|
attr_string(std::string("storage"))
[std::cout << val("(") << _1 << ")" << std::endl]
)
>> char_('>')
>> comment
>> *tag_option
>> lit("</enum>");
tag_option =
lit("<option")
[std::cout << val("OPTION=")]
>> *(
attr_string(std::string("name"))
[std::cout << _1 << std::endl]
|
attr_string(std::string("value"))
)
>> char_('>')
>> comment
>> lit("</option>");
tag_version =
lit("<version")
[std::cout << val("VERSION=")]
>> attr_version(std::string("num"))
[std::cout << _1 << std::endl]
>> char_('>')
>> comment
>> lit("</version>");
attr_string %=
lit(_r1) >> '='
>> lexeme['"' >> *(char_ - '"') >> '"'];
attr_version =
lit(_r1)[_val = 0] >> '='
>> '"' >> (uint_[_val = _val * 256 + _1] % '.') >> '"';
tag_fileformat.name("<niftoolsxml>...</niftoolsxml>");
comment.name("...");
tag_version.name("<version>...</version>");
tag_basic.name("<basic>...</basic>");
attr_string.name("attribute (string)");
attr_version.name("attribute (version)");
on_error<fail>(
tag_fileformat,
std::cout
<< val("Error! Expecting ")
<< _4 // what failed?
<< val(" here: \"")
<< construct<std::string>(_3, _2) // iterators to error-pos, end
<< val("\"")
<< std::endl
);
};
};
/*
* Main entry point for parsing an xml file.
*/
FileFormat::FileFormat(const std::string & filename)
{
// open file, disable skipping of whitespace
std::ifstream in(filename.c_str());
if (in.fail()) {
throw io_error("Could not open '" + filename + "'.");
}
in.unsetf(std::ios::skipws);
std::cout << "PARSING " << filename << std::endl;
// wrap istream into iterator
boost::spirit::istream_iterator first(in);
boost::spirit::istream_iterator last;
// create skip parser
xml_skipper<boost::spirit::istream_iterator> skipper;
// create parser
xml_parser<boost::spirit::istream_iterator> parser;
// use iterator to parse file data
bool r = qi::phrase_parse(first, last, parser, skipper);
// fail if we did not get a full match
if (!r || first != last)
throw syntax_error("Syntax error while parsing '" + filename + "'.");
};
}; // namespace xml
}; // namespace object_models
}; // namespace pyffi
<commit_msg>Added struct tag.<commit_after>/*
Copyright (c) 2007-2008, Python File Format Interface
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 Python File Format Interface
project 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.
*/
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <fstream>
#include "pyffi/object_models/xml/file_format.hpp"
#include "pyffi/exceptions.hpp"
namespace pyffi
{
namespace object_models
{
namespace xml
{
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
template <typename Iterator>
struct xml_skipper : qi::grammar<Iterator> {
qi::rule<Iterator> start;
xml_skipper()
: xml_skipper::base_type(start) {
start =
qi::space
//[std::cout << phoenix::val("SPACE") << std::endl]
|
qi::lit("<!--")
//[std::cout << phoenix::val("XMLCOMMENT=")]
>> *(!qi::lit("-->")
>> qi::char_
//[std::cout << qi::_1]
)
>> qi::lit("-->");
};
};
template <typename Iterator, typename Skipper = qi::grammar<Iterator> >
struct xml_parser : qi::grammar<Iterator, Skipper> {
qi::rule<Iterator, Skipper> tag_fileformat;
qi::rule<Iterator, Skipper> comment;
qi::rule<Iterator, Skipper> tag_version;
qi::rule<Iterator, Skipper> tag_basic;
qi::rule<Iterator, Skipper> tag_enum;
qi::rule<Iterator, Skipper> tag_option;
qi::rule<Iterator, Skipper> tag_bitflags;
qi::rule<Iterator, Skipper> tag_struct;
qi::rule<Iterator, Skipper> tag_add;
qi::rule<Iterator, std::string(std::string), Skipper> attr_string;
qi::rule<Iterator, unsigned(std::string), Skipper> attr_version;
xml_parser()
: xml_parser::base_type(tag_fileformat, "fileformatxml") {
using phoenix::construct;
using phoenix::val;
using qi::char_;
using qi::eoi;
using qi::eps;
using qi::fail;
using qi::graph;
using qi::lexeme;
using qi::lit;
using qi::on_error;
using qi::space;
using qi::uint_;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::_r1;
using qi::_val;
tag_fileformat =
-(lit("<?xml")
[std::cout << val("XML") << std::endl]
>> *(!lit("?>") >> char_)
>> lit("?>"))
>> -(lit("<!DOCTYPE")
[std::cout << val("DOCTYPE") << std::endl]
>> lit("niftoolsxml")
>> lit(">"))
>> lit("<niftoolsxml")
[std::cout << val("NIFTOOLSXML") << std::endl]
>> -(lit("version") >> lit("=") >> lit("\"0.7.0.0\""))
>> lit(">")
>> *(tag_version | tag_basic | tag_enum | tag_struct)
//>> *(!lit("</niftoolsxml>") >> char_) // temporary skip rule
>> lit("</niftoolsxml>")
>> eoi;
comment = *lexeme[+(!char_('<') >> graph)];
tag_add =
lit("<add")
[std::cout << val("ADD=")]
>> *(
attr_string(std::string("name"))
[std::cout << _1 << std::endl]
| attr_string(std::string("type"))
| attr_string(std::string("default"))
| attr_version(std::string("ver1"))
| attr_version(std::string("ver2"))
| attr_string(std::string("cond"))
| attr_string(std::string("arr1"))
| attr_string(std::string("arr2"))
| attr_string(std::string("template"))
| attr_string(std::string("vercond"))
)
>> char_('>')
>> comment
>> lit("</add>");
tag_basic =
lit("<basic")
[std::cout << val("BASIC=")]
>> *(
attr_string(std::string("name"))
[std::cout << _1 << std::endl]
| attr_string(std::string("count"))
| attr_string(std::string("niflibtype"))
| attr_string(std::string("nifskopetype"))
| attr_string(std::string("istemplate"))
)
>> char_('>')
>> comment
>> lit("</basic>");
tag_enum =
lit("<enum")
[std::cout << val("ENUM=")]
>> *(
attr_string(std::string("name"))
[std::cout << _1 << std::endl]
|
attr_string(std::string("storage"))
[std::cout << val("(") << _1 << ")" << std::endl]
)
>> char_('>')
>> comment
>> *tag_option
>> lit("</enum>");
tag_option =
lit("<option")
[std::cout << val("OPTION=")]
>> *(
attr_string(std::string("name"))
[std::cout << _1 << std::endl]
|
attr_string(std::string("value"))
)
>> char_('>')
>> comment
>> lit("</option>");
tag_struct =
(lit("<struct") | lit("<compound") | lit("<niobject"))
[std::cout << val("STRUCT=")]
>> *(
attr_string(std::string("name"))
[std::cout << _1 << std::endl]
|
attr_string(std::string("inherit"))
[std::cout << val("(") << _1 << ")" << std::endl]
| attr_string(std::string("niflibtype"))
| attr_string(std::string("nifskopetype"))
| attr_string(std::string("abstract"))
| attr_string(std::string("ver1"))
| attr_string(std::string("ver2"))
)
>> char_('>')
>> comment
>> *tag_add
>> (lit("</struct>") | lit("</compound>") | lit("</niobject>"));
tag_version =
lit("<version")
[std::cout << val("VERSION=")]
>> attr_version(std::string("num"))
[std::cout << _1 << std::endl]
>> char_('>')
>> comment
>> lit("</version>");
attr_string %=
lit(_r1) >> '='
>> lexeme['"' >> *(char_ - '"') >> '"'];
attr_version =
lit(_r1)[_val = 0] >> '='
>> '"' >> (uint_[_val = _val * 256 + _1] % '.') >> '"';
tag_fileformat.name("<niftoolsxml>...</niftoolsxml>");
comment.name("...");
tag_version.name("<version>...</version>");
tag_basic.name("<basic>...</basic>");
attr_string.name("attribute (string)");
attr_version.name("attribute (version)");
on_error<fail>(
tag_fileformat,
std::cout
<< val("Error! Expecting ")
<< _4 // what failed?
<< val(" here: \"")
<< construct<std::string>(_3, _2) // iterators to error-pos, end
<< val("\"")
<< std::endl
);
};
};
/*
* Main entry point for parsing an xml file.
*/
FileFormat::FileFormat(const std::string & filename)
{
// open file, disable skipping of whitespace
std::ifstream in(filename.c_str());
if (in.fail()) {
throw io_error("Could not open '" + filename + "'.");
}
in.unsetf(std::ios::skipws);
std::cout << "PARSING " << filename << std::endl;
// wrap istream into iterator
boost::spirit::istream_iterator first(in);
boost::spirit::istream_iterator last;
// create skip parser
xml_skipper<boost::spirit::istream_iterator> skipper;
// create parser
xml_parser<boost::spirit::istream_iterator> parser;
// use iterator to parse file data
bool r = qi::phrase_parse(first, last, parser, skipper);
// fail if we did not get a full match
if (!r || first != last)
throw syntax_error("Syntax error while parsing '" + filename + "'.");
};
}; // namespace xml
}; // namespace object_models
}; // namespace pyffi
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_LOGGED_RESOURCES_HXX
#define INCLUDED_LOGGED_RESOURCES_HXX
#include "WW8ResourceModel.hxx"
#include "TagLogger.hxx"
namespace writerfilter
{
class LoggedResourcesHelper
{
public:
explicit LoggedResourcesHelper(TagLogger::Pointer_t pLogger, const string & sPrefix);
virtual ~LoggedResourcesHelper();
void startElement(const string & sElement);
void endElement(const string & sElement);
void chars(const ::rtl::OUString & rChars);
void chars(const string & rChars);
void attribute(const string & rName, const string & rValue);
void attribute(const string & rName, sal_uInt32 nValue);
void setPrefix(const string & rPrefix);
private:
TagLogger::Pointer_t mpLogger;
string msPrefix;
};
class WRITERFILTER_DLLPUBLIC LoggedStream : public Stream
{
public:
explicit LoggedStream(TagLogger::Pointer_t pLogger, const string & sPrefix);
virtual ~LoggedStream();
void startSectionGroup();
void endSectionGroup();
void startParagraphGroup();
void endParagraphGroup();
void startCharacterGroup();
void endCharacterGroup();
void startShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape );
void endShape();
void text(const sal_uInt8 * data, size_t len);
void utext(const sal_uInt8 * data, size_t len);
void props(writerfilter::Reference<Properties>::Pointer_t ref);
void table(Id name, writerfilter::Reference<Table>::Pointer_t ref);
void substream(Id name, writerfilter::Reference<Stream>::Pointer_t ref);
void info(const string & info);
protected:
virtual void lcl_startSectionGroup() = 0;
virtual void lcl_endSectionGroup() = 0;
virtual void lcl_startParagraphGroup() = 0;
virtual void lcl_endParagraphGroup() = 0;
virtual void lcl_startCharacterGroup() = 0;
virtual void lcl_endCharacterGroup() = 0;
virtual void lcl_startShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ) = 0;
virtual void lcl_endShape() = 0;
virtual void lcl_text(const sal_uInt8 * data, size_t len) = 0;
virtual void lcl_utext(const sal_uInt8 * data, size_t len) = 0;
virtual void lcl_props(writerfilter::Reference<Properties>::Pointer_t ref) = 0;
virtual void lcl_table(Id name, writerfilter::Reference<Table>::Pointer_t ref) = 0;
virtual void lcl_substream(Id name, writerfilter::Reference<Stream>::Pointer_t ref) = 0;
virtual void lcl_info(const string & info) = 0;
LoggedResourcesHelper mHelper;
};
class WRITERFILTER_DLLPUBLIC LoggedProperties : public Properties
{
public:
explicit LoggedProperties(TagLogger::Pointer_t pLogger, const string & sPrefix);
virtual ~LoggedProperties();
void attribute(Id name, Value & val);
void sprm(Sprm & sprm);
protected:
virtual void lcl_attribute(Id name, Value & val) = 0;
virtual void lcl_sprm(Sprm & sprm) = 0;
LoggedResourcesHelper mHelper;
};
class WRITERFILTER_DLLPUBLIC LoggedTable : public Table
{
public:
explicit LoggedTable(TagLogger::Pointer_t pLogger, const string & sPrefix);
virtual ~LoggedTable();
void entry(int pos, writerfilter::Reference<Properties>::Pointer_t ref);
protected:
virtual void lcl_entry(int pos, writerfilter::Reference<Properties>::Pointer_t ref) = 0;
LoggedResourcesHelper mHelper;
};
}
#endif // INCLUDED_LOGGED_RESOURCES_HXX
<commit_msg>Export the LoggedResourcesHelper class<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_LOGGED_RESOURCES_HXX
#define INCLUDED_LOGGED_RESOURCES_HXX
#include "WW8ResourceModel.hxx"
#include "TagLogger.hxx"
#include <WriterFilterDllApi.hxx>
namespace writerfilter
{
class WRITERFILTER_DLLPUBLIC LoggedResourcesHelper
{
public:
explicit LoggedResourcesHelper(TagLogger::Pointer_t pLogger, const string & sPrefix);
virtual ~LoggedResourcesHelper();
void startElement(const string & sElement);
void endElement(const string & sElement);
void chars(const ::rtl::OUString & rChars);
void chars(const string & rChars);
void attribute(const string & rName, const string & rValue);
void attribute(const string & rName, sal_uInt32 nValue);
void setPrefix(const string & rPrefix);
private:
TagLogger::Pointer_t mpLogger;
string msPrefix;
};
class WRITERFILTER_DLLPUBLIC LoggedStream : public Stream
{
public:
explicit LoggedStream(TagLogger::Pointer_t pLogger, const string & sPrefix);
virtual ~LoggedStream();
void startSectionGroup();
void endSectionGroup();
void startParagraphGroup();
void endParagraphGroup();
void startCharacterGroup();
void endCharacterGroup();
void startShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape );
void endShape();
void text(const sal_uInt8 * data, size_t len);
void utext(const sal_uInt8 * data, size_t len);
void props(writerfilter::Reference<Properties>::Pointer_t ref);
void table(Id name, writerfilter::Reference<Table>::Pointer_t ref);
void substream(Id name, writerfilter::Reference<Stream>::Pointer_t ref);
void info(const string & info);
protected:
virtual void lcl_startSectionGroup() = 0;
virtual void lcl_endSectionGroup() = 0;
virtual void lcl_startParagraphGroup() = 0;
virtual void lcl_endParagraphGroup() = 0;
virtual void lcl_startCharacterGroup() = 0;
virtual void lcl_endCharacterGroup() = 0;
virtual void lcl_startShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ) = 0;
virtual void lcl_endShape() = 0;
virtual void lcl_text(const sal_uInt8 * data, size_t len) = 0;
virtual void lcl_utext(const sal_uInt8 * data, size_t len) = 0;
virtual void lcl_props(writerfilter::Reference<Properties>::Pointer_t ref) = 0;
virtual void lcl_table(Id name, writerfilter::Reference<Table>::Pointer_t ref) = 0;
virtual void lcl_substream(Id name, writerfilter::Reference<Stream>::Pointer_t ref) = 0;
virtual void lcl_info(const string & info) = 0;
LoggedResourcesHelper mHelper;
};
class WRITERFILTER_DLLPUBLIC LoggedProperties : public Properties
{
public:
explicit LoggedProperties(TagLogger::Pointer_t pLogger, const string & sPrefix);
virtual ~LoggedProperties();
void attribute(Id name, Value & val);
void sprm(Sprm & sprm);
protected:
virtual void lcl_attribute(Id name, Value & val) = 0;
virtual void lcl_sprm(Sprm & sprm) = 0;
LoggedResourcesHelper mHelper;
};
class WRITERFILTER_DLLPUBLIC LoggedTable : public Table
{
public:
explicit LoggedTable(TagLogger::Pointer_t pLogger, const string & sPrefix);
virtual ~LoggedTable();
void entry(int pos, writerfilter::Reference<Properties>::Pointer_t ref);
protected:
virtual void lcl_entry(int pos, writerfilter::Reference<Properties>::Pointer_t ref) = 0;
LoggedResourcesHelper mHelper;
};
}
#endif // INCLUDED_LOGGED_RESOURCES_HXX
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/time/time.h"
#include "chrome/test/base/chrome_render_view_test.h"
#include "components/autofill/content/common/autofill_messages.h"
#include "components/autofill/core/common/form_data.h"
#include "content/public/test/mock_render_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebFormElement.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
using blink::WebString;
using blink::WebURLError;
typedef ChromeRenderViewTest FormAutocompleteTest;
namespace autofill {
namespace {
// Helper function to verify the form-related messages received from the
// renderer. The same data is expected in both messages. Depending on
// |expect_submitted_message|, will verify presence of FormSubmitted message.
void VerifyReceivedRendererMessages(content::MockRenderThread* render_thread,
bool expect_submitted_message) {
const IPC::Message* will_submit_message =
render_thread->sink().GetFirstMessageMatching(
AutofillHostMsg_WillSubmitForm::ID);
const IPC::Message* submitted_message =
render_thread->sink().GetFirstMessageMatching(
AutofillHostMsg_FormSubmitted::ID);
ASSERT_TRUE(will_submit_message != NULL);
ASSERT_EQ(expect_submitted_message, submitted_message != NULL);
// The tuple also includes a timestamp, which is ignored.
base::Tuple<FormData, base::TimeTicks> will_submit_forms;
AutofillHostMsg_WillSubmitForm::Read(will_submit_message, &will_submit_forms);
ASSERT_EQ(2U, base::get<0>(will_submit_forms).fields.size());
FormFieldData& will_submit_form_field =
base::get<0>(will_submit_forms).fields[0];
EXPECT_EQ(WebString("fname"), will_submit_form_field.name);
EXPECT_EQ(WebString("Rick"), will_submit_form_field.value);
will_submit_form_field = base::get<0>(will_submit_forms).fields[1];
EXPECT_EQ(WebString("lname"), will_submit_form_field.name);
EXPECT_EQ(WebString("Deckard"), will_submit_form_field.value);
if (expect_submitted_message) {
base::Tuple<FormData> submitted_forms;
AutofillHostMsg_FormSubmitted::Read(submitted_message, &submitted_forms);
ASSERT_EQ(2U, base::get<0>(submitted_forms).fields.size());
FormFieldData& submitted_field = base::get<0>(submitted_forms).fields[0];
EXPECT_EQ(WebString("fname"), submitted_field.name);
EXPECT_EQ(WebString("Rick"), submitted_field.value);
submitted_field = base::get<0>(submitted_forms).fields[1];
EXPECT_EQ(WebString("lname"), submitted_field.name);
EXPECT_EQ(WebString("Deckard"), submitted_field.value);
}
}
} // end namespace
// Tests that submitting a form generates WillSubmitForm and FormSubmitted
// messages with the form fields.
// Flaky: http://crbug.com/500851.
TEST_F(FormAutocompleteTest, DISABLED_NormalFormSubmit) {
// Load a form.
LoadHTML("<html><form id='myForm'><input name='fname' value='Rick'/>"
"<input name='lname' value='Deckard'/></form></html>");
// Submit the form.
ExecuteJavaScript("document.getElementById('myForm').submit();");
ProcessPendingMessages();
VerifyReceivedRendererMessages(render_thread_.get(),
true /* expect_submitted_message */);
}
// Tests that submitting a form that prevents the submit event from propagating
// will only send the WillSubmitForm message.
TEST_F(FormAutocompleteTest, SubmitEventPrevented) {
// Load a form.
LoadHTML(
"<html><form id='myForm'><input name='fname' value='Rick'/>"
"<input name='lname' value='Deckard'/><input type=submit></form>"
"</html>");
// Submit the form.
ExecuteJavaScript(
"var form = document.forms[0];"
"form.onsubmit = function(event) { event.preventDefault(); };"
"document.querySelector('input[type=submit]').click();");
ProcessPendingMessages();
VerifyReceivedRendererMessages(render_thread_.get(),
false /* expect_submitted_message */);
}
// Tests that submitting a form that has autocomplete="off" generates
// WillSubmitForm and FormSubmitted messages.
TEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) {
// Load a form.
LoadHTML("<html><form id='myForm' autocomplete='off'>"
"<input name='fname' value='Rick'/>"
"<input name='lname' value='Deckard'/>"
"</form></html>");
// Submit the form.
ExecuteJavaScript("document.getElementById('myForm').submit();");
ProcessPendingMessages();
VerifyReceivedRendererMessages(render_thread_.get(),
true /* expect_submitted_message */);
}
// Tests that fields with autocomplete off are submitted.
// Flaky: http://crbug.com/500851.
TEST_F(FormAutocompleteTest, DISABLED_AutoCompleteOffInputSubmit) {
// Load a form.
LoadHTML("<html><form id='myForm'>"
"<input name='fname' value='Rick'/>"
"<input name='lname' value='Deckard' autocomplete='off'/>"
"</form></html>");
// Submit the form.
ExecuteJavaScript("document.getElementById('myForm').submit();");
ProcessPendingMessages();
VerifyReceivedRendererMessages(render_thread_.get(),
true /* expect_submitted_message */);
}
// Tests that submitting a form that has been dynamically set as autocomplete
// off generates WillSubmitForm and FormSubmitted messages.
// Note: We previously did the opposite, for bug http://crbug.com/36520
// Flaky: http://crbug.com/500851.
TEST_F(FormAutocompleteTest, DISABLED_DynamicAutoCompleteOffFormSubmit) {
LoadHTML("<html><form id='myForm'><input name='fname' value='Rick'/>"
"<input name='lname' value='Deckard'/></form></html>");
blink::WebElement element =
GetMainFrame()->document().getElementById(blink::WebString("myForm"));
ASSERT_FALSE(element.isNull());
blink::WebFormElement form = element.to<blink::WebFormElement>();
EXPECT_TRUE(form.autoComplete());
// Dynamically mark the form as autocomplete off.
ExecuteJavaScript("document.getElementById('myForm')."
"setAttribute('autocomplete', 'off');");
ProcessPendingMessages();
EXPECT_FALSE(form.autoComplete());
// Submit the form.
ExecuteJavaScript("document.getElementById('myForm').submit();");
ProcessPendingMessages();
VerifyReceivedRendererMessages(render_thread_.get(),
true /* expect_submitted_message */);
}
} // namespace autofill
<commit_msg>Disable one more form autocomplete test I missed.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/time/time.h"
#include "chrome/test/base/chrome_render_view_test.h"
#include "components/autofill/content/common/autofill_messages.h"
#include "components/autofill/core/common/form_data.h"
#include "content/public/test/mock_render_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebFormElement.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
using blink::WebString;
using blink::WebURLError;
typedef ChromeRenderViewTest FormAutocompleteTest;
namespace autofill {
namespace {
// Helper function to verify the form-related messages received from the
// renderer. The same data is expected in both messages. Depending on
// |expect_submitted_message|, will verify presence of FormSubmitted message.
void VerifyReceivedRendererMessages(content::MockRenderThread* render_thread,
bool expect_submitted_message) {
const IPC::Message* will_submit_message =
render_thread->sink().GetFirstMessageMatching(
AutofillHostMsg_WillSubmitForm::ID);
const IPC::Message* submitted_message =
render_thread->sink().GetFirstMessageMatching(
AutofillHostMsg_FormSubmitted::ID);
ASSERT_TRUE(will_submit_message != NULL);
ASSERT_EQ(expect_submitted_message, submitted_message != NULL);
// The tuple also includes a timestamp, which is ignored.
base::Tuple<FormData, base::TimeTicks> will_submit_forms;
AutofillHostMsg_WillSubmitForm::Read(will_submit_message, &will_submit_forms);
ASSERT_EQ(2U, base::get<0>(will_submit_forms).fields.size());
FormFieldData& will_submit_form_field =
base::get<0>(will_submit_forms).fields[0];
EXPECT_EQ(WebString("fname"), will_submit_form_field.name);
EXPECT_EQ(WebString("Rick"), will_submit_form_field.value);
will_submit_form_field = base::get<0>(will_submit_forms).fields[1];
EXPECT_EQ(WebString("lname"), will_submit_form_field.name);
EXPECT_EQ(WebString("Deckard"), will_submit_form_field.value);
if (expect_submitted_message) {
base::Tuple<FormData> submitted_forms;
AutofillHostMsg_FormSubmitted::Read(submitted_message, &submitted_forms);
ASSERT_EQ(2U, base::get<0>(submitted_forms).fields.size());
FormFieldData& submitted_field = base::get<0>(submitted_forms).fields[0];
EXPECT_EQ(WebString("fname"), submitted_field.name);
EXPECT_EQ(WebString("Rick"), submitted_field.value);
submitted_field = base::get<0>(submitted_forms).fields[1];
EXPECT_EQ(WebString("lname"), submitted_field.name);
EXPECT_EQ(WebString("Deckard"), submitted_field.value);
}
}
} // end namespace
// Tests that submitting a form generates WillSubmitForm and FormSubmitted
// messages with the form fields.
// Flaky: http://crbug.com/500851.
TEST_F(FormAutocompleteTest, DISABLED_NormalFormSubmit) {
// Load a form.
LoadHTML("<html><form id='myForm'><input name='fname' value='Rick'/>"
"<input name='lname' value='Deckard'/></form></html>");
// Submit the form.
ExecuteJavaScript("document.getElementById('myForm').submit();");
ProcessPendingMessages();
VerifyReceivedRendererMessages(render_thread_.get(),
true /* expect_submitted_message */);
}
// Tests that submitting a form that prevents the submit event from propagating
// will only send the WillSubmitForm message.
TEST_F(FormAutocompleteTest, SubmitEventPrevented) {
// Load a form.
LoadHTML(
"<html><form id='myForm'><input name='fname' value='Rick'/>"
"<input name='lname' value='Deckard'/><input type=submit></form>"
"</html>");
// Submit the form.
ExecuteJavaScript(
"var form = document.forms[0];"
"form.onsubmit = function(event) { event.preventDefault(); };"
"document.querySelector('input[type=submit]').click();");
ProcessPendingMessages();
VerifyReceivedRendererMessages(render_thread_.get(),
false /* expect_submitted_message */);
}
// Tests that submitting a form that has autocomplete="off" generates
// WillSubmitForm and FormSubmitted messages.
// Flaky: http://crbug.com/500851.
TEST_F(FormAutocompleteTest, DISABLED_AutoCompleteOffFormSubmit) {
// Load a form.
LoadHTML("<html><form id='myForm' autocomplete='off'>"
"<input name='fname' value='Rick'/>"
"<input name='lname' value='Deckard'/>"
"</form></html>");
// Submit the form.
ExecuteJavaScript("document.getElementById('myForm').submit();");
ProcessPendingMessages();
VerifyReceivedRendererMessages(render_thread_.get(),
true /* expect_submitted_message */);
}
// Tests that fields with autocomplete off are submitted.
// Flaky: http://crbug.com/500851.
TEST_F(FormAutocompleteTest, DISABLED_AutoCompleteOffInputSubmit) {
// Load a form.
LoadHTML("<html><form id='myForm'>"
"<input name='fname' value='Rick'/>"
"<input name='lname' value='Deckard' autocomplete='off'/>"
"</form></html>");
// Submit the form.
ExecuteJavaScript("document.getElementById('myForm').submit();");
ProcessPendingMessages();
VerifyReceivedRendererMessages(render_thread_.get(),
true /* expect_submitted_message */);
}
// Tests that submitting a form that has been dynamically set as autocomplete
// off generates WillSubmitForm and FormSubmitted messages.
// Note: We previously did the opposite, for bug http://crbug.com/36520
// Flaky: http://crbug.com/500851.
TEST_F(FormAutocompleteTest, DISABLED_DynamicAutoCompleteOffFormSubmit) {
LoadHTML("<html><form id='myForm'><input name='fname' value='Rick'/>"
"<input name='lname' value='Deckard'/></form></html>");
blink::WebElement element =
GetMainFrame()->document().getElementById(blink::WebString("myForm"));
ASSERT_FALSE(element.isNull());
blink::WebFormElement form = element.to<blink::WebFormElement>();
EXPECT_TRUE(form.autoComplete());
// Dynamically mark the form as autocomplete off.
ExecuteJavaScript("document.getElementById('myForm')."
"setAttribute('autocomplete', 'off');");
ProcessPendingMessages();
EXPECT_FALSE(form.autoComplete());
// Submit the form.
ExecuteJavaScript("document.getElementById('myForm').submit();");
ProcessPendingMessages();
VerifyReceivedRendererMessages(render_thread_.get(),
true /* expect_submitted_message */);
}
} // namespace autofill
<|endoftext|>
|
<commit_before>#include "card.hpp"
#include <iostream>
void card::assign(rank r, suit s) {
rank_ = r;
suit_ = s;
}
bool operator==(card a, card b) {
return a.get_rank() == b.get_rank() and
a.get_suit() == b.get_suit();
}
bool operator!=(card a, card b) {
return not (a == b);
}
std::ostream& operator<<(std::ostream& out, card c) {
out << c.get_rank() << " " << c.get_suit();
return out;
}
std::istream& operator>>(std::istream& in, card c) {
char s{}, r{};
in >> r;
in >> s;
c.assign(r, s);
return in;
}
bool acehigh_compare(card a, card b) {
return a.get_rank() < b.get_rank();
}
bool acelow_compare(card a, card b) {
return (card::ace == a.get_rank())
? true
: a.get_rank() < b.get_rank();
}
card_generator::card_generator()
: rankIndex_{ 2 }, suitIndex_{ card::ace } { }
card card_generator::operator()() {
card c = card(rankIndex_, suitIndex_);
if(++rankIndex_ > card::ace) {
if (card::spades == suitIndex_) {
rankIndex_ = 2;
suitIndex_ = card::diamonds;
}
else {
rankIndex_ = 2;
++suitIndex_;
}
}
return c;
}
<commit_msg>ch-53: modify the 3-d example for chapter 53<commit_after>#include "card.hpp"
#include <iostream>
void card::assign(rank r, suit s) {
rank_ = r;
suit_ = s;
}
bool operator==(card a, card b) {
return a.get_rank() == b.get_rank() and
a.get_suit() == b.get_suit();
}
bool operator!=(card a, card b) {
return not (a == b);
}
std::ostream& operator<<(std::ostream& out, card c) {
out << int(c.get_rank()) << " " << int(c.get_suit());
return out;
}
std::istream& operator>>(std::istream& in, card c) {
char s{}, r{};
in >> r;
in >> s;
c.assign(r, s);
return in;
}
bool acehigh_compare(card a, card b) {
return a.get_rank() < b.get_rank();
}
bool acelow_compare(card a, card b) {
return (card::ace == a.get_rank())
? true
: a.get_rank() < b.get_rank();
}
card_generator::card_generator()
: rankIndex_{ 2 }, suitIndex_{ card::diamonds } { }
card card_generator::operator()() {
card c = card(rankIndex_, suitIndex_);
if(++rankIndex_ > card::ace) {
if (card::spades == suitIndex_) {
rankIndex_ = 2;
suitIndex_ = card::diamonds;
}
else {
rankIndex_ = 2;
++suitIndex_;
}
}
return c;
}
<|endoftext|>
|
<commit_before>/*
Упорядочить три числа в порядке возрастания.
C++ версия
*/
#include <iostream> // подключение ввода/вывода в консоль
#include <clocale> // Для Windows - подключение вывода русских букв в консоль
int main()
{
std::setlocale(LC_ALL, "RUS");
int x, y, z;
std::cout << "x: ";
std::cin >> x;
std::cout << "y: ";
std::cin >> y;
std::cout << "z: ";
std::cin >> z;
// Печатаем некоторый текст с переносом
std::cout << "Результат: \n";
if (x > y) {
if (y > z) {
// Обращаем внимание, как форматируется строка для вывода на экран. В частности, отступы
std::cout << "z = " << z << "\n";
std::cout << "y = " << y << "\n";
std::cout << "x = " << x << "\n";
} else {
std::cout << "y = " << y << "\n";
if (x > z) {
std::cout << "z = " << z << "\n";
std::cout << "x = " << x << "\n";
} else {
std::cout << "x = " << x << "\n";
std::cout << "z = " << z << "\n";
}
}
} else {
if (x > z) {
std::cout << "z = " << z << "\n";
std::cout << "x = " << x << "\n";
printf("y = %d\n", y);
} else {
std::cout << "x = " << x << "\n";
if (y > z) {
std::cout << "z = " << z << "\n";
std::cout << "y = " << y << "\n";
} else {
std::cout << "y = " << y << "\n";
std::cout << "z = " << z << "\n";
}
}
}
return 0;
}
<commit_msg>fix console output in 1.cpp<commit_after>/*
Упорядочить три числа в порядке возрастания.
C++ версия
*/
#include <iostream> // подключение ввода/вывода в консоль
#include <clocale> // Для Windows - подключение вывода русских букв в консоль
int main()
{
std::setlocale(LC_ALL, "RUS");
int x, y, z;
std::cout << "x: ";
std::cin >> x;
std::cout << "y: ";
std::cin >> y;
std::cout << "z: ";
std::cin >> z;
// Печатаем некоторый текст с переносом
std::cout << "Результат: \n";
if (x > y) {
if (y > z) {
// Обращаем внимание, как форматируется строка для вывода на экран. В частности, отступы
std::cout << "z = " << z << "\n";
std::cout << "y = " << y << "\n";
std::cout << "x = " << x << "\n";
} else {
std::cout << "y = " << y << "\n";
if (x > z) {
std::cout << "z = " << z << "\n";
std::cout << "x = " << x << "\n";
} else {
std::cout << "x = " << x << "\n";
std::cout << "z = " << z << "\n";
}
}
} else {
if (x > z) {
std::cout << "z = " << z << "\n";
std::cout << "x = " << x << "\n";
std::cout << "y = " << y << "\n";
} else {
std::cout << "x = " << x << "\n";
if (y > z) {
std::cout << "z = " << z << "\n";
std::cout << "y = " << y << "\n";
} else {
std::cout << "y = " << y << "\n";
std::cout << "z = " << z << "\n";
}
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE2D_BORDERLINEPRIMITIVE2D_HXX
#define INCLUDED_DRAWINGLAYER_PRIMITIVE2D_BORDERLINEPRIMITIVE2D_HXX
#include <drawinglayer/drawinglayerdllapi.h>
#include <drawinglayer/primitive2d/baseprimitive2d.hxx>
#include <basegfx/color/bcolor.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <svtools/ctrlbox.hxx>
//////////////////////////////////////////////////////////////////////////////
namespace drawinglayer
{
namespace primitive2d
{
/** BorderLinePrimitive2D class
This is the basic primitive to build frames around objects, e.g. tables.
It defines a single or double line from Start to nd using the LeftWidth,
Distance and RightWidth definitions.
The LineStart/End overlap is defined by the Extend(Inner|Outer)(Start|End)
definitions.
*/
class DRAWINGLAYER_DLLPUBLIC BorderLinePrimitive2D : public BufferedDecompositionPrimitive2D
{
private:
/// the line definition
basegfx::B2DPoint maStart;
basegfx::B2DPoint maEnd;
/// the widths of single/double line
double mfLeftWidth;
double mfDistance;
double mfRightWidth;
/// edge overlap sizes
double mfExtendLeftStart;
double mfExtendLeftEnd;
double mfExtendRightStart;
double mfExtendRightEnd;
/// the line colors
basegfx::BColor maRGBColorRight;
basegfx::BColor maRGBColorLeft;
basegfx::BColor maRGBColorGap;
bool mbHasGapColor;
short mnStyle;
/// bitfield
/// flags to influence inside/outside creation
unsigned mbCreateInside : 1;
unsigned mbCreateOutside : 1;
/// local helpers
double getWidth(
const geometry::ViewInformation2D& rViewInformation) const;
bool isSolidLine() const
{
return (mnStyle==STYLE_SOLID);
}
bool isInsideUsed() const
{
return !basegfx::fTools::equalZero(mfLeftWidth);
}
bool isOutsideUsed() const
{
return !basegfx::fTools::equalZero(mfRightWidth);
}
protected:
virtual basegfx::B2DPolyPolygon getClipPolygon(
const geometry::ViewInformation2D& rViewInformation) const;
/// create local decomposition
virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const;
public:
/// constructor
BorderLinePrimitive2D(
const basegfx::B2DPoint& rStart,
const basegfx::B2DPoint& rEnd,
double fLeftWidth,
double fDistance,
double fRightWidth,
double fExtendLeftStart,
double fExtendLeftEnd,
double fExtendRightStart,
double fExtendRightEnd,
const basegfx::BColor& rRGBColorRight,
const basegfx::BColor& rRGBColorLeft,
const basegfx::BColor& rRGBColorGap,
bool bHasGapColor,
const short nStyle );
/// data read access
const basegfx::B2DPoint& getStart() const { return maStart; }
const basegfx::B2DPoint& getEnd() const { return maEnd; }
double getLeftWidth() const { return mfLeftWidth; }
double getDistance() const { return mfDistance; }
double getRightWidth() const { return mfRightWidth; }
double getExtendLeftStart() const { return mfExtendLeftStart; }
double getExtendLeftEnd() const { return mfExtendLeftEnd; }
double getExtendRightStart() const { return mfExtendRightStart; }
double getExtendRightEnd() const { return mfExtendRightEnd; }
const basegfx::BColor& getRGBColorRight () const { return maRGBColorRight; }
const basegfx::BColor& getRGBColorLeft () const { return maRGBColorLeft; }
const basegfx::BColor& getRGBColorGap () const { return maRGBColorGap; }
bool hasGapColor( ) const { return mbHasGapColor; }
short getStyle () const { return mnStyle; }
/// compare operator
virtual bool operator==(const BasePrimitive2D& rPrimitive) const;
/// provide unique ID
DeclPrimitrive2DIDBlock()
};
} // end of namespace primitive2d
} // end of namespace drawinglayer
//////////////////////////////////////////////////////////////////////////////
#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE2D_BORDERLINEPRIMITIVE2D_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>-Werror,-Wunused-private-field (Clang towards 3.2)<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE2D_BORDERLINEPRIMITIVE2D_HXX
#define INCLUDED_DRAWINGLAYER_PRIMITIVE2D_BORDERLINEPRIMITIVE2D_HXX
#include <drawinglayer/drawinglayerdllapi.h>
#include <drawinglayer/primitive2d/baseprimitive2d.hxx>
#include <basegfx/color/bcolor.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <svtools/ctrlbox.hxx>
//////////////////////////////////////////////////////////////////////////////
namespace drawinglayer
{
namespace primitive2d
{
/** BorderLinePrimitive2D class
This is the basic primitive to build frames around objects, e.g. tables.
It defines a single or double line from Start to nd using the LeftWidth,
Distance and RightWidth definitions.
The LineStart/End overlap is defined by the Extend(Inner|Outer)(Start|End)
definitions.
*/
class DRAWINGLAYER_DLLPUBLIC BorderLinePrimitive2D : public BufferedDecompositionPrimitive2D
{
private:
/// the line definition
basegfx::B2DPoint maStart;
basegfx::B2DPoint maEnd;
/// the widths of single/double line
double mfLeftWidth;
double mfDistance;
double mfRightWidth;
/// edge overlap sizes
double mfExtendLeftStart;
double mfExtendLeftEnd;
double mfExtendRightStart;
double mfExtendRightEnd;
/// the line colors
basegfx::BColor maRGBColorRight;
basegfx::BColor maRGBColorLeft;
basegfx::BColor maRGBColorGap;
bool mbHasGapColor;
short mnStyle;
/// local helpers
double getWidth(
const geometry::ViewInformation2D& rViewInformation) const;
bool isSolidLine() const
{
return (mnStyle==STYLE_SOLID);
}
bool isInsideUsed() const
{
return !basegfx::fTools::equalZero(mfLeftWidth);
}
bool isOutsideUsed() const
{
return !basegfx::fTools::equalZero(mfRightWidth);
}
protected:
virtual basegfx::B2DPolyPolygon getClipPolygon(
const geometry::ViewInformation2D& rViewInformation) const;
/// create local decomposition
virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const;
public:
/// constructor
BorderLinePrimitive2D(
const basegfx::B2DPoint& rStart,
const basegfx::B2DPoint& rEnd,
double fLeftWidth,
double fDistance,
double fRightWidth,
double fExtendLeftStart,
double fExtendLeftEnd,
double fExtendRightStart,
double fExtendRightEnd,
const basegfx::BColor& rRGBColorRight,
const basegfx::BColor& rRGBColorLeft,
const basegfx::BColor& rRGBColorGap,
bool bHasGapColor,
const short nStyle );
/// data read access
const basegfx::B2DPoint& getStart() const { return maStart; }
const basegfx::B2DPoint& getEnd() const { return maEnd; }
double getLeftWidth() const { return mfLeftWidth; }
double getDistance() const { return mfDistance; }
double getRightWidth() const { return mfRightWidth; }
double getExtendLeftStart() const { return mfExtendLeftStart; }
double getExtendLeftEnd() const { return mfExtendLeftEnd; }
double getExtendRightStart() const { return mfExtendRightStart; }
double getExtendRightEnd() const { return mfExtendRightEnd; }
const basegfx::BColor& getRGBColorRight () const { return maRGBColorRight; }
const basegfx::BColor& getRGBColorLeft () const { return maRGBColorLeft; }
const basegfx::BColor& getRGBColorGap () const { return maRGBColorGap; }
bool hasGapColor( ) const { return mbHasGapColor; }
short getStyle () const { return mnStyle; }
/// compare operator
virtual bool operator==(const BasePrimitive2D& rPrimitive) const;
/// provide unique ID
DeclPrimitrive2DIDBlock()
};
} // end of namespace primitive2d
} // end of namespace drawinglayer
//////////////////////////////////////////////////////////////////////////////
#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE2D_BORDERLINEPRIMITIVE2D_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <chrono>
#include "aggregate_bandwidth.cpp"
#include "aggregate_bandwidth.hpp"
#include "bytes_object.hpp"
#include "log_results.hpp"
#include <derecho/conf/conf.hpp>
#include <derecho/core/derecho.hpp>
#include <derecho/mutils-serialization/SerializationSupport.hpp>
#include <derecho/persistent/Persistent.hpp>
#include "partial_senders_allocator.hpp"
using std::endl;
using test::Bytes;
using namespace std::chrono;
/**
* RPC Object with a single function that accepts a string
*/
class TestObject {
public:
void fun(const std::string& words) {
}
void bytes_fun(const Bytes& bytes) {
}
bool finishing_call(int x) {
return true;
}
REGISTER_RPC_FUNCTIONS(TestObject, ORDERED_TARGETS(fun, bytes_fun, finishing_call));
};
struct exp_result {
int num_nodes;
uint32_t num_sender_sel;
long long unsigned int max_msg_size;
unsigned int window_size;
uint32_t count;
double avg_msec;
double avg_gbps;
void print(std::ofstream& fout) {
fout << num_nodes << " " << num_sender_sel << " "
<< max_msg_size << " " << window_size << " "
<< count << " "
<< avg_msec << " " << avg_gbps << endl;
}
};
#define DEFAULT_PROC_NAME "typed_bw_test"
int main(int argc, char* argv[]) {
int dashdash_pos = argc - 1;
while(dashdash_pos > 0) {
if(strcmp(argv[dashdash_pos], "--") == 0) {
break;
}
dashdash_pos--;
}
if((argc - dashdash_pos) < 4) {
std::cout << "Invalid command line arguments." << std::endl;
std::cout << "USAGE: " << argv[0] << " [ derecho-config-list -- ] <num_nodes> <count> <num_senders_selector> [proc_name]" << std::endl;
std::cout << "Note: proc_name sets the process's name as displayed in ps and pkill commands, default is " DEFAULT_PROC_NAME << std::endl;
return -1;
}
derecho::Conf::initialize(argc, argv);
//The maximum number of bytes that can be sent to change_pers_bytes() is not quite MAX_PAYLOAD_SIZE.
//The serialized Bytes object will include its size field as well as the actual buffer, and
//the RPC function header contains an InvocationID (which is a size_t) as well as the header
//fields defined by remote_invocation_utilites::header_space().
const std::size_t rpc_header_size = sizeof(std::size_t) + sizeof(std::size_t)
+ derecho::remote_invocation_utilities::header_space();
const int num_nodes = std::stoi(argv[dashdash_pos + 1]);
const uint64_t max_msg_size = derecho::getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE) - rpc_header_size;
const uint32_t count = std::stoi(argv[dashdash_pos + 2]);
const uint32_t num_senders_selector = std::stoi(argv[dashdash_pos + 3]);
steady_clock::time_point begin_time, send_complete_time;
// Convert this integer to a more readable enum value
const PartialSendMode senders_mode = num_senders_selector == 0
? PartialSendMode::ALL_SENDERS
: (num_senders_selector == 1
? PartialSendMode::HALF_SENDERS
: PartialSendMode::ONE_SENDER);
// Compute the total number of messages that should be delivered
uint64_t total_num_messages = 0;
switch(senders_mode) {
case PartialSendMode::ALL_SENDERS:
total_num_messages = count * num_nodes;
break;
case PartialSendMode::HALF_SENDERS:
total_num_messages = count * (num_nodes / 2);
break;
case PartialSendMode::ONE_SENDER:
total_num_messages = count;
break;
}
// variable 'done' tracks the end of the test
volatile bool done = false;
// callback into the application code at each message delivery
auto stability_callback = [&done,
total_num_messages,
num_delivered = 0u,
&send_complete_time](uint32_t subgroup,
uint32_t sender_id,
long long int index,
std::optional<std::pair<char*, long long int>> data,
persistent::version_t ver) mutable {
// Count the total number of messages delivered
++num_delivered;
// Check for completion
if(num_delivered == total_num_messages) {
send_complete_time = std::chrono::steady_clock::now();
done = true;
}
};
if(dashdash_pos + 4 < argc) {
pthread_setname_np(pthread_self(), argv[dashdash_pos + 3]);
} else {
pthread_setname_np(pthread_self(), DEFAULT_PROC_NAME);
}
/*******************
derecho::SubgroupInfo subgroup_info{[num_nodes](
const std::vector<std::type_index>& subgroup_type_order,
const std::unique_ptr<derecho::View>& prev_view, derecho::View& curr_view) {
if(curr_view.num_members < num_nodes) {
std::cout << "not enough members yet:" << curr_view.num_members << " < " << num_nodes << std::endl;
throw derecho::subgroup_provisioning_exception();
}
derecho::subgroup_shard_layout_t subgroup_layout(1);
std::vector<uint32_t> members(num_nodes);
for(int i = 0; i < num_nodes; i++) {
members[i] = i;
}
subgroup_layout[0].emplace_back(curr_view.make_subview(members));
curr_view.next_unassigned_rank = std::max(curr_view.next_unassigned_rank, num_nodes);
derecho::subgroup_allocation_map_t subgroup_allocation;
subgroup_allocation.emplace(std::type_index(typeid(TestObject)), std::move(subgroup_layout));
return subgroup_allocation;
}};
*****************/
auto membership_function = PartialSendersAllocator(num_nodes, senders_mode, derecho::Mode::ORDERED);
derecho::SubgroupInfo subgroup_info(membership_function);
auto ba_factory = [](persistent::PersistentRegistry*, derecho::subgroup_id_t) { return std::make_unique<TestObject>(); };
derecho::Group<TestObject> group(derecho::UserMessageCallbacks{stability_callback}, subgroup_info, {}, std::vector<derecho::view_upcall_t>{}, ba_factory);
std::cout << "Finished constructing/joining Group" << std::endl;
//std::string str_1k(max_msg_size, 'x');
char* bbuf = (char*)malloc(max_msg_size);
bzero(bbuf, max_msg_size);
Bytes bytes(bbuf, max_msg_size);
// this function sends all the messages
auto send_all = [&]() {
for(uint i = 0; i < count; i++) {
derecho::Replicated<TestObject>& handle = group.get_subgroup<TestObject>();
handle.ordered_send<RPC_NAME(bytes_fun)>(bytes);
}
};
int node_rank = group.get_my_rank();
// Begin Clock Timer
begin_time = std::chrono::steady_clock::now();
if(senders_mode == PartialSendMode::ALL_SENDERS) {
send_all();
} else if(senders_mode == PartialSendMode::HALF_SENDERS) {
if(node_rank > (num_nodes - 1) / 2) {
send_all();
}
} else {
if(node_rank == num_nodes - 1) {
send_all();
}
}
/*
if(node_rank == 0) {
derecho::rpc::QueryResults<bool> results = handle.ordered_send<RPC_NAME(finishing_call)>(0);
std::cout << "waiting for response..." << std::endl;
#pragma GCC diagnostic ignored "-Wunused-variable"
decltype(results)::ReplyMap& replies = results.get();
#pragma GCC diagnostic pop
}
*/
while(!done){
}
free(bbuf);
int64_t nsec = duration_cast<nanoseconds>(send_complete_time - begin_time).count();
double thp_gbps = (static_cast<double>(total_num_messages) * max_msg_size) / nsec;
double msec = (double)nsec / 1000000;
double thp_ops = ((double)count * 1000000000) / nsec;
std::cout << "timespan:" << msec << " millisecond." << std::endl;
std::cout << "throughput:" << thp_gbps << "GB/s." << std::endl;
std::cout << "throughput:" << thp_ops << "ops." << std::endl;
std::cout << std::flush;
// aggregate bandwidth from all nodes
std::pair<double, double> bw_laten(thp_gbps,msec);
auto members_order = group.get_members();
bw_laten = aggregate_bandwidth(members_order, members_order[node_rank], bw_laten);
double avg_gbps = bw_laten.first;
double avg_msec = bw_laten.second;
if(node_rank == 0) {
log_results(exp_result{num_nodes, num_senders_selector, max_msg_size,
derecho::getConfUInt32(CONF_SUBGROUP_DEFAULT_WINDOW_SIZE), count,
avg_msec, avg_gbps},
"data_derecho_typed_subgroup_bw");
}
group.barrier_sync();
group.leave();
}
<commit_msg>typed subgroup bw test with latency.<commit_after>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <chrono>
#include "aggregate_bandwidth.cpp"
#include "aggregate_bandwidth.hpp"
#include "bytes_object.hpp"
#include "log_results.hpp"
#include <derecho/conf/conf.hpp>
#include <derecho/core/derecho.hpp>
#include <derecho/mutils-serialization/SerializationSupport.hpp>
#include <derecho/persistent/Persistent.hpp>
#include "partial_senders_allocator.hpp"
#include <derecho/utils/time.h>
using std::endl;
using test::Bytes;
using namespace std::chrono;
/**
* RPC Object with a single function that accepts a string
*/
class TestObject : public derecho::GroupReference {
public:
/* group reference */
using derecho::GroupReference::group;
void fun(const std::string& words);
std::tuple<persistent::version_t,uint64_t> bytes_fun(const Bytes& bytes);
bool finishing_call(int x);
REGISTER_RPC_FUNCTIONS(TestObject, ORDERED_TARGETS(fun, bytes_fun, finishing_call));
};
void TestObject::fun(const std::string& words) {}
std::tuple<persistent::version_t,uint64_t> TestObject::bytes_fun(const Bytes& bytes) {
return group->template get_subgroup<TestObject>(this->subgroup_index).get_current_version();
}
bool TestObject::finishing_call(int x) {
return true;
}
struct exp_result {
int num_nodes;
uint32_t num_sender_sel;
long long unsigned int max_msg_size;
unsigned int window_size;
uint32_t count;
double avg_msec;
double avg_gbps;
void print(std::ofstream& fout) {
fout << num_nodes << " " << num_sender_sel << " "
<< max_msg_size << " " << window_size << " "
<< count << " "
<< avg_msec << " " << avg_gbps << endl;
}
};
#define DEFAULT_PROC_NAME "typed_bw_test"
int main(int argc, char* argv[]) {
int dashdash_pos = argc - 1;
while(dashdash_pos > 0) {
if(strcmp(argv[dashdash_pos], "--") == 0) {
break;
}
dashdash_pos--;
}
if((argc - dashdash_pos) < 4) {
std::cout << "Invalid command line arguments." << std::endl;
std::cout << "USAGE: " << argv[0] << " [ derecho-config-list -- ] <num_nodes> <count> <num_senders_selector> [proc_name]" << std::endl;
std::cout << "Note: proc_name sets the process's name as displayed in ps and pkill commands, default is " DEFAULT_PROC_NAME << std::endl;
return -1;
}
derecho::Conf::initialize(argc, argv);
//The maximum number of bytes that can be sent to change_pers_bytes() is not quite MAX_PAYLOAD_SIZE.
//The serialized Bytes object will include its size field as well as the actual buffer, and
//the RPC function header contains an InvocationID (which is a size_t) as well as the header
//fields defined by remote_invocation_utilites::header_space().
const std::size_t rpc_header_size = sizeof(std::size_t) + sizeof(std::size_t)
+ derecho::remote_invocation_utilities::header_space();
const int num_nodes = std::stoi(argv[dashdash_pos + 1]);
const uint64_t max_msg_size = derecho::getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE) - rpc_header_size;
const uint32_t count = std::stoi(argv[dashdash_pos + 2]);
const uint32_t num_senders_selector = std::stoi(argv[dashdash_pos + 3]);
steady_clock::time_point begin_time, send_complete_time;
// Convert this integer to a more readable enum value
const PartialSendMode senders_mode = num_senders_selector == 0
? PartialSendMode::ALL_SENDERS
: (num_senders_selector == 1
? PartialSendMode::HALF_SENDERS
: PartialSendMode::ONE_SENDER);
// Compute the total number of messages that should be delivered
uint64_t total_num_messages = 0;
switch(senders_mode) {
case PartialSendMode::ALL_SENDERS:
total_num_messages = count * num_nodes;
break;
case PartialSendMode::HALF_SENDERS:
total_num_messages = count * (num_nodes / 2);
break;
case PartialSendMode::ONE_SENDER:
total_num_messages = count;
break;
}
// map from version to timestamp in ns.
std::map <persistent::version_t,uint64_t> stable_ts;
std::vector<std::tuple<persistent::version_t,uint64_t,uint64_t>> timestamp_log;
timestamp_log.reserve(total_num_messages);
// variable 'done' tracks the end of the test
volatile bool done = false;
// callback into the application code at each message delivery
auto stability_callback = [&done,
total_num_messages,
num_delivered = 0u,
&stable_ts,
&send_complete_time](uint32_t subgroup,
uint32_t sender_id,
long long int index,
std::optional<std::pair<char*, long long int>> data,
persistent::version_t ver) mutable {
// Count the total number of messages delivered
++num_delivered;
stable_ts.emplace(ver,get_walltime());
// Check for completion
if(num_delivered == total_num_messages) {
send_complete_time = std::chrono::steady_clock::now();
done = true;
}
};
if(dashdash_pos + 4 < argc) {
pthread_setname_np(pthread_self(), argv[dashdash_pos + 3]);
} else {
pthread_setname_np(pthread_self(), DEFAULT_PROC_NAME);
}
auto membership_function = PartialSendersAllocator(num_nodes, senders_mode, derecho::Mode::ORDERED);
derecho::SubgroupInfo subgroup_info(membership_function);
auto ba_factory = [](persistent::PersistentRegistry*, derecho::subgroup_id_t) { return std::make_unique<TestObject>(); };
derecho::Group<TestObject> group(derecho::UserMessageCallbacks{stability_callback}, subgroup_info, {}, std::vector<derecho::view_upcall_t>{}, ba_factory);
std::cout << "Finished constructing/joining Group" << std::endl;
//std::string str_1k(max_msg_size, 'x');
char* bbuf = (char*)malloc(max_msg_size);
bzero(bbuf, max_msg_size);
Bytes bytes(bbuf, max_msg_size);
// this function sends all the messages
auto send_all = [&](std::vector<std::tuple<persistent::version_t,uint64_t,uint64_t>>& timestamp_log) {
// 1 - synchronization data structures
uint32_t window_size = derecho::getConfUInt32(CONF_SUBGROUP_DEFAULT_WINDOW_SIZE);
uint32_t window_slots = window_size*2;
std::mutex window_slots_mutex;
std::condition_variable window_slots_cv;
std::queue<std::pair<uint64_t,derecho::QueryResults<std::tuple<persistent::version_t,uint64_t>>>> futures;
std::mutex futures_mutex;
std::condition_variable futures_cv;
std::atomic<bool> all_sent(false);
// 2 - query thread
std::thread query_thread(
[×tamp_log,&window_slots,&window_slots_mutex,&window_slots_cv,&futures,&futures_mutex,&futures_cv,&all_sent](){
std::unique_lock<std::mutex> futures_lck{futures_mutex};
while(!all_sent || (futures.size()>0)) {
// pick pending futures
using namespace std::chrono_literals;
while(!futures_cv.wait_for(futures_lck,500ms,[&futures,&all_sent]{return(futures.size()>0)||all_sent;}));
std::decay_t<decltype(futures)> pending_futures;
futures.swap(pending_futures);
futures_lck.unlock();
// queue unlocked
while (pending_futures.size()>0) {
auto& replies = pending_futures.front().second.get();
for (auto& reply: replies) {
auto version = std::get<0>(reply.second.get());
uint64_t reply_timestamp_ns = get_walltime();
uint64_t send_timestamp_ns = pending_futures.front().first;
timestamp_log.emplace_back(version, send_timestamp_ns, reply_timestamp_ns);
break;
}
pending_futures.pop();
{
std::lock_guard<std::mutex> window_slots_lock{window_slots_mutex};
window_slots ++;
}
window_slots_cv.notify_one();
}
futures_lck.lock();
}
});
for(uint i = 0; i < count; i++) {
// acquire a window_slot
{
std::unique_lock<std::mutex> window_slots_lock{window_slots_mutex};
window_slots_cv.wait(window_slots_lock,[&window_slots]{return (window_slots >0);});
window_slots --;
}
// send
derecho::Replicated<TestObject>& handle = group.get_subgroup<TestObject>();
auto qr = handle.ordered_send<RPC_NAME(bytes_fun)>(bytes);
// insert future
{
uint64_t timestamp_ns = get_walltime();
std::unique_lock<std::mutex> future_lock{futures_mutex};
futures.emplace(timestamp_ns,std::move(qr));
}
futures_cv.notify_one();
}
all_sent.store(true);
query_thread.join();
};
int node_rank = group.get_my_rank();
// Begin Clock Timer
begin_time = std::chrono::steady_clock::now();
if(senders_mode == PartialSendMode::ALL_SENDERS) {
send_all(timestamp_log);
} else if(senders_mode == PartialSendMode::HALF_SENDERS) {
if(node_rank > (num_nodes - 1) / 2) {
send_all(timestamp_log);
}
} else {
if(node_rank == num_nodes - 1) {
send_all(timestamp_log);
}
}
while(!done);
free(bbuf);
int64_t nsec = duration_cast<nanoseconds>(send_complete_time - begin_time).count();
double thp_gbps = (static_cast<double>(total_num_messages) * max_msg_size) / nsec;
double msec = (double)nsec / 1000000;
double thp_ops = ((double)count * 1000000000) / nsec;
std::cout << "timespan:" << msec << " millisecond." << std::endl;
std::cout << "throughput:" << thp_gbps << "GB/s." << std::endl;
std::cout << "throughput:" << thp_ops << "ops." << std::endl;
std::cout << std::flush;
// aggregate bandwidth from all nodes
std::pair<double, double> bw_laten(thp_gbps,msec);
auto members_order = group.get_members();
bw_laten = aggregate_bandwidth(members_order, members_order[node_rank], bw_laten);
double avg_gbps = bw_laten.first;
double avg_msec = bw_laten.second;
if(node_rank == 0) {
log_results(exp_result{num_nodes, num_senders_selector, max_msg_size,
derecho::getConfUInt32(CONF_SUBGROUP_DEFAULT_WINDOW_SIZE), count,
avg_msec, avg_gbps},
"data_derecho_typed_subgroup_bw");
}
// write timestamp log into file
std::ofstream ofile(DEFAULT_PROC_NAME);
ofile << "#ver send(us) stable(us) acked(us)" << std::endl;
for (auto t: timestamp_log) {
auto ver = std::get<0>(t);
ofile << ver << "\t" << std::get<1>(t)/1000 << "\t" << stable_ts.at(ver)/1000 << "\t" << std::get<2>(t)/1000 << std::endl;
}
group.barrier_sync();
group.leave();
}
<|endoftext|>
|
<commit_before>#include <boost/test/unit_test.hpp>
#include <fstream>
#include <streambuf>
#include <string>
// xerces
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/sax2/DefaultHandler.hpp>
#include <xercesc/util/XMLString.hpp>
// wiki xml dump lib
#include "../../s3_recursiveFillCategories.h"
#include "../helpers/buildArtificialDump.h"
#include "../../../core/wikiDataCache.h"
#include "../../sortTitlesHelper.h"
#include "../../wikiArticleHandlers/articleDatesAndCategoriesHandler.h"
#include "../../wikiArticleHandlers/allLinksArticleHandler.h"
#include "../../../../libs/wiki_xml_dump_xerces/src/parsers/singleCoreParser.hpp"
#include "../../../../libs/wiki_xml_dump_xerces/src/handlers/wikiDumpHandlerProperties.hpp"
#include "../../../../libs/wiki_xml_dump_xerces/src/handlers/basicTitleFilters.hpp"
BOOST_AUTO_TEST_SUITE(category_has_article_tests)
BOOST_AUTO_TEST_CASE(check_if_recursive_articles_are_detected_articial)
{
std::vector<std::string> titles = { "A", "B", "C", "D", "E", "Category:C1", "Category:C2", "Category:C3" };
std::vector<std::pair<std::string,std::string>> expected_links = {
{ "A", "C" },
{ "A", "D" },
{ "C", "D" },
{ "D", "E" },
{ "D", "A" },
{ "D", "C" },
{ "E", "A" },
{ "A", "Category:C3" },
{ "B", "Category:C3" },
{ "C", "Category:C2" },
{ "D", "Category:C1" },
{ "Category:C2", "Category:C1" },
{ "Category:C3", "Category:C2" },
};
std::vector<std::pair<std::string,std::string>> expected_category_containment = {
{ "A", "Category:C1" },
{ "A", "Category:C2" },
{ "A", "Category:C3" },
};
std::string content = build_artificial_dump(titles, expected_links);
WikiXmlDumpXerces::WikiDumpHandlerProperties parser_properties;
parser_properties.TitleFilter = WikiXmlDumpXerces::only_articles_and_categories();
// init xerces
xercesc::XMLPlatformUtils::Initialize();
// run parsing
auto article_titles_stream = std::make_shared<std::stringstream>();
auto article_dates_stream = std::make_shared<std::stringstream>();
auto category_titles_stream = std::make_shared<std::stringstream>();
auto redirects_stream = std::make_shared<std::stringstream>();
std::mutex article_titles_mutex;
std::mutex category_titles_mutex;
std::mutex redirect_mutex;
ArticleDatesAndCategoriesHandler art_handler(*article_titles_stream, *article_dates_stream, *category_titles_stream, *redirects_stream, article_titles_mutex, category_titles_mutex, redirect_mutex);
art_handler.ExtractOnlyArticlesWithDates = false;
WikiXmlDumpXerces::SingleCoreParser parser(art_handler, parser_properties);
parser.RunOnString(content);
article_titles_stream->seekg(0);
article_dates_stream->seekg(0);
category_titles_stream->seekg(0);
redirects_stream->seekg(0);
// terminate xerces
auto article_titles_sorted_stream = std::make_shared<std::stringstream>();
auto article_dates_sorted_stream = std::make_shared<std::stringstream>();
auto category_titles_sorted_stream = std::make_shared<std::stringstream>();
sort_article_files(*article_titles_stream, *article_dates_stream, *article_titles_sorted_stream, *article_dates_sorted_stream);
sort_category_files(*category_titles_stream, *category_titles_sorted_stream);
article_titles_sorted_stream->seekg(0);
category_titles_sorted_stream->seekg(0);
WikiMainPath::WikiDataCache wiki_data_cache(article_titles_sorted_stream, article_dates_sorted_stream, category_titles_sorted_stream, redirects_stream);
auto& article_titles = wiki_data_cache.article_titles();
auto& category_titles = wiki_data_cache.category_titles();
auto& redirects = wiki_data_cache.redirects();
std::vector<boost::container::flat_set<std::size_t>> category_has_article(category_titles.size());
AllLinksArticleHander::CategoryHirachyGraph category_hirachy_graph(category_titles.size());
std::vector<boost::container::flat_set<std::size_t>> article_adjacency_list(article_titles.size());
VectorMutex<1000> vector_mutex;
AllLinksArticleHander all_links_handler(article_titles, category_titles, redirects, category_has_article, category_hirachy_graph, article_adjacency_list, vector_mutex);
WikiXmlDumpXerces::SingleCoreParser parser2(all_links_handler, parser_properties);
parser2.RunOnString(content);
xercesc::XMLPlatformUtils::Terminate();
recursiveFillCategories(category_hirachy_graph, category_has_article);
for (auto containment : expected_category_containment) {
auto it_1 = std::find(article_titles.begin(), article_titles.end(), containment.first);
auto it_2 = std::find(category_titles.begin(), category_titles.end(), containment.second);
bool found_article = it_1 != article_titles.end();
bool found_category= it_2 != category_titles.end();
BOOST_CHECK(found_article);
BOOST_CHECK(found_category);
std::size_t i_article = it_1-article_titles.begin();
std::size_t i_category = it_2-category_titles.begin();
if(found_article && found_category)
{
bool found = std::find(category_has_article[i_category].begin(), category_has_article[i_category].end(), i_article) != category_has_article[i_category].end();
if(!found)
std::cout << containment.first << " - " << containment.second << std::endl;
BOOST_CHECK(found);
}
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Identified some error in category has article<commit_after>#include <boost/test/unit_test.hpp>
#include <fstream>
#include <streambuf>
#include <string>
// xerces
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/sax2/DefaultHandler.hpp>
#include <xercesc/util/XMLString.hpp>
// wiki xml dump lib
#include "../../s3_recursiveFillCategories.h"
#include "../helpers/buildArtificialDump.h"
#include "../../../core/wikiDataCache.h"
#include "../../sortTitlesHelper.h"
#include "../../wikiArticleHandlers/articleDatesAndCategoriesHandler.h"
#include "../../wikiArticleHandlers/allLinksArticleHandler.h"
#include "../../../../libs/wiki_xml_dump_xerces/src/parsers/singleCoreParser.hpp"
#include "../../../../libs/wiki_xml_dump_xerces/src/handlers/wikiDumpHandlerProperties.hpp"
#include "../../../../libs/wiki_xml_dump_xerces/src/handlers/basicTitleFilters.hpp"
BOOST_AUTO_TEST_SUITE(category_has_article_tests)
BOOST_AUTO_TEST_CASE(check_if_recursive_articles_are_detected_articial)
{
std::vector<std::string> titles = { "A", "B", "C", "D", "E", "Category:C1", "Category:C2", "Category:C3" };
std::vector<std::pair<std::string,std::string>> expected_links = {
{ "A", "C" },
{ "A", "D" },
{ "C", "D" },
{ "D", "E" },
{ "D", "A" },
{ "D", "C" },
{ "E", "A" },
{ "A", "Category:C3" },
{ "B", "Category:C3" },
{ "C", "Category:C2" },
{ "D", "Category:C1" },
{ "Category:C2", "Category:C1" },
{ "Category:C3", "Category:C2" },
};
std::vector<std::pair<std::string,std::string>> expected_category_containment = {
{ "A", "C1" },
{ "A", "C2" },
{ "A", "C3" },
};
std::string content = build_artificial_dump(titles, expected_links);
WikiXmlDumpXerces::WikiDumpHandlerProperties parser_properties;
parser_properties.TitleFilter = WikiXmlDumpXerces::only_articles_and_categories();
// init xerces
xercesc::XMLPlatformUtils::Initialize();
// run parsing
auto article_titles_stream = std::make_shared<std::stringstream>();
auto article_dates_stream = std::make_shared<std::stringstream>();
auto category_titles_stream = std::make_shared<std::stringstream>();
auto redirects_stream = std::make_shared<std::stringstream>();
std::mutex article_titles_mutex;
std::mutex category_titles_mutex;
std::mutex redirect_mutex;
ArticleDatesAndCategoriesHandler art_handler(*article_titles_stream, *article_dates_stream, *category_titles_stream, *redirects_stream, article_titles_mutex, category_titles_mutex, redirect_mutex);
art_handler.ExtractOnlyArticlesWithDates = false;
WikiXmlDumpXerces::SingleCoreParser parser(art_handler, parser_properties);
parser.RunOnString(content);
article_titles_stream->seekg(0);
article_dates_stream->seekg(0);
category_titles_stream->seekg(0);
redirects_stream->seekg(0);
// terminate xerces
auto article_titles_sorted_stream = std::make_shared<std::stringstream>();
auto article_dates_sorted_stream = std::make_shared<std::stringstream>();
auto category_titles_sorted_stream = std::make_shared<std::stringstream>();
sort_article_files(*article_titles_stream, *article_dates_stream, *article_titles_sorted_stream, *article_dates_sorted_stream);
sort_category_files(*category_titles_stream, *category_titles_sorted_stream);
article_titles_sorted_stream->seekg(0);
category_titles_sorted_stream->seekg(0);
WikiMainPath::WikiDataCache wiki_data_cache(article_titles_sorted_stream, article_dates_sorted_stream, category_titles_sorted_stream, redirects_stream);
auto& article_titles = wiki_data_cache.article_titles();
auto& category_titles = wiki_data_cache.category_titles();
auto& redirects = wiki_data_cache.redirects();
std::vector<boost::container::flat_set<std::size_t>> category_has_article(category_titles.size());
AllLinksArticleHander::CategoryHirachyGraph category_hirachy_graph(category_titles.size());
std::vector<boost::container::flat_set<std::size_t>> article_adjacency_list(article_titles.size());
VectorMutex<1000> vector_mutex;
AllLinksArticleHander all_links_handler(article_titles, category_titles, redirects, category_has_article, category_hirachy_graph, article_adjacency_list, vector_mutex);
WikiXmlDumpXerces::SingleCoreParser parser2(all_links_handler, parser_properties);
parser2.RunOnString(content);
xercesc::XMLPlatformUtils::Terminate();
for (auto title : category_titles) {
std::cout << title << std::endl;
}
recursiveFillCategories(category_hirachy_graph, category_has_article);
for (auto containment : expected_category_containment) {
auto it_1 = std::find(article_titles.begin(), article_titles.end(), containment.first);
auto it_2 = std::find(category_titles.begin(), category_titles.end(), containment.second);
bool found_article = it_1 != article_titles.end();
bool found_category= it_2 != category_titles.end();
BOOST_CHECK(found_article);
BOOST_CHECK(found_category);
std::size_t i_article = it_1-article_titles.begin();
std::size_t i_category = it_2-category_titles.begin();
if(found_article && found_category)
{
bool found = std::find(category_has_article[i_category].begin(), category_has_article[i_category].end(), i_article) != category_has_article[i_category].end();
if(!found)
std::cout << containment.first << " - " << containment.second << std::endl;
BOOST_CHECK(found);
}
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "navigatortreemodel.h"
#include <nodeabstractproperty.h>
#include <nodelistproperty.h>
#include <abstractview.h>
#include <qmlitemnode.h>
#include <invalididexception.h>
#include <QMimeData>
namespace QmlDesigner {
NavigatorTreeModel::NavigatorTreeModel(QObject *parent)
: QStandardItemModel(parent)
{
invisibleRootItem()->setFlags(Qt::NoItemFlags);
setHorizontalHeaderItem(0, new QStandardItem(tr("Name")));
setHorizontalHeaderItem(1, new QStandardItem(tr("Type")));
setHorizontalHeaderItem(2, new QStandardItem(tr("Show in Editor")));
setSupportedDragActions(Qt::LinkAction);
connect(this, SIGNAL(itemChanged(QStandardItem*)),
this, SLOT(handleChangedItem(QStandardItem*)));
}
NavigatorTreeModel::~NavigatorTreeModel()
{
}
Qt::DropActions NavigatorTreeModel::supportedDropActions() const
{
return Qt::LinkAction;
}
QStringList NavigatorTreeModel::mimeTypes() const
{
QStringList types;
types << "application/vnd.modelnode.list";
return types;
}
QMimeData *NavigatorTreeModel::mimeData(const QModelIndexList &indexList) const
{
QMimeData *mimeData = new QMimeData();
QByteArray encodedData;
QSet<QModelIndex> rowAlreadyUsedSet;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
foreach (const QModelIndex &index, indexList) {
if (!index.isValid())
continue;
QModelIndex idIndex = index.sibling(index.row(), 0);
if (rowAlreadyUsedSet.contains(idIndex))
continue;
rowAlreadyUsedSet.insert(idIndex);
stream << idIndex.data(Qt::UserRole).toUInt();
}
mimeData->setData("application/vnd.modelnode.list", encodedData);
return mimeData;
}
static bool isAnchestorInList(const ModelNode &node, const QList<ModelNode> &nodeList)
{
foreach (const ModelNode &nodeInList, nodeList) {
if (nodeInList.isAncestorOf(node))
return true;
}
return false;
}
bool NavigatorTreeModel::dropMimeData(const QMimeData *data,
Qt::DropAction action,
int row,
int column,
const QModelIndex &parentIndex)
{
if (action == Qt::IgnoreAction)
return true;
if (action != Qt::LinkAction)
return false;
if (!data->hasFormat("application/vnd.modelnode.list"))
return false;
if (column > 1)
return false;
if (parentIndex.model() != this)
return false;
QModelIndex parentIdIndex = parentIndex;
parentIdIndex = parentIdIndex.sibling(parentIdIndex.row(), 0);
Q_ASSERT(parentIdIndex.isValid());
int targetIndex = 0;
if (row > -1) {
targetIndex = row;
} else {
targetIndex = rowCount(parentIdIndex);
}
QByteArray encodedData = data->data("application/vnd.modelnode.list");
QDataStream stream(&encodedData, QIODevice::ReadOnly);
uint nodeHash = parentIdIndex.data(Qt::UserRole).toUInt();
QmlItemNode parentItemNode(nodeForHash(nodeHash));
QList<ModelNode> nodeList;
while (!stream.atEnd()) {
uint nodeHash;
stream >> nodeHash;
ModelNode node(nodeForHash(nodeHash));
if (!node.isValid() || node.isAncestorOf(parentItemNode))
return false;
nodeList.append(node);
}
RewriterTransaction transaction = m_view->beginRewriterTransaction();
foreach (const ModelNode &node, nodeList) {
if (!isAnchestorInList(node, nodeList)) {
if (node.parentProperty().parentModelNode() != parentItemNode) {
QmlItemNode itemNode(node);
if (node != parentItemNode) {
itemNode.setParent(parentItemNode);
}
}
if (node.parentProperty().isNodeListProperty()) {
int index = node.parentProperty().toNodeListProperty().toModelNodeList().indexOf(node);
if (index < targetIndex) { // item is first removed from oldIndex, then inserted at new index
--targetIndex;
}
if (index != targetIndex) {
node.parentProperty().toNodeListProperty().slide(index, targetIndex);
}
}
}
}
return false; // don't let the view do drag&drop on its own
}
NavigatorTreeModel::ItemRow NavigatorTreeModel::createItemRow(const ModelNode &node)
{
Q_ASSERT(node.isValid());
uint hash = qHash(node);
QStandardItem *idItem = new QStandardItem;
idItem->setDragEnabled(true);
idItem->setDropEnabled(node.metaInfo().isContainer());
idItem->setEditable(true);
idItem->setData(hash, Qt::UserRole);
QStandardItem *typeItem = new QStandardItem;
typeItem->setDragEnabled(true);
idItem->setDropEnabled(node.metaInfo().isContainer());
typeItem->setEditable(false);
typeItem->setData(hash, Qt::UserRole);
QStandardItem *visibilityItem = new QStandardItem;
visibilityItem->setDropEnabled(node.metaInfo().isContainer());
visibilityItem->setCheckable(true);
visibilityItem->setData(hash, Qt::UserRole);
return ItemRow(idItem, typeItem, visibilityItem);
}
void NavigatorTreeModel::updateItemRow(const ModelNode &node, ItemRow items)
{
items.idItem->setText(node.id());
items.typeItem->setText(node.simplifiedTypeName());
items.visibilityItem->setCheckState(node.auxiliaryData("invisible").toBool() ? Qt::Unchecked : Qt::Checked);
}
/**
Update the information shown for a node / property
*/
void NavigatorTreeModel::updateItemRow(const ModelNode &node)
{
if (!containsNode(node))
return;
updateItemRow(node, itemRowForNode(node));
}
/**
Updates the sibling position of the item, depending on the position in the model.
*/
void NavigatorTreeModel::updateItemRowOrder(const ModelNode &node)
{
if (!containsNode(node))
return;
ItemRow itemRow = itemRowForNode(node);
int currentRow = itemRow.idItem->row();
int newRow = currentRow;
if (node.parentProperty().parentModelNode().isValid())
newRow = modelNodeChildren(node.parentProperty().parentModelNode()).indexOf(node);
Q_ASSERT(newRow >= 0);
if (currentRow != newRow) {
QStandardItem *parentIdItem = itemRow.idItem->parent();
QList<QStandardItem*> items = parentIdItem->takeRow(currentRow);
parentIdItem->insertRow(newRow, items);
}
}
void NavigatorTreeModel::handleChangedItem(QStandardItem *item)
{
uint nodeHash = item->data(Qt::UserRole).toUInt();
Q_ASSERT(nodeHash && containsNodeHash(nodeHash));
ModelNode node = nodeForHash(nodeHash);
ItemRow itemRow = itemRowForNode(node);
if (item == itemRow.idItem) {
try {
if (ModelNode::isValidId(item->text()))
node.setId(item->text());
else
item->setText(node.id());
} catch (InvalidIdException &) {
item->setText(node.id());
}
} else if (item == itemRow.visibilityItem) {
bool invisible = (item->checkState() == Qt::Unchecked);
node.setAuxiliaryData("invisible", invisible);
}
}
ModelNode NavigatorTreeModel::nodeForHash(uint hash) const
{
ModelNode node = m_nodeHash.value(hash);
Q_ASSERT(node.isValid());
return node;
}
bool NavigatorTreeModel::containsNodeHash(uint hash) const
{
return m_nodeHash.contains(hash);
}
bool NavigatorTreeModel::containsNode(const ModelNode &node) const
{
return m_nodeItemHash.contains(node);
}
NavigatorTreeModel::ItemRow NavigatorTreeModel::itemRowForNode(const ModelNode &node)
{
Q_ASSERT(node.isValid());
return m_nodeItemHash.value(node);
}
void NavigatorTreeModel::setView(AbstractView *view)
{
m_view = view;
addSubTree(view->rootModelNode());
}
void NavigatorTreeModel::clearView()
{
m_view.clear();
m_nodeHash.clear();
m_nodeItemHash.clear();
clear();
}
QModelIndex NavigatorTreeModel::indexForNode(const ModelNode &node) const
{
Q_ASSERT(node.isValid());
if (!containsNode(node))
return QModelIndex();
ItemRow row = m_nodeItemHash.value(node);
return row.idItem->index();
}
ModelNode NavigatorTreeModel::nodeForIndex(const QModelIndex &index) const
{
Q_ASSERT(index.isValid());
uint hash = index.data(Qt::UserRole).toUInt();
Q_ASSERT(hash);
Q_ASSERT(containsNodeHash(hash));
return nodeForHash(hash);
}
bool NavigatorTreeModel::isInTree(const ModelNode &node) const
{
return m_nodeHash.keys().contains(qHash(node));
}
/**
Adds node & all children to the visible tree hierarchy (if node should be visible at all).
It always adds the node to the _end_ of the list of items.
*/
void NavigatorTreeModel::addSubTree(const ModelNode &node)
{
Q_ASSERT(node.isValid());
Q_ASSERT(!containsNodeHash(qHash(node)));
// only add items that are in the modelNodeChildren list (that means, visible in the editor)
if (!node.isRootNode()
&& !modelNodeChildren(node.parentProperty().parentModelNode()).contains(node)) {
return;
}
ItemRow newRow = createItemRow(node);
m_nodeHash.insert(qHash(node), node);
m_nodeItemHash.insert(node, newRow);
updateItemRow(node, newRow);
foreach (const ModelNode &childNode, modelNodeChildren(node))
addSubTree(childNode);
// We assume that the node is always added to the _end_ of the property list.
if (node.hasParentProperty()) {
ItemRow parentRow = itemRowForNode(node.parentProperty().parentModelNode());
if (parentRow.idItem)
parentRow.idItem->appendRow(newRow.toList());
} else {
appendRow(newRow.toList());
}
}
/**
Deletes visual representation for the node (subtree).
*/
void NavigatorTreeModel::removeSubTree(const ModelNode &node)
{
Q_ASSERT(node.isValid());
if (!containsNode(node))
return;
QList<QStandardItem*> rowList;
ItemRow itemRow = itemRowForNode(node);
if (itemRow.idItem->parent()) {
rowList = itemRow.idItem->parent()->takeRow(itemRow.idItem->row());
}
foreach (const ModelNode &node, modelNodeChildren(node)) {
removeSubTree(node);
}
qDeleteAll(rowList);
m_nodeHash.remove(qHash(node));
m_nodeItemHash.remove(node);
}
QList<ModelNode> NavigatorTreeModel::modelNodeChildren(const ModelNode &parentNode)
{
QList<ModelNode> children;
if (QmlItemNode(parentNode).isValid())
foreach (const QmlItemNode &childNode, QmlItemNode(parentNode).children())
children << childNode.modelNode();
return children;
}
}
<commit_msg>Fix crash in QmlDesigner navigator<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "navigatortreemodel.h"
#include <nodeabstractproperty.h>
#include <nodelistproperty.h>
#include <abstractview.h>
#include <qmlitemnode.h>
#include <invalididexception.h>
#include <QMimeData>
namespace QmlDesigner {
NavigatorTreeModel::NavigatorTreeModel(QObject *parent)
: QStandardItemModel(parent)
{
invisibleRootItem()->setFlags(Qt::NoItemFlags);
setHorizontalHeaderItem(0, new QStandardItem(tr("Name")));
setHorizontalHeaderItem(1, new QStandardItem(tr("Type")));
setHorizontalHeaderItem(2, new QStandardItem(tr("Show in Editor")));
setSupportedDragActions(Qt::LinkAction);
connect(this, SIGNAL(itemChanged(QStandardItem*)),
this, SLOT(handleChangedItem(QStandardItem*)));
}
NavigatorTreeModel::~NavigatorTreeModel()
{
}
Qt::DropActions NavigatorTreeModel::supportedDropActions() const
{
return Qt::LinkAction;
}
QStringList NavigatorTreeModel::mimeTypes() const
{
QStringList types;
types << "application/vnd.modelnode.list";
return types;
}
QMimeData *NavigatorTreeModel::mimeData(const QModelIndexList &indexList) const
{
QMimeData *mimeData = new QMimeData();
QByteArray encodedData;
QSet<QModelIndex> rowAlreadyUsedSet;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
foreach (const QModelIndex &index, indexList) {
if (!index.isValid())
continue;
QModelIndex idIndex = index.sibling(index.row(), 0);
if (rowAlreadyUsedSet.contains(idIndex))
continue;
rowAlreadyUsedSet.insert(idIndex);
stream << idIndex.data(Qt::UserRole).toUInt();
}
mimeData->setData("application/vnd.modelnode.list", encodedData);
return mimeData;
}
static bool isAnchestorInList(const ModelNode &node, const QList<ModelNode> &nodeList)
{
foreach (const ModelNode &nodeInList, nodeList) {
if (nodeInList.isAncestorOf(node))
return true;
}
return false;
}
bool NavigatorTreeModel::dropMimeData(const QMimeData *data,
Qt::DropAction action,
int row,
int column,
const QModelIndex &parentIndex)
{
if (action == Qt::IgnoreAction)
return true;
if (action != Qt::LinkAction)
return false;
if (!data->hasFormat("application/vnd.modelnode.list"))
return false;
if (column > 1)
return false;
if (parentIndex.model() != this)
return false;
QModelIndex parentIdIndex = parentIndex;
parentIdIndex = parentIdIndex.sibling(parentIdIndex.row(), 0);
Q_ASSERT(parentIdIndex.isValid());
int targetIndex = 0;
if (row > -1) {
targetIndex = row;
} else {
targetIndex = rowCount(parentIdIndex);
}
QByteArray encodedData = data->data("application/vnd.modelnode.list");
QDataStream stream(&encodedData, QIODevice::ReadOnly);
QmlItemNode parentItemNode(nodeForIndex(parentIdIndex));
QList<ModelNode> nodeList;
while (!stream.atEnd()) {
uint nodeHash;
stream >> nodeHash;
ModelNode node(nodeForHash(nodeHash));
if (!node.isValid() || (parentItemNode == node) || node.isAncestorOf(parentItemNode))
continue;
nodeList.append(node);
}
RewriterTransaction transaction = m_view->beginRewriterTransaction();
foreach (const ModelNode &node, nodeList) {
if (!isAnchestorInList(node, nodeList)) {
if (node.parentProperty().parentModelNode() != parentItemNode) {
QmlItemNode itemNode(node);
if (node != parentItemNode) {
itemNode.setParent(parentItemNode);
}
}
if (node.parentProperty().isNodeListProperty()) {
int index = node.parentProperty().toNodeListProperty().toModelNodeList().indexOf(node);
if (index < targetIndex) { // item is first removed from oldIndex, then inserted at new index
--targetIndex;
}
if (index != targetIndex) {
node.parentProperty().toNodeListProperty().slide(index, targetIndex);
}
}
}
}
return false; // don't let the view do drag&drop on its own
}
NavigatorTreeModel::ItemRow NavigatorTreeModel::createItemRow(const ModelNode &node)
{
Q_ASSERT(node.isValid());
uint hash = qHash(node);
QStandardItem *idItem = new QStandardItem;
idItem->setDragEnabled(true);
idItem->setDropEnabled(node.metaInfo().isContainer());
idItem->setEditable(true);
idItem->setData(hash, Qt::UserRole);
QStandardItem *typeItem = new QStandardItem;
typeItem->setDragEnabled(true);
idItem->setDropEnabled(node.metaInfo().isContainer());
typeItem->setEditable(false);
typeItem->setData(hash, Qt::UserRole);
QStandardItem *visibilityItem = new QStandardItem;
visibilityItem->setDropEnabled(node.metaInfo().isContainer());
visibilityItem->setCheckable(true);
visibilityItem->setData(hash, Qt::UserRole);
return ItemRow(idItem, typeItem, visibilityItem);
}
void NavigatorTreeModel::updateItemRow(const ModelNode &node, ItemRow items)
{
items.idItem->setText(node.id());
items.typeItem->setText(node.simplifiedTypeName());
items.visibilityItem->setCheckState(node.auxiliaryData("invisible").toBool() ? Qt::Unchecked : Qt::Checked);
}
/**
Update the information shown for a node / property
*/
void NavigatorTreeModel::updateItemRow(const ModelNode &node)
{
if (!containsNode(node))
return;
updateItemRow(node, itemRowForNode(node));
}
/**
Updates the sibling position of the item, depending on the position in the model.
*/
void NavigatorTreeModel::updateItemRowOrder(const ModelNode &node)
{
if (!containsNode(node))
return;
ItemRow itemRow = itemRowForNode(node);
int currentRow = itemRow.idItem->row();
int newRow = currentRow;
if (node.parentProperty().parentModelNode().isValid())
newRow = modelNodeChildren(node.parentProperty().parentModelNode()).indexOf(node);
Q_ASSERT(newRow >= 0);
if (currentRow != newRow) {
QStandardItem *parentIdItem = itemRow.idItem->parent();
QList<QStandardItem*> items = parentIdItem->takeRow(currentRow);
parentIdItem->insertRow(newRow, items);
}
}
void NavigatorTreeModel::handleChangedItem(QStandardItem *item)
{
uint nodeHash = item->data(Qt::UserRole).toUInt();
Q_ASSERT(nodeHash && containsNodeHash(nodeHash));
ModelNode node = nodeForHash(nodeHash);
ItemRow itemRow = itemRowForNode(node);
if (item == itemRow.idItem) {
try {
if (ModelNode::isValidId(item->text()))
node.setId(item->text());
else
item->setText(node.id());
} catch (InvalidIdException &) {
item->setText(node.id());
}
} else if (item == itemRow.visibilityItem) {
bool invisible = (item->checkState() == Qt::Unchecked);
node.setAuxiliaryData("invisible", invisible);
}
}
ModelNode NavigatorTreeModel::nodeForHash(uint hash) const
{
ModelNode node = m_nodeHash.value(hash);
Q_ASSERT(node.isValid());
return node;
}
bool NavigatorTreeModel::containsNodeHash(uint hash) const
{
return m_nodeHash.contains(hash);
}
bool NavigatorTreeModel::containsNode(const ModelNode &node) const
{
return m_nodeItemHash.contains(node);
}
NavigatorTreeModel::ItemRow NavigatorTreeModel::itemRowForNode(const ModelNode &node)
{
Q_ASSERT(node.isValid());
return m_nodeItemHash.value(node);
}
void NavigatorTreeModel::setView(AbstractView *view)
{
m_view = view;
addSubTree(view->rootModelNode());
}
void NavigatorTreeModel::clearView()
{
m_view.clear();
m_nodeHash.clear();
m_nodeItemHash.clear();
clear();
}
QModelIndex NavigatorTreeModel::indexForNode(const ModelNode &node) const
{
Q_ASSERT(node.isValid());
if (!containsNode(node))
return QModelIndex();
ItemRow row = m_nodeItemHash.value(node);
return row.idItem->index();
}
ModelNode NavigatorTreeModel::nodeForIndex(const QModelIndex &index) const
{
Q_ASSERT(index.isValid());
uint hash = index.data(Qt::UserRole).toUInt();
Q_ASSERT(hash);
Q_ASSERT(containsNodeHash(hash));
return nodeForHash(hash);
}
bool NavigatorTreeModel::isInTree(const ModelNode &node) const
{
return m_nodeHash.keys().contains(qHash(node));
}
/**
Adds node & all children to the visible tree hierarchy (if node should be visible at all).
It always adds the node to the _end_ of the list of items.
*/
void NavigatorTreeModel::addSubTree(const ModelNode &node)
{
Q_ASSERT(node.isValid());
Q_ASSERT(!containsNodeHash(qHash(node)));
// only add items that are in the modelNodeChildren list (that means, visible in the editor)
if (!node.isRootNode()
&& !modelNodeChildren(node.parentProperty().parentModelNode()).contains(node)) {
return;
}
ItemRow newRow = createItemRow(node);
m_nodeHash.insert(qHash(node), node);
m_nodeItemHash.insert(node, newRow);
updateItemRow(node, newRow);
foreach (const ModelNode &childNode, modelNodeChildren(node))
addSubTree(childNode);
// We assume that the node is always added to the _end_ of the property list.
if (node.hasParentProperty()) {
ItemRow parentRow = itemRowForNode(node.parentProperty().parentModelNode());
if (parentRow.idItem)
parentRow.idItem->appendRow(newRow.toList());
} else {
appendRow(newRow.toList());
}
}
/**
Deletes visual representation for the node (subtree).
*/
void NavigatorTreeModel::removeSubTree(const ModelNode &node)
{
Q_ASSERT(node.isValid());
if (!containsNode(node))
return;
QList<QStandardItem*> rowList;
ItemRow itemRow = itemRowForNode(node);
if (itemRow.idItem->parent()) {
rowList = itemRow.idItem->parent()->takeRow(itemRow.idItem->row());
}
foreach (const ModelNode &node, modelNodeChildren(node)) {
removeSubTree(node);
}
qDeleteAll(rowList);
m_nodeHash.remove(qHash(node));
m_nodeItemHash.remove(node);
}
QList<ModelNode> NavigatorTreeModel::modelNodeChildren(const ModelNode &parentNode)
{
QList<ModelNode> children;
if (QmlItemNode(parentNode).isValid())
foreach (const QmlItemNode &childNode, QmlItemNode(parentNode).children())
children << childNode.modelNode();
return children;
}
}
<|endoftext|>
|
<commit_before>/*
Copyright Eli Dupree and Isaac Dupree, 2014
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Lasercake is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#define GLM_FORCE_RADIANS
//#define GLM_PRECISION_MEDIUMP_FLOAT
#include <iostream>
#include <cstddef>
#include "green_caves.cpp"
#include "../testcase_draw.cpp"
gl_data_format::color green_color(0x00ff00ff);
gl_data_format::color black_color(0x000000ff);
struct gl_draw_funcs {
gl_draw_funcs(gl_triangles& triangles) : triangles(triangles){}
gl_triangles& triangles;
void circle(double cx, double cy, double r) {
gl_data_format::vertex_with_color first;
gl_data_format::vertex_with_color prev;
gl_data_format::vertex_with_color center(cx, cy, 0, green_color);
for (double theta = 0; ; theta += 0.3) {
gl_data_format::vertex_with_color cur(
cx + std::cos(theta)*r,
cy + std::sin(theta)*r,
0,
green_color);
if (theta == 0) {
first = cur;
}
else {
if (theta >= 6.283) {
triangles.push_back(gl_triangle{{{ center, prev, first }}});
break;
}
else {
triangles.push_back(gl_triangle{{{ center, prev, cur }}});
}
}
prev = cur;
}
}
void rect(double x0, double y0, double x1, double y1, bool color) {
gl_data_format::color c = color ? green_color : black_color;
triangles.push_back(gl_triangle{{{
gl_data_format::vertex_with_color(x0, y0, 0, c),
gl_data_format::vertex_with_color(x1, y0, 0, c),
gl_data_format::vertex_with_color(x1, y1, 0, c) }}});
triangles.push_back(gl_triangle{{{
gl_data_format::vertex_with_color(x0, y0, 0, c),
gl_data_format::vertex_with_color(x0, y1, 0, c),
gl_data_format::vertex_with_color(x1, y1, 0, c) }}});
}
void segment(double x0, double y0, double x1, double y1, double width) {
triangles.push_back(gl_triangle{{{
gl_data_format::vertex_with_color(x0+width, y0, 0, green_color),
gl_data_format::vertex_with_color(x0-width, y0, 0, green_color),
gl_data_format::vertex_with_color(x1, y1, 0, green_color) }}});
triangles.push_back(gl_triangle{{{
gl_data_format::vertex_with_color(x0, y0+width, 0, green_color),
gl_data_format::vertex_with_color(x0, y0-width, 0, green_color),
gl_data_format::vertex_with_color(x1, y1, 0, green_color) }}});
}
};
gl_triangles display(green_caves_ui_backend& backend) {
gl_triangles triangles;
gl_draw_funcs draw(triangles);
backend.draw(draw);
return triangles;
}
#if 0
std::string read_file(const char* filename) {
// https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring
// " Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. "
std::ifstream t(filename);
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
return str;
}
#endif
void shader_debug_info(GLuint obj) {
int infologLength = 0;
int charsWritten = 0;
char* infoLog;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
if(infologLength > 0) {
infoLog = (char *)malloc(infologLength);
glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);
printf("%s\n",infoLog);
free(infoLog);
}
}
void program_debug_info(GLuint obj) {
int infologLength = 0;
int charsWritten = 0;
char* infoLog;
glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
if(infologLength > 0) {
infoLog = (char *)malloc(infologLength);
glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog);
printf("%s\n",infoLog);
free(infoLog);
}
}
GLuint shader_program_name;
void add_shaders() {
GLuint v,f,f2,p;
v = glCreateShader(GL_VERTEX_SHADER);
f = glCreateShader(GL_FRAGMENT_SHADER);
// f2 = glCreateShader(GL_FRAGMENT_SHADER);
//std::string vs = read_file("horrible.vert");
//std::string fs = read_file("horrible.frag");
const char* vs =
#ifdef EMSCRIPTEN
"precision mediump float;\n"
#endif
"uniform mat4 transformation;\n"
"attribute vec3 position;\n"
"attribute vec4 color;\n"
"varying vec4 colorV;\n"
"void main() {\n"
" colorV = color;\n"
// This is the deprecated way to do it that doesn't work at all in OpenGL ES 2.0 / WebGL:
//" gl_Position = gl_ModelViewProjectionMatrix * vec4(position, 1.0);\n"
" gl_Position = transformation * vec4(position, 1.0);\n"
"}\n"
;
const char* fs =
#ifdef EMSCRIPTEN
"precision mediump float;\n"
#endif
"varying vec4 colorV;\n"
"void main() {\n"
" gl_FragColor = colorV;\n"
"}\n"
;
glShaderSource(v, 1, &vs, NULL);
glShaderSource(f, 1, &fs, NULL);
glCompileShader(v);
glCompileShader(f);
shader_debug_info(v);
shader_debug_info(f);
p = glCreateProgram();
glAttachShader(p,v);
glAttachShader(p,f);
glLinkProgram(p);
program_debug_info(p);
glUseProgram(p);
glEnableVertexAttribArray(0);
shader_program_name = p;
}
void do_gl(green_caves_ui_backend& backend) {
static bool first_time = true;//hack
if(first_time) {
add_shaders();
first_time = false;
}
//std::cerr<<"hi.\n";
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
gl_triangles data = display(backend);
if(const size_t count = data.size()*3) {
GLuint triangles_VBO_name;
glGenBuffers(1, &triangles_VBO_name);
glBindBuffer(GL_ARRAY_BUFFER, triangles_VBO_name);
glBufferData(GL_ARRAY_BUFFER, count*sizeof(gl_data_format::vertex_with_color), &data[0], GL_STREAM_DRAW);
//glBufferData(GL_ARRAY_BUFFER, count*sizeof(vertex_with_color), data.vertices, GL_STREAM_DRAW);
auto position_attrib_location = glGetAttribLocation(shader_program_name, "position");
auto color_attrib_location = glGetAttribLocation(shader_program_name, "color");
if(GLEW_VERSION_2_0) {
//std::cerr << "GLEW_VERSION_2_0\n";
#define BUFFER_OFFSET(i) ((void*)(i))
glVertexAttribPointer(color_attrib_location, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(gl_data_format::vertex_with_color), BUFFER_OFFSET(0+offsetof(gl_data_format::vertex_with_color, c)));
glVertexAttribPointer(position_attrib_location, 3, GL_FLOAT, GL_FALSE, sizeof(gl_data_format::vertex_with_color), BUFFER_OFFSET(0+offsetof(gl_data_format::vertex_with_color, v)));
glEnableVertexAttribArray(color_attrib_location);
glEnableVertexAttribArray(position_attrib_location);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}else {
glInterleavedArrays(GL_C4UB_V3F, 0, (void*)(0));
}
glDrawArrays(GL_TRIANGLES, 0, count);
//glDrawElements for indexed mode
if(GLEW_VERSION_2_0) {
glDisableVertexAttribArray(position_attrib_location);
glDisableVertexAttribArray(color_attrib_location);
}
//glVertexAttribPointer(, 3, GL_FLOAT, GL_FALSE, sizeof(gl_data_format::vertex_with_color), (void*)4);
//glEnableVertexAttribArray(glGetAttribLocation(shader_program_name, "position"));
// glBindBuffer(GL_ARRAY_BUFFER, 0);
//glInterleavedArrays(GL_C4UB_V3F, 0, (void*)(0));
//glDrawArrays(GL_TRIANGLES, 0, count);
glDeleteBuffers(1, &triangles_VBO_name);
//glDisableVertexAttribArray(glGetAttribLocation(shader_program_name, "position"));
}
}
void gl_reshape(int width, int height) {
glViewport(0,0,width,height);
const GLint uniform_id = glGetUniformLocation(shader_program_name, "transformation");
const glm::mat4 transformation = glm::ortho(0.0f, GLfloat(width), 0.0f, GLfloat(height));
glUniformMatrix4fv(uniform_id, 1, GL_FALSE, glm::value_ptr(transformation));
// This is the deprecated way to do it that doesn't work at all in OpenGL ES 2.0 / WebGL:
// glLoadIdentity();
// gluOrtho2D(0, GLdouble(width), 0, GLdouble(height));
}
<commit_msg>Made green-caves lines look better in GL UI<commit_after>/*
Copyright Eli Dupree and Isaac Dupree, 2014
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Lasercake is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#define GLM_FORCE_RADIANS
//#define GLM_PRECISION_MEDIUMP_FLOAT
#include <iostream>
#include <cstddef>
#include "green_caves.cpp"
#include "../testcase_draw.cpp"
gl_data_format::color green_color(0x00ff00ff);
gl_data_format::color black_color(0x000000ff);
struct gl_draw_funcs {
gl_draw_funcs(gl_triangles& triangles) : triangles(triangles){}
gl_triangles& triangles;
void circle(double cx, double cy, double r) {
gl_data_format::vertex_with_color first;
gl_data_format::vertex_with_color prev;
gl_data_format::vertex_with_color center(cx, cy, 0, green_color);
for (double theta = 0; ; theta += 0.3) {
gl_data_format::vertex_with_color cur(
cx + std::cos(theta)*r,
cy + std::sin(theta)*r,
0,
green_color);
if (theta == 0) {
first = cur;
}
else {
if (theta >= 6.283) {
triangles.push_back(gl_triangle{{{ center, prev, first }}});
break;
}
else {
triangles.push_back(gl_triangle{{{ center, prev, cur }}});
}
}
prev = cur;
}
}
void rect(double x0, double y0, double x1, double y1, bool color) {
gl_data_format::color c = color ? green_color : black_color;
triangles.push_back(gl_triangle{{{
gl_data_format::vertex_with_color(x0, y0, 0, c),
gl_data_format::vertex_with_color(x1, y0, 0, c),
gl_data_format::vertex_with_color(x1, y1, 0, c) }}});
triangles.push_back(gl_triangle{{{
gl_data_format::vertex_with_color(x0, y0, 0, c),
gl_data_format::vertex_with_color(x0, y1, 0, c),
gl_data_format::vertex_with_color(x1, y1, 0, c) }}});
}
void segment(double x0, double y0, double x1, double y1, double width) {
double m = std::sqrt((x0-x1)*(x0-x1)+(y0-y1)*(y0-y1));
double dx = (y1-y0)*width/m/2;
double dy = -(x1-x0)*width/m/2;
triangles.push_back(gl_triangle{{{
gl_data_format::vertex_with_color(x0+dx, y0+dy, 0, green_color),
gl_data_format::vertex_with_color(x0-dx, y0-dy, 0, green_color),
gl_data_format::vertex_with_color(x1+dx, y1+dy, 0, green_color) }}});
triangles.push_back(gl_triangle{{{
gl_data_format::vertex_with_color(x1+dx, y1+dy, 0, green_color),
gl_data_format::vertex_with_color(x1-dx, y1-dy, 0, green_color),
gl_data_format::vertex_with_color(x0-dx, y0-dy, 0, green_color) }}});
}
};
gl_triangles display(green_caves_ui_backend& backend) {
gl_triangles triangles;
gl_draw_funcs draw(triangles);
backend.draw(draw);
return triangles;
}
#if 0
std::string read_file(const char* filename) {
// https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring
// " Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. "
std::ifstream t(filename);
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
return str;
}
#endif
void shader_debug_info(GLuint obj) {
int infologLength = 0;
int charsWritten = 0;
char* infoLog;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
if(infologLength > 0) {
infoLog = (char *)malloc(infologLength);
glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);
printf("%s\n",infoLog);
free(infoLog);
}
}
void program_debug_info(GLuint obj) {
int infologLength = 0;
int charsWritten = 0;
char* infoLog;
glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
if(infologLength > 0) {
infoLog = (char *)malloc(infologLength);
glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog);
printf("%s\n",infoLog);
free(infoLog);
}
}
GLuint shader_program_name;
void add_shaders() {
GLuint v,f,f2,p;
v = glCreateShader(GL_VERTEX_SHADER);
f = glCreateShader(GL_FRAGMENT_SHADER);
// f2 = glCreateShader(GL_FRAGMENT_SHADER);
//std::string vs = read_file("horrible.vert");
//std::string fs = read_file("horrible.frag");
const char* vs =
#ifdef EMSCRIPTEN
"precision mediump float;\n"
#endif
"uniform mat4 transformation;\n"
"attribute vec3 position;\n"
"attribute vec4 color;\n"
"varying vec4 colorV;\n"
"void main() {\n"
" colorV = color;\n"
// This is the deprecated way to do it that doesn't work at all in OpenGL ES 2.0 / WebGL:
//" gl_Position = gl_ModelViewProjectionMatrix * vec4(position, 1.0);\n"
" gl_Position = transformation * vec4(position, 1.0);\n"
"}\n"
;
const char* fs =
#ifdef EMSCRIPTEN
"precision mediump float;\n"
#endif
"varying vec4 colorV;\n"
"void main() {\n"
" gl_FragColor = colorV;\n"
"}\n"
;
glShaderSource(v, 1, &vs, NULL);
glShaderSource(f, 1, &fs, NULL);
glCompileShader(v);
glCompileShader(f);
shader_debug_info(v);
shader_debug_info(f);
p = glCreateProgram();
glAttachShader(p,v);
glAttachShader(p,f);
glLinkProgram(p);
program_debug_info(p);
glUseProgram(p);
glEnableVertexAttribArray(0);
shader_program_name = p;
}
void do_gl(green_caves_ui_backend& backend) {
static bool first_time = true;//hack
if(first_time) {
add_shaders();
first_time = false;
}
//std::cerr<<"hi.\n";
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
gl_triangles data = display(backend);
if(const size_t count = data.size()*3) {
GLuint triangles_VBO_name;
glGenBuffers(1, &triangles_VBO_name);
glBindBuffer(GL_ARRAY_BUFFER, triangles_VBO_name);
glBufferData(GL_ARRAY_BUFFER, count*sizeof(gl_data_format::vertex_with_color), &data[0], GL_STREAM_DRAW);
//glBufferData(GL_ARRAY_BUFFER, count*sizeof(vertex_with_color), data.vertices, GL_STREAM_DRAW);
auto position_attrib_location = glGetAttribLocation(shader_program_name, "position");
auto color_attrib_location = glGetAttribLocation(shader_program_name, "color");
if(GLEW_VERSION_2_0) {
//std::cerr << "GLEW_VERSION_2_0\n";
#define BUFFER_OFFSET(i) ((void*)(i))
glVertexAttribPointer(color_attrib_location, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(gl_data_format::vertex_with_color), BUFFER_OFFSET(0+offsetof(gl_data_format::vertex_with_color, c)));
glVertexAttribPointer(position_attrib_location, 3, GL_FLOAT, GL_FALSE, sizeof(gl_data_format::vertex_with_color), BUFFER_OFFSET(0+offsetof(gl_data_format::vertex_with_color, v)));
glEnableVertexAttribArray(color_attrib_location);
glEnableVertexAttribArray(position_attrib_location);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}else {
glInterleavedArrays(GL_C4UB_V3F, 0, (void*)(0));
}
glDrawArrays(GL_TRIANGLES, 0, count);
//glDrawElements for indexed mode
if(GLEW_VERSION_2_0) {
glDisableVertexAttribArray(position_attrib_location);
glDisableVertexAttribArray(color_attrib_location);
}
//glVertexAttribPointer(, 3, GL_FLOAT, GL_FALSE, sizeof(gl_data_format::vertex_with_color), (void*)4);
//glEnableVertexAttribArray(glGetAttribLocation(shader_program_name, "position"));
// glBindBuffer(GL_ARRAY_BUFFER, 0);
//glInterleavedArrays(GL_C4UB_V3F, 0, (void*)(0));
//glDrawArrays(GL_TRIANGLES, 0, count);
glDeleteBuffers(1, &triangles_VBO_name);
//glDisableVertexAttribArray(glGetAttribLocation(shader_program_name, "position"));
}
}
void gl_reshape(int width, int height) {
glViewport(0,0,width,height);
const GLint uniform_id = glGetUniformLocation(shader_program_name, "transformation");
const glm::mat4 transformation = glm::ortho(0.0f, GLfloat(width), 0.0f, GLfloat(height));
glUniformMatrix4fv(uniform_id, 1, GL_FALSE, glm::value_ptr(transformation));
// This is the deprecated way to do it that doesn't work at all in OpenGL ES 2.0 / WebGL:
// glLoadIdentity();
// gluOrtho2D(0, GLdouble(width), 0, GLdouble(height));
}
<|endoftext|>
|
<commit_before><commit_msg>Update factory classes<commit_after><|endoftext|>
|
<commit_before>#include "Genes/Look_Ahead_Gene.h"
#include <cassert>
#include <memory>
#include <algorithm>
#include "Genes/Gene.h"
#include "Utility.h"
#include "Game/Board.h"
#include "Game/Clock.h"
class Move;
Look_Ahead_Gene::Look_Ahead_Gene() :
mean_game_length(50),
game_length_uncertainty(0.5),
speculation_constant(1.0),
capturing_speculation_constant(1.0)
{
}
void Look_Ahead_Gene::reset_properties() const
{
properties["Mean Game Length"] = mean_game_length;
properties["Game Length Uncertainty"] = game_length_uncertainty;
properties["Speculation Constant"] = speculation_constant;
properties["Capturing Speculation Constant"] = capturing_speculation_constant;
}
void Look_Ahead_Gene::load_properties()
{
mean_game_length = properties["Mean Game Length"];
game_length_uncertainty = properties["Game Length Uncertainty"];
speculation_constant = properties["Speculation Constant"];
capturing_speculation_constant = properties["Capturing Speculation Constant"];
}
double Look_Ahead_Gene::time_to_examine(const Board& board, const Clock& clock) const
{
auto time_left = clock.time_left(board.whose_turn());
auto moves_to_reset = clock.moves_to_reset(board.whose_turn());
auto moves_so_far = board.get_game_record().size()/2; // only count moves by this player
auto moves_left = Math::average_moves_left(mean_game_length, game_length_uncertainty, moves_so_far);
return time_left/std::min(moves_left, double(moves_to_reset));
}
void Look_Ahead_Gene::gene_specific_mutation()
{
switch(Random::random_integer(1, 4))
{
case 1:
mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0));
break;
case 2:
game_length_uncertainty = std::abs(game_length_uncertainty + Random::random_normal(0.05));
break;
case 3:
speculation_constant += Random::random_normal(0.05);
break;
case 4:
capturing_speculation_constant += Random::random_normal(0.05);
break;
default:
assert(false); // If here, random_integer() called with wrong parameters
break;
}
}
std::unique_ptr<Gene> Look_Ahead_Gene::duplicate() const
{
return std::make_unique<Look_Ahead_Gene>(*this);
}
std::string Look_Ahead_Gene::name() const
{
return "Look Ahead Gene";
}
double Look_Ahead_Gene::score_board(const Board&) const
{
return 0.0;
}
double Look_Ahead_Gene::speculation_time_factor(const Board& board) const
{
return board.capture_possible() ? capturing_speculation_constant : speculation_constant;
}
<commit_msg>More neutral starting point for clock control<commit_after>#include "Genes/Look_Ahead_Gene.h"
#include <cassert>
#include <memory>
#include <algorithm>
#include "Genes/Gene.h"
#include "Utility.h"
#include "Game/Board.h"
#include "Game/Clock.h"
class Move;
Look_Ahead_Gene::Look_Ahead_Gene() :
mean_game_length(50),
game_length_uncertainty(0.5),
speculation_constant(0.0),
capturing_speculation_constant(0.0)
{
}
void Look_Ahead_Gene::reset_properties() const
{
properties["Mean Game Length"] = mean_game_length;
properties["Game Length Uncertainty"] = game_length_uncertainty;
properties["Speculation Constant"] = speculation_constant;
properties["Capturing Speculation Constant"] = capturing_speculation_constant;
}
void Look_Ahead_Gene::load_properties()
{
mean_game_length = properties["Mean Game Length"];
game_length_uncertainty = properties["Game Length Uncertainty"];
speculation_constant = properties["Speculation Constant"];
capturing_speculation_constant = properties["Capturing Speculation Constant"];
}
double Look_Ahead_Gene::time_to_examine(const Board& board, const Clock& clock) const
{
auto time_left = clock.time_left(board.whose_turn());
auto moves_to_reset = clock.moves_to_reset(board.whose_turn());
auto moves_so_far = board.get_game_record().size()/2; // only count moves by this player
auto moves_left = Math::average_moves_left(mean_game_length, game_length_uncertainty, moves_so_far);
return time_left/std::min(moves_left, double(moves_to_reset));
}
void Look_Ahead_Gene::gene_specific_mutation()
{
switch(Random::random_integer(1, 4))
{
case 1:
mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0));
break;
case 2:
game_length_uncertainty = std::abs(game_length_uncertainty + Random::random_normal(0.05));
break;
case 3:
speculation_constant += Random::random_normal(0.05);
break;
case 4:
capturing_speculation_constant += Random::random_normal(0.05);
break;
default:
assert(false); // If here, random_integer() called with wrong parameters
break;
}
}
std::unique_ptr<Gene> Look_Ahead_Gene::duplicate() const
{
return std::make_unique<Look_Ahead_Gene>(*this);
}
std::string Look_Ahead_Gene::name() const
{
return "Look Ahead Gene";
}
double Look_Ahead_Gene::score_board(const Board&) const
{
return 0.0;
}
double Look_Ahead_Gene::speculation_time_factor(const Board& board) const
{
return board.capture_possible() ? capturing_speculation_constant : speculation_constant;
}
<|endoftext|>
|
<commit_before>#include "Genes/Look_Ahead_Gene.h"
#include <cmath>
#include <cassert>
#include <memory>
#include "Genes/Gene.h"
#include "Utility.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Moves/Move.h"
Look_Ahead_Gene::Look_Ahead_Gene() :
mean_game_length(50),
game_length_uncertainty(0.5),
speculation_constant(1.0),
capturing_speculation_constant(1.0)
{
}
void Look_Ahead_Gene::reset_properties() const
{
properties["Mean Game Length"] = mean_game_length;
properties["Game Length Uncertainty"] = game_length_uncertainty;
properties["Speculation Constant"] = speculation_constant;
properties["Capturing Speculation Constant"] = capturing_speculation_constant;
}
void Look_Ahead_Gene::load_properties()
{
mean_game_length = properties["Mean Game Length"];
game_length_uncertainty = properties["Game Length Uncertainty"];
speculation_constant = properties["Speculation Constant"];
capturing_speculation_constant = properties["Capturing Speculation Constant"];
}
double Look_Ahead_Gene::time_to_examine(const Board& board, const Clock& clock) const
{
auto time_left = clock.time_left(board.whose_turn());
auto moves_to_reset = clock.moves_to_reset(board.whose_turn());
auto moves_so_far = board.get_game_record().size()/2; // only count moves by this player
auto moves_left = Math::average_moves_left(mean_game_length, game_length_uncertainty, moves_so_far);
return time_left/std::min(moves_left, double(moves_to_reset));
}
void Look_Ahead_Gene::gene_specific_mutation()
{
switch(Random::random_integer(1, 4))
{
case 1:
mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0));
break;
case 2:
game_length_uncertainty = std::abs(game_length_uncertainty + Random::random_normal(0.05));
break;
case 3:
speculation_constant += Random::random_normal(0.01);
break;
case 4:
capturing_speculation_constant += Random::random_normal(0.01);
break;
default:
assert(false); // If here, random_integer() called with wrong parameters
break;
}
}
std::unique_ptr<Gene> Look_Ahead_Gene::duplicate() const
{
return std::make_unique<Look_Ahead_Gene>(*this);
}
std::string Look_Ahead_Gene::name() const
{
return "Look Ahead Gene";
}
double Look_Ahead_Gene::score_board(const Board&) const
{
return 0.0;
}
double Look_Ahead_Gene::speculation_time_factor(const Board& board) const
{
return board.capture_possible() ? capturing_speculation_constant : speculation_constant;
}
<commit_msg>Adjust includes<commit_after>#include "Genes/Look_Ahead_Gene.h"
#include <cassert>
#include <memory>
#include <algorithm>
#include "Genes/Gene.h"
#include "Utility.h"
#include "Game/Board.h"
#include "Game/Clock.h"
class Move;
Look_Ahead_Gene::Look_Ahead_Gene() :
mean_game_length(50),
game_length_uncertainty(0.5),
speculation_constant(1.0),
capturing_speculation_constant(1.0)
{
}
void Look_Ahead_Gene::reset_properties() const
{
properties["Mean Game Length"] = mean_game_length;
properties["Game Length Uncertainty"] = game_length_uncertainty;
properties["Speculation Constant"] = speculation_constant;
properties["Capturing Speculation Constant"] = capturing_speculation_constant;
}
void Look_Ahead_Gene::load_properties()
{
mean_game_length = properties["Mean Game Length"];
game_length_uncertainty = properties["Game Length Uncertainty"];
speculation_constant = properties["Speculation Constant"];
capturing_speculation_constant = properties["Capturing Speculation Constant"];
}
double Look_Ahead_Gene::time_to_examine(const Board& board, const Clock& clock) const
{
auto time_left = clock.time_left(board.whose_turn());
auto moves_to_reset = clock.moves_to_reset(board.whose_turn());
auto moves_so_far = board.get_game_record().size()/2; // only count moves by this player
auto moves_left = Math::average_moves_left(mean_game_length, game_length_uncertainty, moves_so_far);
return time_left/std::min(moves_left, double(moves_to_reset));
}
void Look_Ahead_Gene::gene_specific_mutation()
{
switch(Random::random_integer(1, 4))
{
case 1:
mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0));
break;
case 2:
game_length_uncertainty = std::abs(game_length_uncertainty + Random::random_normal(0.05));
break;
case 3:
speculation_constant += Random::random_normal(0.01);
break;
case 4:
capturing_speculation_constant += Random::random_normal(0.01);
break;
default:
assert(false); // If here, random_integer() called with wrong parameters
break;
}
}
std::unique_ptr<Gene> Look_Ahead_Gene::duplicate() const
{
return std::make_unique<Look_Ahead_Gene>(*this);
}
std::string Look_Ahead_Gene::name() const
{
return "Look Ahead Gene";
}
double Look_Ahead_Gene::score_board(const Board&) const
{
return 0.0;
}
double Look_Ahead_Gene::speculation_time_factor(const Board& board) const
{
return board.capture_possible() ? capturing_speculation_constant : speculation_constant;
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009-2013, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include <string.h>
#include "tbb/spin_rw_mutex.h"
#include "tbb/concurrent_hash_map.h"
#include "boost/multi_index_container.hpp"
#include "boost/lexical_cast.hpp"
#include "IECore/HashTable.h"
#include "IECore/InternedString.h"
namespace IECore
{
namespace Detail
{
typedef boost::multi_index::multi_index_container<
std::string,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<
boost::multi_index::identity<std::string>,
Hash<std::string>
>
>
> HashSet;
typedef HashSet::nth_index<0>::type Index;
typedef HashSet::nth_index_const_iterator<0>::type ConstIterator;
typedef tbb::spin_rw_mutex Mutex;
static HashSet *hashSet()
{
static HashSet g_hashSet;
return &g_hashSet;
}
static Mutex *mutex()
{
static Detail::Mutex g_mutex;
return &g_mutex;
}
struct StringCStringEqual
{
bool operator()( const char *c, const std::string &s ) const
{
return strcmp( c, s.c_str() )==0;
}
bool operator()( const std::string &s, const char *c ) const
{
return strcmp( c, s.c_str() )==0;
}
};
} // namespace Detail
const std::string *InternedString::internedString( const char *value )
{
Detail::HashSet *hashSet = Detail::hashSet();
Detail::Index &hashIndex = hashSet->get<0>();
Detail::Mutex::scoped_lock lock( *Detail::mutex(), false ); // read-only lock
Detail::HashSet::const_iterator it = hashIndex.find( value, Hash<const char *>(), Detail::StringCStringEqual() );
if( it!=hashIndex.end() )
{
return &(*it);
}
else
{
lock.upgrade_to_writer();
return &(*(hashSet->insert( std::string( value ) ).first ) );
}
}
size_t InternedString::numUniqueStrings()
{
Detail::Mutex::scoped_lock lock( *Detail::mutex(), false ); // read-only lock
Detail::HashSet *hashSet = Detail::hashSet();
return hashSet->size();
}
static InternedString g_emptyString("");
const InternedString &InternedString::emptyString()
{
return g_emptyString;
}
// make sure we create the g_numbers map at load time.
static InternedString g_zero((int64_t)0);
const InternedString &InternedString::numberString( int64_t number )
{
typedef tbb::concurrent_hash_map< int64_t, InternedString > NumbersMap;
static NumbersMap *g_numbers = 0;
if ( !g_numbers )
{
g_numbers = new NumbersMap;
}
NumbersMap::accessor it;
if ( g_numbers->insert( it, number ) )
{
it->second = InternedString( boost::lexical_cast<std::string>( number ) );
}
return it->second;
}
std::ostream &operator << ( std::ostream &o, const InternedString &str )
{
o << str.c_str();
return o;
}
} // namespace IECore
<commit_msg>Removed InternedString reliance on IECore/HashTable.h.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009-2014, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include <string.h>
#include "tbb/spin_rw_mutex.h"
#include "tbb/concurrent_hash_map.h"
#include "boost/multi_index_container.hpp"
#include "boost/multi_index/hashed_index.hpp"
#include "boost/lexical_cast.hpp"
#include "IECore/InternedString.h"
namespace IECore
{
namespace Detail
{
// Hash for strings of various types.
// By overloading it for multiple types, we are able to do
// lookups into HashSet using any type as a key, and without
// needing to construct a temporary std::string when the type
// is a raw c string.
struct Hash
{
// Dan Bernstein's original string hash
size_t operator()( const char *s ) const
{
size_t hash = 5381;
while( *s )
{
hash = ( ( hash << 5 ) + hash ) + *s++;
}
return hash;
}
size_t operator()( const std::string &s ) const
{
return (*this)( s.c_str() );
}
};
// Equality operator between strings of various types.
// As above, this allows HashSet lookups to be performed
// using any type, without the overhead of constructing
// temporary std::strings.
struct Equal
{
bool operator()( const std::string &s1, const std::string &s2 ) const
{
return s1 == s2;
}
bool operator()( const char *c, const std::string &s ) const
{
return strcmp( c, s.c_str() )==0;
}
bool operator()( const std::string &s, const char *c ) const
{
return strcmp( c, s.c_str() )==0;
}
};
typedef boost::multi_index::multi_index_container<
std::string,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<
boost::multi_index::identity<std::string>,
Hash,
Equal
>
>
> HashSet;
typedef HashSet::nth_index<0>::type Index;
typedef HashSet::nth_index_const_iterator<0>::type ConstIterator;
typedef tbb::spin_rw_mutex Mutex;
static HashSet *hashSet()
{
static HashSet g_hashSet;
return &g_hashSet;
}
static Mutex *mutex()
{
static Detail::Mutex g_mutex;
return &g_mutex;
}
} // namespace Detail
const std::string *InternedString::internedString( const char *value )
{
Detail::HashSet *hashSet = Detail::hashSet();
Detail::Index &hashIndex = hashSet->get<0>();
Detail::Mutex::scoped_lock lock( *Detail::mutex(), false ); // read-only lock
Detail::HashSet::const_iterator it = hashIndex.find( value );
if( it!=hashIndex.end() )
{
return &(*it);
}
else
{
lock.upgrade_to_writer();
return &(*(hashSet->insert( std::string( value ) ).first ) );
}
}
size_t InternedString::numUniqueStrings()
{
Detail::Mutex::scoped_lock lock( *Detail::mutex(), false ); // read-only lock
Detail::HashSet *hashSet = Detail::hashSet();
return hashSet->size();
}
static InternedString g_emptyString("");
const InternedString &InternedString::emptyString()
{
return g_emptyString;
}
// make sure we create the g_numbers map at load time.
static InternedString g_zero((int64_t)0);
const InternedString &InternedString::numberString( int64_t number )
{
typedef tbb::concurrent_hash_map< int64_t, InternedString > NumbersMap;
static NumbersMap *g_numbers = 0;
if ( !g_numbers )
{
g_numbers = new NumbersMap;
}
NumbersMap::accessor it;
if ( g_numbers->insert( it, number ) )
{
it->second = InternedString( boost::lexical_cast<std::string>( number ) );
}
return it->second;
}
std::ostream &operator << ( std::ostream &o, const InternedString &str )
{
o << str.c_str();
return o;
}
} // namespace IECore
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreD3D11HardwareVertexBuffer.h"
#include "OgreD3D11HardwareBuffer.h"
#include "OgreD3D11Device.h"
namespace Ogre {
//---------------------------------------------------------------------
D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize,
size_t numVertices, HardwareBuffer::Usage usage, D3D11Device & device,
bool useSystemMemory, bool useShadowBuffer)
: HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, useSystemMemory, useShadowBuffer),
mBufferImpl(0)
{
// everything is done via internal generalisation
mBufferImpl = new D3D11HardwareBuffer(D3D11HardwareBuffer::VERTEX_BUFFER,
mSizeInBytes, mUsage, device, useSystemMemory, useShadowBuffer);
}
//---------------------------------------------------------------------
D3D11HardwareVertexBuffer::~D3D11HardwareVertexBuffer()
{
SAFE_DELETE(mBufferImpl);
}
//---------------------------------------------------------------------
void* D3D11HardwareVertexBuffer::lock(size_t offset, size_t length, LockOptions options)
{
return mBufferImpl->lock(offset, length, options);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::unlock(void)
{
mBufferImpl->unlock();
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::readData(size_t offset, size_t length, void* pDest)
{
mBufferImpl->readData(offset, length, pDest);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::writeData(size_t offset, size_t length, const void* pSource,
bool discardWholeBuffer)
{
mBufferImpl->writeData(offset, length, pSource, discardWholeBuffer);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::copyData(HardwareBuffer& srcBuffer, size_t srcOffset,
size_t dstOffset, size_t length, bool discardWholeBuffer)
{
// check if the other buffer is also a D3D11HardwareVertexBuffer
if (srcBuffer.isSystemMemory())
{
// src is not not a D3D11HardwareVertexBuffer - use default copy
HardwareBuffer::copyData(srcBuffer, srcOffset, dstOffset, length, discardWholeBuffer);
}
else
{
// src is a D3D11HardwareVertexBuffer use d3d11 optimized copy
D3D11HardwareVertexBuffer& d3dBuf = static_cast<D3D11HardwareVertexBuffer&>(srcBuffer);
mBufferImpl->copyData(*(d3dBuf.mBufferImpl), srcOffset, dstOffset, length, discardWholeBuffer);
}
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::isLocked(void) const
{
return mBufferImpl->isLocked();
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::releaseIfDefaultPool(void)
{
/* if (mD3DPool == D3DPOOL_DEFAULT)
{
SAFE_RELEASE(mlpD3DBuffer);
return true;
}
return false;
*/
return true;
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::recreateIfDefaultPool(D3D11Device & device)
{
/* if (mD3DPool == D3DPOOL_DEFAULT)
{
// Create the Index buffer
HRESULT hr = device->CreateIndexBuffer(
static_cast<UINT>(mSizeInBytes),
D3D11Mappings::get(mUsage),
D3D11Mappings::get(mIndexType),
mD3DPool,
&mlpD3DBuffer,
NULL
);
if (FAILED(hr))
{
String msg = DXGetErrorDescription(hr);
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Cannot create D3D11 Index buffer: " + msg,
"D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer");
}
return true;
}
return false;
*/
return true;
}
//---------------------------------------------------------------------
ID3D11Buffer * D3D11HardwareVertexBuffer::getD3DVertexBuffer( void ) const
{
return mBufferImpl->getD3DBuffer();
}
//---------------------------------------------------------------------
}
<commit_msg>D3D11 render system: Fixed a comment typo.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreD3D11HardwareVertexBuffer.h"
#include "OgreD3D11HardwareBuffer.h"
#include "OgreD3D11Device.h"
namespace Ogre {
//---------------------------------------------------------------------
D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize,
size_t numVertices, HardwareBuffer::Usage usage, D3D11Device & device,
bool useSystemMemory, bool useShadowBuffer)
: HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, useSystemMemory, useShadowBuffer),
mBufferImpl(0)
{
// everything is done via internal generalisation
mBufferImpl = new D3D11HardwareBuffer(D3D11HardwareBuffer::VERTEX_BUFFER,
mSizeInBytes, mUsage, device, useSystemMemory, useShadowBuffer);
}
//---------------------------------------------------------------------
D3D11HardwareVertexBuffer::~D3D11HardwareVertexBuffer()
{
SAFE_DELETE(mBufferImpl);
}
//---------------------------------------------------------------------
void* D3D11HardwareVertexBuffer::lock(size_t offset, size_t length, LockOptions options)
{
return mBufferImpl->lock(offset, length, options);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::unlock(void)
{
mBufferImpl->unlock();
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::readData(size_t offset, size_t length, void* pDest)
{
mBufferImpl->readData(offset, length, pDest);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::writeData(size_t offset, size_t length, const void* pSource,
bool discardWholeBuffer)
{
mBufferImpl->writeData(offset, length, pSource, discardWholeBuffer);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::copyData(HardwareBuffer& srcBuffer, size_t srcOffset,
size_t dstOffset, size_t length, bool discardWholeBuffer)
{
// check if the other buffer is also a D3D11HardwareVertexBuffer
if (srcBuffer.isSystemMemory())
{
// src is not a D3D11HardwareVertexBuffer - use default copy
HardwareBuffer::copyData(srcBuffer, srcOffset, dstOffset, length, discardWholeBuffer);
}
else
{
// src is a D3D11HardwareVertexBuffer use d3d11 optimized copy
D3D11HardwareVertexBuffer& d3dBuf = static_cast<D3D11HardwareVertexBuffer&>(srcBuffer);
mBufferImpl->copyData(*(d3dBuf.mBufferImpl), srcOffset, dstOffset, length, discardWholeBuffer);
}
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::isLocked(void) const
{
return mBufferImpl->isLocked();
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::releaseIfDefaultPool(void)
{
/* if (mD3DPool == D3DPOOL_DEFAULT)
{
SAFE_RELEASE(mlpD3DBuffer);
return true;
}
return false;
*/
return true;
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::recreateIfDefaultPool(D3D11Device & device)
{
/* if (mD3DPool == D3DPOOL_DEFAULT)
{
// Create the Index buffer
HRESULT hr = device->CreateIndexBuffer(
static_cast<UINT>(mSizeInBytes),
D3D11Mappings::get(mUsage),
D3D11Mappings::get(mIndexType),
mD3DPool,
&mlpD3DBuffer,
NULL
);
if (FAILED(hr))
{
String msg = DXGetErrorDescription(hr);
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Cannot create D3D11 Index buffer: " + msg,
"D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer");
}
return true;
}
return false;
*/
return true;
}
//---------------------------------------------------------------------
ID3D11Buffer * D3D11HardwareVertexBuffer::getD3DVertexBuffer( void ) const
{
return mBufferImpl->getD3DBuffer();
}
//---------------------------------------------------------------------
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLSLESProgramCommon.h"
#include "OgreGLSLESProgram.h"
#include "OgreGpuProgramManager.h"
#include "OgreGLUtil.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreRoot.h"
#include "OgreGLNativeSupport.h"
namespace Ogre {
//-----------------------------------------------------------------------
GLSLESProgramCommon::GLSLESProgramCommon(const GLShaderList& shaders)
: GLSLProgramCommon(shaders)
{
}
void GLSLESProgramCommon::bindFixedAttributes(GLuint program)
{
GLint maxAttribs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumVertexAttributes();
size_t numAttribs = sizeof(msCustomAttributes) / sizeof(CustomAttribute);
for (size_t i = 0; i < numAttribs; ++i)
{
const CustomAttribute& a = msCustomAttributes[i];
if (a.attrib < maxAttribs)
{
OGRE_CHECK_GL_ERROR(glBindAttribLocation(program, a.attrib, a.name));
}
}
}
//-----------------------------------------------------------------------
bool GLSLESProgramCommon::getMicrocodeFromCache(uint32 id, GLuint programHandle)
{
if (!GpuProgramManager::canGetCompiledShaderBuffer())
return false;
if (!GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(id))
return false;
GpuProgramManager::Microcode cacheMicrocode = GpuProgramManager::getSingleton().getMicrocodeFromCache(id);
// turns out we need this param when loading
GLenum binaryFormat = 0;
cacheMicrocode->seek(0);
// get size of binary
cacheMicrocode->read(&binaryFormat, sizeof(GLenum));
if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER))
return false;
GLint binaryLength = static_cast<GLint>(cacheMicrocode->size() - sizeof(GLenum));
// load binary
OGRE_CHECK_GL_ERROR(glProgramBinaryOES(programHandle,
binaryFormat,
cacheMicrocode->getCurrentPtr(),
binaryLength));
GLint success = 0;
OGRE_CHECK_GL_ERROR(glGetProgramiv(programHandle, GL_LINK_STATUS, &success));
return success;
}
void GLSLESProgramCommon::_writeToCache(uint32 id, GLuint programHandle)
{
if(!GpuProgramManager::canGetCompiledShaderBuffer())
return;
if(!GpuProgramManager::getSingleton().getSaveMicrocodesToCache())
return;
// Add to the microcode to the cache
// Get buffer size
GLint binaryLength = 0;
OGRE_CHECK_GL_ERROR(glGetProgramiv(programHandle, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength));
// Create microcode
GpuProgramManager::Microcode newMicrocode =
GpuProgramManager::getSingleton().createMicrocode(static_cast<uint32>(binaryLength + sizeof(GLenum)));
// Get binary
OGRE_CHECK_GL_ERROR(glGetProgramBinaryOES(programHandle, binaryLength, NULL, (GLenum *)newMicrocode->getPtr(),
newMicrocode->getPtr() + sizeof(GLenum)));
// Add to the microcode to the cache
GpuProgramManager::getSingleton().addMicrocodeToCache(id, newMicrocode);
}
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
void GLSLESProgramCommon::notifyOnContextLost()
{
mLinked = false;
mUniformRefsBuilt = false;
for(auto s : mShaders)
{
if(s) s->getUniformCache()->clearCache();
}
}
void GLSLESProgramCommon::notifyOnContextReset()
{
activate();
}
#endif
} // namespace Ogre
<commit_msg>GLES2: iOS - suppress attribute warnings<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLSLESProgramCommon.h"
#include "OgreGLSLESProgram.h"
#include "OgreGpuProgramManager.h"
#include "OgreGLUtil.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreRoot.h"
#include "OgreGLNativeSupport.h"
namespace Ogre {
//-----------------------------------------------------------------------
GLSLESProgramCommon::GLSLESProgramCommon(const GLShaderList& shaders)
: GLSLProgramCommon(shaders)
{
}
void GLSLESProgramCommon::bindFixedAttributes(GLuint program)
{
GLint maxAttribs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumVertexAttributes();
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
// must query active attributes on OSX to avoid warning spam
OGRE_CHECK_GL_ERROR(glLinkProgram( program ));
#endif
size_t numAttribs = sizeof(msCustomAttributes) / sizeof(CustomAttribute);
for (size_t i = 0; i < numAttribs; ++i)
{
const CustomAttribute& a = msCustomAttributes[i];
if (a.attrib < maxAttribs)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
if(glGetAttribLocation(program, a.name) == -1) continue;
#endif
OGRE_CHECK_GL_ERROR(glBindAttribLocation(program, a.attrib, a.name));
}
}
}
//-----------------------------------------------------------------------
bool GLSLESProgramCommon::getMicrocodeFromCache(uint32 id, GLuint programHandle)
{
if (!GpuProgramManager::canGetCompiledShaderBuffer())
return false;
if (!GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(id))
return false;
GpuProgramManager::Microcode cacheMicrocode = GpuProgramManager::getSingleton().getMicrocodeFromCache(id);
// turns out we need this param when loading
GLenum binaryFormat = 0;
cacheMicrocode->seek(0);
// get size of binary
cacheMicrocode->read(&binaryFormat, sizeof(GLenum));
if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER))
return false;
GLint binaryLength = static_cast<GLint>(cacheMicrocode->size() - sizeof(GLenum));
// load binary
OGRE_CHECK_GL_ERROR(glProgramBinaryOES(programHandle,
binaryFormat,
cacheMicrocode->getCurrentPtr(),
binaryLength));
GLint success = 0;
OGRE_CHECK_GL_ERROR(glGetProgramiv(programHandle, GL_LINK_STATUS, &success));
return success;
}
void GLSLESProgramCommon::_writeToCache(uint32 id, GLuint programHandle)
{
if(!GpuProgramManager::canGetCompiledShaderBuffer())
return;
if(!GpuProgramManager::getSingleton().getSaveMicrocodesToCache())
return;
// Add to the microcode to the cache
// Get buffer size
GLint binaryLength = 0;
OGRE_CHECK_GL_ERROR(glGetProgramiv(programHandle, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength));
// Create microcode
GpuProgramManager::Microcode newMicrocode =
GpuProgramManager::getSingleton().createMicrocode(static_cast<uint32>(binaryLength + sizeof(GLenum)));
// Get binary
OGRE_CHECK_GL_ERROR(glGetProgramBinaryOES(programHandle, binaryLength, NULL, (GLenum *)newMicrocode->getPtr(),
newMicrocode->getPtr() + sizeof(GLenum)));
// Add to the microcode to the cache
GpuProgramManager::getSingleton().addMicrocodeToCache(id, newMicrocode);
}
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
void GLSLESProgramCommon::notifyOnContextLost()
{
mLinked = false;
mUniformRefsBuilt = false;
for(auto s : mShaders)
{
if(s) s->getUniformCache()->clearCache();
}
}
void GLSLESProgramCommon::notifyOnContextReset()
{
activate();
}
#endif
} // namespace Ogre
<|endoftext|>
|
<commit_before>#include <set>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <uuid/uuid.h>
#include <vector>
#include <wchar.h>
#include <scxcorelib/scxcmn.h>
#include <scxcorelib/scxprocess.h>
#include <scxcorelib/stringaid.h>
#include <testutils/scxunit.h>
#include <testutils/providertestutils.h>
#include "Container_ImageInventory_Class_Provider.h"
#include "cjson/cJSON.h"
#include "TestScriptPath.h"
using namespace std;
using namespace SCXCoreLib;
class ImageInventoryTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(ImageInventoryTest);
CPPUNIT_TEST(TestEnumerateInstances);
CPPUNIT_TEST(TestEnumerateVerifyAllValues);
CPPUNIT_TEST(TestRunContainer);
CPPUNIT_TEST(TestRunFailedContainer);
CPPUNIT_TEST_SUITE_END();
private:
vector<string> containers;
static string NewGuid()
{
uuid_t uuid;
uuid_generate_random(uuid);
char s[37];
uuid_unparse(uuid, s);
return s;
}
static string RunCommand(const char* command)
{
istringstream processInput;
ostringstream processOutput;
ostringstream processErr;
CPPUNIT_ASSERT(!SCXProcess::Run(StrFromMultibyte(string(command)), processInput, processOutput, processErr, 0));
CPPUNIT_ASSERT_EQUAL(processErr.str(), string());
return processOutput.str();
}
public:
void setUp()
{
// Get some images to use
fputc('\n', stdout);
RunCommand("docker pull hello-world");
RunCommand("docker pull centos");
RunCommand("rm -f /var/opt/microsoft/docker-cimprov/state/ImageInventory/*");
}
void tearDown()
{
char command[128];
// Remove the containers that were started by the tests
for (unsigned i = 0; i < containers.size(); i++)
{
sprintf(command, "docker rm -f %s", containers[i].c_str());
RunCommand(command);
}
containers.clear();
}
protected:
void TestEnumerateInstances()
{
wstring errMsg;
TestableContext context;
vector<wstring> m_keyNames;
m_keyNames.push_back(L"InstanceID");
// Remove cached state
RunCommand("rm -f /var/opt/microsoft/docker-cimprov/state/ContainerInventory/*");
// Enumerate provider
StandardTestEnumerateInstances<mi::Container_ImageInventory_Class_Provider>(m_keyNames, context, CALL_LOCATION(errMsg));
// Get images using command line
CPPUNIT_ASSERT(!system("docker images -q --no-trunc > /tmp/docker_image_ids.txt"));
FILE* idFile = fopen("/tmp/docker_image_ids.txt", "r");
CPPUNIT_ASSERT(idFile);
wchar_t id[65];
set<wstring> allIds;
// Full image IDs (one per line)
while (fwscanf(idFile, L"%ls", id) != EOF)
{
allIds.insert(wstring(id));
}
fclose(idFile);
remove("/tmp/docker_image_ids.txt");
CPPUNIT_ASSERT_EQUAL(allIds.size(), context.Size());
for (unsigned i = 0; i < context.Size(); ++i)
{
// Verify the InstanceID
CPPUNIT_ASSERT(allIds.count(context[i].GetKey(L"InstanceID", CALL_LOCATION(errMsg))));
}
}
void TestEnumerateVerifyAllValues()
{
wstring errMsg;
TestableContext context;
vector<wstring> m_keyNames;
m_keyNames.push_back(L"InstanceID");
// Remove cached state
RunCommand("rm -f /var/opt/microsoft/docker-cimprov/state/ContainerInventory/*");
// Enumerate provider
StandardTestEnumerateInstances<mi::Container_ImageInventory_Class_Provider>(m_keyNames, context, CALL_LOCATION(errMsg));
// Get image inventory using a script
char command[256];
sprintf(command, "python %sImageInventory.py > /tmp/docker_image_inventory.txt", TEST_SCRIPT_PATH);
CPPUNIT_ASSERT(!system(command));
FILE* imageFile = fopen("/tmp/docker_image_inventory.txt", "r");
CPPUNIT_ASSERT(imageFile);
char buffer[1024];
vector<cJSON*> images;
while (fgets(buffer, 1023, imageFile))
{
images.push_back(cJSON_Parse(buffer));
}
fclose(imageFile);
remove("/tmp/docker_image_inventory.txt");
// Should have same number of images
CPPUNIT_ASSERT_EQUAL(images.size(), context.Size());
wchar_t currentId[66];
int imageCount = 0;
// Verify every field of every object
for (unsigned i = 0; i < images.size(); i++)
{
bool flag = false;
mbstowcs(currentId, cJSON_GetObjectItem(images[i], "InstanceID")->valuestring, 65);
for (unsigned j = 0; !flag && j < context.Size(); j++)
{
if (!context[j].GetProperty(L"InstanceID", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)).compare(wstring(currentId)))
{
wchar_t temp[512];
unsigned count = 0;
mbstowcs(temp, cJSON_GetObjectItem(images[i], "Image")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"Image", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
mbstowcs(temp, cJSON_GetObjectItem(images[i], "Repository")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"Repository", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
mbstowcs(temp, cJSON_GetObjectItem(images[i], "ImageTag")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"ImageTag", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
mbstowcs(temp, cJSON_GetObjectItem(images[i], "Computer")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"Computer", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
mbstowcs(temp, cJSON_GetObjectItem(images[i], "ImageSize")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"ImageSize", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
mbstowcs(temp, cJSON_GetObjectItem(images[i], "VirtualSize")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"VirtualSize", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
count = cJSON_GetObjectItem(images[i], "Running")->valueint;
CPPUNIT_ASSERT_EQUAL(count, context[j].GetProperty(L"Running", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
count = cJSON_GetObjectItem(images[i], "Stopped")->valueint;
CPPUNIT_ASSERT_EQUAL(count, context[j].GetProperty(L"Stopped", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
count = cJSON_GetObjectItem(images[i], "Failed")->valueint;
CPPUNIT_ASSERT_EQUAL(count, context[j].GetProperty(L"Failed", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
count = cJSON_GetObjectItem(images[i], "Paused")->valueint;
CPPUNIT_ASSERT_EQUAL(count, context[j].GetProperty(L"Paused", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
count = cJSON_GetObjectItem(images[i], "Total")->valueint;
CPPUNIT_ASSERT_EQUAL(count, context[j].GetProperty(L"Total", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
flag = true;
imageCount += 1;
}
}
cJSON_Delete(images[i]);
}
// Ensure all objects were validated
CPPUNIT_ASSERT_EQUAL(imageCount, context.Size());
}
void TestRunContainer()
{
wstring errMsg;
TestableContext context;
vector<wstring> m_keyNames;
m_keyNames.push_back(L"InstanceID");
// Remove cached state
RunCommand("rm -f /var/opt/microsoft/docker-cimprov/state/ContainerInventory/*");
char containerName[64];
strcpy(containerName, NewGuid().c_str());
containers.push_back(string(containerName));
char command[128];
sprintf(command, "docker run --name=%s hello-world", containerName);
CPPUNIT_ASSERT(!system(command));
sleep(5);
bool flag = false;
// Enumerate provider
StandardTestEnumerateInstances<mi::Container_ImageInventory_Class_Provider>(m_keyNames, context, CALL_LOCATION(errMsg));
for (unsigned i = 0; !flag && i < context.Size(); ++i)
{
if (!context[i].GetProperty(L"Image", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)).compare(L"hello-world"))
{
// Checke that the number of stopped containers is not 0
CPPUNIT_ASSERT(context[i].GetProperty(L"Stopped", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
flag = true;
}
}
}
void TestRunFailedContainer()
{
wstring errMsg;
TestableContext context;
vector<wstring> m_keyNames;
m_keyNames.push_back(L"InstanceID");
// Remove cached state
RunCommand("rm -f /var/opt/microsoft/docker-cimprov/state/ContainerInventory/*");
char containerName[64];
strcpy(containerName, NewGuid().c_str());
containers.push_back(string(containerName));
char command[128];
sprintf(command, "docker run --name=%s centos false", containerName);
CPPUNIT_ASSERT(system(command));
sleep(5);
bool flag = false;
// Enumerate provider
StandardTestEnumerateInstances<mi::Container_ImageInventory_Class_Provider>(m_keyNames, context, CALL_LOCATION(errMsg));
for (unsigned i = 0; !flag && i < context.Size(); ++i)
{
if (!context[i].GetProperty(L"Image", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)).compare(L"centos"))
{
// Check that the number of failed containers is not 0
CPPUNIT_ASSERT(context[i].GetProperty(L"Failed", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
flag = true;
}
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(ImageInventoryTest);<commit_msg>Fix image inventory unit test: Buffer for ID was too short.<commit_after>#include <set>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <uuid/uuid.h>
#include <vector>
#include <wchar.h>
#include <scxcorelib/scxcmn.h>
#include <scxcorelib/scxprocess.h>
#include <scxcorelib/stringaid.h>
#include <testutils/scxunit.h>
#include <testutils/providertestutils.h>
#include "Container_ImageInventory_Class_Provider.h"
#include "cjson/cJSON.h"
#include "TestScriptPath.h"
using namespace std;
using namespace SCXCoreLib;
class ImageInventoryTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(ImageInventoryTest);
CPPUNIT_TEST(TestEnumerateInstances);
CPPUNIT_TEST(TestEnumerateVerifyAllValues);
CPPUNIT_TEST(TestRunContainer);
CPPUNIT_TEST(TestRunFailedContainer);
CPPUNIT_TEST_SUITE_END();
private:
vector<string> containers;
static string NewGuid()
{
uuid_t uuid;
uuid_generate_random(uuid);
char s[37];
uuid_unparse(uuid, s);
return s;
}
static string RunCommand(const char* command)
{
istringstream processInput;
ostringstream processOutput;
ostringstream processErr;
CPPUNIT_ASSERT(!SCXProcess::Run(StrFromMultibyte(string(command)), processInput, processOutput, processErr, 0));
CPPUNIT_ASSERT_EQUAL(processErr.str(), string());
return processOutput.str();
}
public:
void setUp()
{
// Get some images to use
fputc('\n', stdout);
RunCommand("docker pull hello-world");
RunCommand("docker pull centos");
RunCommand("rm -f /var/opt/microsoft/docker-cimprov/state/ImageInventory/*");
}
void tearDown()
{
char command[128];
// Remove the containers that were started by the tests
for (unsigned i = 0; i < containers.size(); i++)
{
sprintf(command, "docker rm -f %s", containers[i].c_str());
RunCommand(command);
}
containers.clear();
}
protected:
void TestEnumerateInstances()
{
wstring errMsg;
TestableContext context;
vector<wstring> m_keyNames;
m_keyNames.push_back(L"InstanceID");
// Remove cached state
RunCommand("rm -f /var/opt/microsoft/docker-cimprov/state/ContainerInventory/*");
// Enumerate provider
StandardTestEnumerateInstances<mi::Container_ImageInventory_Class_Provider>(m_keyNames, context, CALL_LOCATION(errMsg));
// Get images using command line
CPPUNIT_ASSERT(!system("docker images -q --no-trunc > /tmp/docker_image_ids.txt"));
FILE* idFile = fopen("/tmp/docker_image_ids.txt", "r");
CPPUNIT_ASSERT(idFile);
wchar_t id[65];
set<wstring> allIds;
// Full image IDs (one per line)
while (fwscanf(idFile, L"%ls", id) != EOF)
{
allIds.insert(wstring(id));
}
fclose(idFile);
remove("/tmp/docker_image_ids.txt");
CPPUNIT_ASSERT_EQUAL(allIds.size(), context.Size());
for (unsigned i = 0; i < context.Size(); ++i)
{
// Verify the InstanceID
CPPUNIT_ASSERT(allIds.count(context[i].GetKey(L"InstanceID", CALL_LOCATION(errMsg))));
}
}
void TestEnumerateVerifyAllValues()
{
wstring errMsg;
TestableContext context;
vector<wstring> m_keyNames;
m_keyNames.push_back(L"InstanceID");
// Remove cached state
RunCommand("rm -f /var/opt/microsoft/docker-cimprov/state/ContainerInventory/*");
// Enumerate provider
StandardTestEnumerateInstances<mi::Container_ImageInventory_Class_Provider>(m_keyNames, context, CALL_LOCATION(errMsg));
// Get image inventory using a script
char command[256];
sprintf(command, "python %sImageInventory.py > /tmp/docker_image_inventory.txt", TEST_SCRIPT_PATH);
CPPUNIT_ASSERT(!system(command));
FILE* imageFile = fopen("/tmp/docker_image_inventory.txt", "r");
CPPUNIT_ASSERT(imageFile);
char buffer[1024];
vector<cJSON*> images;
while (fgets(buffer, 1023, imageFile))
{
images.push_back(cJSON_Parse(buffer));
}
fclose(imageFile);
remove("/tmp/docker_image_inventory.txt");
// Should have same number of images
CPPUNIT_ASSERT_EQUAL(images.size(), context.Size());
wchar_t currentId[128];
int imageCount = 0;
// Verify every field of every object
for (unsigned i = 0; i < images.size(); i++)
{
bool flag = false;
int rc = mbstowcs(currentId, cJSON_GetObjectItem(images[i], "InstanceID")->valuestring, (sizeof(currentId)/sizeof(currentId[0])) - 1);
if (rc > 0 && rc < sizeof(currentId)/sizeof(currentId[0])) currentId[rc] = 0;
for (unsigned j = 0; !flag && j < context.Size(); j++)
{
if (!context[j].GetProperty(L"InstanceID", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)).compare(wstring(currentId)))
{
wchar_t temp[512];
unsigned count = 0;
mbstowcs(temp, cJSON_GetObjectItem(images[i], "Image")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"Image", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
mbstowcs(temp, cJSON_GetObjectItem(images[i], "Repository")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"Repository", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
mbstowcs(temp, cJSON_GetObjectItem(images[i], "ImageTag")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"ImageTag", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
mbstowcs(temp, cJSON_GetObjectItem(images[i], "Computer")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"Computer", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
mbstowcs(temp, cJSON_GetObjectItem(images[i], "ImageSize")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"ImageSize", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
mbstowcs(temp, cJSON_GetObjectItem(images[i], "VirtualSize")->valuestring, 511);
CPPUNIT_ASSERT_EQUAL(wstring(temp), context[j].GetProperty(L"VirtualSize", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));
count = cJSON_GetObjectItem(images[i], "Running")->valueint;
CPPUNIT_ASSERT_EQUAL(count, context[j].GetProperty(L"Running", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
count = cJSON_GetObjectItem(images[i], "Stopped")->valueint;
CPPUNIT_ASSERT_EQUAL(count, context[j].GetProperty(L"Stopped", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
count = cJSON_GetObjectItem(images[i], "Failed")->valueint;
CPPUNIT_ASSERT_EQUAL(count, context[j].GetProperty(L"Failed", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
count = cJSON_GetObjectItem(images[i], "Paused")->valueint;
CPPUNIT_ASSERT_EQUAL(count, context[j].GetProperty(L"Paused", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
count = cJSON_GetObjectItem(images[i], "Total")->valueint;
CPPUNIT_ASSERT_EQUAL(count, context[j].GetProperty(L"Total", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
flag = true;
imageCount += 1;
}
}
cJSON_Delete(images[i]);
}
// Ensure all objects were validated
CPPUNIT_ASSERT_EQUAL(imageCount, context.Size());
}
void TestRunContainer()
{
wstring errMsg;
TestableContext context;
vector<wstring> m_keyNames;
m_keyNames.push_back(L"InstanceID");
// Remove cached state
RunCommand("rm -f /var/opt/microsoft/docker-cimprov/state/ContainerInventory/*");
char containerName[64];
strcpy(containerName, NewGuid().c_str());
containers.push_back(string(containerName));
char command[128];
sprintf(command, "docker run --name=%s hello-world", containerName);
CPPUNIT_ASSERT(!system(command));
sleep(5);
bool flag = false;
// Enumerate provider
StandardTestEnumerateInstances<mi::Container_ImageInventory_Class_Provider>(m_keyNames, context, CALL_LOCATION(errMsg));
for (unsigned i = 0; !flag && i < context.Size(); ++i)
{
if (!context[i].GetProperty(L"Image", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)).compare(L"hello-world"))
{
// Checke that the number of stopped containers is not 0
CPPUNIT_ASSERT(context[i].GetProperty(L"Stopped", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
flag = true;
}
}
}
void TestRunFailedContainer()
{
wstring errMsg;
TestableContext context;
vector<wstring> m_keyNames;
m_keyNames.push_back(L"InstanceID");
// Remove cached state
RunCommand("rm -f /var/opt/microsoft/docker-cimprov/state/ContainerInventory/*");
char containerName[64];
strcpy(containerName, NewGuid().c_str());
containers.push_back(string(containerName));
char command[128];
sprintf(command, "docker run --name=%s centos false", containerName);
CPPUNIT_ASSERT(system(command));
sleep(5);
bool flag = false;
// Enumerate provider
StandardTestEnumerateInstances<mi::Container_ImageInventory_Class_Provider>(m_keyNames, context, CALL_LOCATION(errMsg));
for (unsigned i = 0; !flag && i < context.Size(); ++i)
{
if (!context[i].GetProperty(L"Image", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)).compare(L"centos"))
{
// Check that the number of failed containers is not 0
CPPUNIT_ASSERT(context[i].GetProperty(L"Failed", CALL_LOCATION(errMsg)).GetValue_MIUint32(CALL_LOCATION(errMsg)));
flag = true;
}
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(ImageInventoryTest);<|endoftext|>
|
<commit_before>#include "../../battery.h"
#include "../../../utils.h"
#define BATTERY_BASE_DIR "/proc/acpi/battery/"
AspectsRegister Battery::aspectsRegister("Battery", getInstance());
Battery * Battery::battery = 0;
Battery * Battery::getInstance() {
if ( battery == 0 )
battery = new Battery();
return battery;
}
vector<string> Battery::getComponents()
{
vector<string> components;
components.insert(components.end(), "_default");
components.insert(components.end(), "_active");
string res = Utils::exec(string("ls -1 ") + BATTERY_BASE_DIR);
int pos, lastpos = 0;
while ( (pos = res.find('\n',lastpos)) != string::npos)
{
components.insert(components.end(), res.substr(lastpos, pos-lastpos).c_str());
lastpos = pos+1;
}
return components;
}
bool Battery::isSupported(string * property)
{
return true;
}
string Battery::getPropertyValue(string * property, string * component)
{
if (*property == "batteryLevel")
return batteryLevel(*component);
if (*property == "batteryBeingCharged")
return batteryBeingCharged(*component);
// TODO: instead trigger the error callback with DOMError of type InvalidAccessError (or abort if no error callback defined)
return "Invalid property";
}
string Battery::batteryLevel(string batteryName)
{
string line, tmp;
int lastFullCapacity, remainingCapacity;
if (batteryName[0] == '_')
batteryName = getComponents()[2];
string batteryInfoFile(BATTERY_BASE_DIR + batteryName + "/info");
string batteryStateFile(BATTERY_BASE_DIR + batteryName + "/state");
char* res = new char[7];
ifstream info(batteryInfoFile.c_str());
while(getline(info, line))
{
if (line.find("last full capacity") != string::npos)
{
stringstream linestream(line);
linestream >> tmp >> tmp >> tmp >> lastFullCapacity >> tmp;
break;
}
}
ifstream state(batteryStateFile.c_str());
while(getline(state, line))
{
if (line.find("remaining capacity") != string::npos)
{
stringstream linestream(line);
linestream >> tmp >> tmp >> remainingCapacity >> tmp;
break;
}
}
sprintf(res, "%.2f", (float)remainingCapacity / lastFullCapacity * 100);
// cout << res;
return string(res);
}
string Battery::batteryBeingCharged(string batteryName)
{
string line, tmp;
string chargingState;
if (batteryName[0] == '_')
batteryName = getComponents()[2];
string batteryStateFile(BATTERY_BASE_DIR + batteryName + "/state");
ifstream state(batteryStateFile.c_str());
while(getline(state, line))
{
if (line.find("charging state") != string::npos)
{
stringstream linestream(line);
linestream >> tmp >> tmp >> chargingState;
break;
}
}
return chargingState == "charging" ? "true" : "false";
}
<commit_msg>Fixed bug including missing libraries<commit_after>#include "../../battery.h"
#include "../../../utils.h"
#include <iostream>
#include <fstream>
#include <sstream>
#define BATTERY_BASE_DIR "/proc/acpi/battery/"
AspectsRegister Battery::aspectsRegister("Battery", getInstance());
Battery * Battery::battery = 0;
Battery * Battery::getInstance() {
if ( battery == 0 )
battery = new Battery();
return battery;
}
vector<string> Battery::getComponents()
{
vector<string> components;
components.insert(components.end(), "_default");
components.insert(components.end(), "_active");
string res = Utils::exec(string("ls -1 ") + BATTERY_BASE_DIR);
int pos, lastpos = 0;
while ( (pos = res.find('\n',lastpos)) != string::npos)
{
components.insert(components.end(), res.substr(lastpos, pos-lastpos).c_str());
lastpos = pos+1;
}
return components;
}
bool Battery::isSupported(string * property)
{
return true;
}
string Battery::getPropertyValue(string * property, string * component)
{
if (*property == "batteryLevel")
return batteryLevel(*component);
if (*property == "batteryBeingCharged")
return batteryBeingCharged(*component);
// TODO: instead trigger the error callback with DOMError of type InvalidAccessError (or abort if no error callback defined)
return "Invalid property";
}
string Battery::batteryLevel(string batteryName)
{
string line, tmp;
int lastFullCapacity, remainingCapacity;
if (batteryName[0] == '_')
batteryName = getComponents()[2];
string batteryInfoFile(BATTERY_BASE_DIR + batteryName + "/info");
string batteryStateFile(BATTERY_BASE_DIR + batteryName + "/state");
char* res = new char[7];
ifstream info(batteryInfoFile.c_str());
while(getline(info, line))
{
if (line.find("last full capacity") != string::npos)
{
stringstream linestream(line);
linestream >> tmp >> tmp >> tmp >> lastFullCapacity >> tmp;
break;
}
}
ifstream state(batteryStateFile.c_str());
while(getline(state, line))
{
if (line.find("remaining capacity") != string::npos)
{
stringstream linestream(line);
linestream >> tmp >> tmp >> remainingCapacity >> tmp;
break;
}
}
sprintf(res, "%.2f", (float)remainingCapacity / lastFullCapacity * 100);
// cout << res;
return string(res);
}
string Battery::batteryBeingCharged(string batteryName)
{
string line, tmp;
string chargingState;
if (batteryName[0] == '_')
batteryName = getComponents()[2];
string batteryStateFile(BATTERY_BASE_DIR + batteryName + "/state");
ifstream state(batteryStateFile.c_str());
while(getline(state, line))
{
if (line.find("charging state") != string::npos)
{
stringstream linestream(line);
linestream >> tmp >> tmp >> chargingState;
break;
}
}
return chargingState == "charging" ? "true" : "false";
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014 Dims dev-team
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addressToCoins.h"
#include <boost/foreach.hpp>
//#include <stdint.h>
namespace tracker
{
template <class K, class T, char _prefix >
class CBatchWrite
{
public:
void insert( K _key, T _object )
{
m_batch.Write( std::make_pair(_prefix, _key), _object );
}
CLevelDBBatch & getBatch(){ return m_batch; }
private:
CLevelDBBatch m_batch;
};
CAddressToCoinsDatabase::CAddressToCoinsDatabase(size_t nCacheSize, bool fMemory, bool fWipe)
: db(GetDataDir(common::AppType::Tracker) / "addressTocoins",
nCacheSize,
fMemory,
fWipe)
{
}
bool
CAddressToCoinsDatabase::getCoinsAmount(const uint160 &_keyId, uint64_t & _amount )
{
return db.Read( std::make_pair('a', _keyId), _amount );
}
bool
CAddressToCoinsDatabase::setCoinsAmount(uint160 const &_keyId, uint64_t const _amount)
{
return db.Write( std::make_pair('a', _keyId), _amount );
}
bool
CAddressToCoinsDatabase::getCoin(CKeyType const &_keyId, uint256 &coins)
{
return db.Read( std::make_pair('c', _keyId), coins );
}
bool
CAddressToCoinsDatabase::setCoin(CKeyType const &_keyId, uint256 const &coins)
{
return db.Write( std::make_pair('c', _keyId), coins );
}
bool
CAddressToCoinsDatabase::eraseCoin( uint256 const &_keyId )
{
return db.Erase( std::make_pair('c', _keyId) );
}
bool
CAddressToCoinsDatabase::haveCoin(uint160 const &_keyId)
{
return db.Exists( std::make_pair( 'a', _keyId ) );
}
void
CAddressToCoinsDatabase::clearView()
{
return db.clear();
}
bool
CAddressToCoinsDatabase::haveCoin(CKeyType const &_keyId)
{
return db.Exists( std::make_pair( 'c', _keyId ) );
}
CAddressToCoins::CAddressToCoins( size_t _cacheSize)
:CAddressToCoinsDatabase( _cacheSize, false, false )
{
}
bool CAddressToCoins::getCoinsAmount( uint160 const &_keyId, uint64_t & _amount )
{
_amount = 0;
CKeyType key( _keyId );
if ( !haveCoin(_keyId) )
return false;
uint64_t potential;
if ( !CAddressToCoinsDatabase::getCoinsAmount(_keyId, potential) )
return false;
while( potential-- )
{
uint256 coin;
if ( haveCoin((CKeyType&)++key) )
{
_amount++;
}
}
return true;
}
bool
CAddressToCoins::getCoins( uint160 const &_keyId, std::vector< uint256 > &_coins )
{
CKeyType key( _keyId );
uint64_t amount;
if ( !haveCoin(_keyId) )
return false;
if ( !CAddressToCoinsDatabase::getCoinsAmount(_keyId, amount) )
return false;
while( amount-- )
{
uint256 coin;
if ( haveCoin((CKeyType&)++key) )
{
getCoin( key, coin );
_coins.push_back( coin );
}
}
return true;
}
typedef std::map< uint256, uint256 > KeyToCoins;
bool CAddressToCoins::eraseCoin( uint160 const &_keyId, uint256 const & _coin )
{
KeyToCoins keyToCoins;
if ( !getCoins(_keyId, keyToCoins ) )
return false;
KeyToCoins::iterator iterator = keyToCoins.begin();
while( iterator != keyToCoins.end() )
{
if( iterator->second != _coin )
{
keyToCoins.erase(iterator++);
}
else
{
++iterator;
}
}
BOOST_FOREACH( KeyToCoins::value_type & coins, keyToCoins )
{
CAddressToCoinsDatabase::eraseCoin( coins.first );
}
return true;
}
bool
CAddressToCoins::getCoins( uint160 const &_keyId, std::map< uint256 , uint256 > &_coins )
{
CKeyType key( _keyId );
uint64_t amount;
if ( !haveCoin(_keyId) )
return false;
if ( !getCoinsAmount(_keyId, amount) )
return false;
while( amount-- )
{
uint256 coin;
if ( haveCoin((CKeyType&)++key) )
{
getCoin( key, coin );
_coins.insert(std::make_pair( key, coin ) );
}
}
return true;
}
bool
CAddressToCoins::setCoins( uint160 const &_keyId, uint256 const & _coin )
{
uint64_t amount;
if ( !getCoinsAmount(_keyId, amount) )
amount = 0;
if ( !setCoinsAmount(_keyId, ++amount ) )
return false;
CKeyType key( _keyId );
if ( !setCoin((CKeyType &)++key, _coin ) )
{
setCoinsAmount(_keyId, --amount );
return false;
}
return true;
}
bool
CAddressToCoins::batchWrite( std::multimap<uint160,uint256> const &mapCoins )
{
CBatchWrite< uint160, uint64_t, 'a' > amountBatch;
CBatchWrite< CKeyType, uint256, 'c' > coinsBatch;
std::multimap<uint160,uint256>::const_iterator iterator = mapCoins.begin(), end;
while( iterator != mapCoins.end() )
{
end = mapCoins.upper_bound( iterator->first );
uint64_t amount = 0;
CKeyType key( iterator->first );
uint160 firstKey = iterator->first;
getCoinsAmount(firstKey, amount);
key += amount;
while( iterator != end )
{
amount++;
coinsBatch.insert( (CKeyType&)++key, iterator->second );
iterator++;
}
amountBatch.insert( firstKey, amount );
}
CAddressToCoinsDatabase::batchWrite( amountBatch );
CAddressToCoinsDatabase::batchWrite( coinsBatch );
return true;
}
void
CAddressToCoins::clearView()
{
CAddressToCoinsDatabase::clearView();
}
CAddressToCoinsViewCache * CAddressToCoinsViewCache::ms_instance = NULL;
CAddressToCoinsViewCache*
CAddressToCoinsViewCache::getInstance()
{
if ( !ms_instance )
{
ms_instance = new CAddressToCoinsViewCache();
};
return ms_instance;
}
bool CAddressToCoinsViewCache::getCoins( uint160 const &_keyId, std::vector< uint256 > &_coins )
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
std::map<uint160,uint256>::iterator it = fetchCoins(_keyId);
while(it != cacheCoins.end() && it->first == _keyId)
{
_coins.push_back( it->second );
it++;
}
return !_coins.empty();
}
bool CAddressToCoinsViewCache::setCoins( uint160 const &_keyId, uint256 const & _coin )
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
insertCacheCoins.insert( std::make_pair( _keyId, _coin ) );
return true;
}
bool CAddressToCoinsViewCache::haveCoins(const uint160 &txid)
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
return fetchCoins(txid) != cacheCoins.end();
}
std::map<uint160,uint256>::iterator
CAddressToCoinsViewCache::fetchCoins(const uint160 &_keyId, bool secondPass )
{
if ( !secondPass )
boost::lock_guard<boost::mutex> lock( m_cacheLock );
std::map<uint160,uint256>::iterator it = cacheCoins.lower_bound(_keyId);
if ( it != cacheCoins.end() && it->first == _keyId )
{
unsigned int distance = std::distance( it, cacheCoins.upper_bound(_keyId));
uint64_t amount;
m_addressToCoins.getCoinsAmount( _keyId, amount );
if ( distance == amount )
return it;
if ( secondPass )// ugly way to indicate error
throw;
}
std::vector< uint256 > tmp;
if ( !m_addressToCoins.getCoins(_keyId,tmp) )
return cacheCoins.end();
BOOST_FOREACH( uint256 & coin, tmp )
{
it = cacheCoins.lower_bound( _keyId );
if ( it == cacheCoins.end() )
cacheCoins.insert(it, std::make_pair(_keyId, coin));
else
{
bool insert = true;
std::map<uint160,uint256>::iterator upper = cacheCoins.upper_bound(_keyId);
while( it!= upper )
{
if ( it->second == coin )
{
insert =false;
break;
}
it++;
}
if ( insert )
cacheCoins.insert(it, std::make_pair(_keyId, coin));
}
}
return fetchCoins(_keyId, true);
}
bool
CAddressToCoinsViewCache::eraseCoins( uint160 const &_keyId, uint256 const & _coin )
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
std::multimap<uint160,uint256>::iterator iterator = cacheCoins.find( _keyId );
if ( iterator != cacheCoins.end() && iterator->second == _coin )
cacheCoins.erase( _keyId );
m_addressToCoins.eraseCoin( _keyId, _coin );
return true;
}
bool
CAddressToCoinsViewCache::flush()
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
bool ok = m_addressToCoins.batchWrite(insertCacheCoins);
if (ok)
insertCacheCoins.clear();
return ok;
}
void
CAddressToCoinsViewCache::clearView()
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
insertCacheCoins.clear();
m_addressToCoins.clearView();
}
CAddressToCoinsViewCache::~CAddressToCoinsViewCache()
{
ms_instance = 0;
}
}
<commit_msg>fix previous<commit_after>// Copyright (c) 2014 Dims dev-team
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addressToCoins.h"
#include <boost/foreach.hpp>
//#include <stdint.h>
namespace tracker
{
template <class K, class T, char _prefix >
class CBatchWrite
{
public:
void insert( K _key, T _object )
{
m_batch.Write( std::make_pair(_prefix, _key), _object );
}
CLevelDBBatch & getBatch(){ return m_batch; }
private:
CLevelDBBatch m_batch;
};
CAddressToCoinsDatabase::CAddressToCoinsDatabase(size_t nCacheSize, bool fMemory, bool fWipe)
: db(GetDataDir(common::AppType::Tracker) / "addressTocoins",
nCacheSize,
fMemory,
fWipe)
{
}
bool
CAddressToCoinsDatabase::getCoinsAmount(const uint160 &_keyId, uint64_t & _amount )
{
return db.Read( std::make_pair('a', _keyId), _amount );
}
bool
CAddressToCoinsDatabase::setCoinsAmount(uint160 const &_keyId, uint64_t const _amount)
{
return db.Write( std::make_pair('a', _keyId), _amount );
}
bool
CAddressToCoinsDatabase::getCoin(CKeyType const &_keyId, uint256 &coins)
{
return db.Read( std::make_pair('c', _keyId), coins );
}
bool
CAddressToCoinsDatabase::setCoin(CKeyType const &_keyId, uint256 const &coins)
{
return db.Write( std::make_pair('c', _keyId), coins );
}
bool
CAddressToCoinsDatabase::eraseCoin( uint256 const &_keyId )
{
return db.Erase( std::make_pair('c', _keyId) );
}
bool
CAddressToCoinsDatabase::haveCoin(uint160 const &_keyId)
{
return db.Exists( std::make_pair( 'a', _keyId ) );
}
void
CAddressToCoinsDatabase::clearView()
{
return db.clear();
}
bool
CAddressToCoinsDatabase::haveCoin(CKeyType const &_keyId)
{
return db.Exists( std::make_pair( 'c', _keyId ) );
}
CAddressToCoins::CAddressToCoins( size_t _cacheSize)
:CAddressToCoinsDatabase( _cacheSize, false, false )
{
}
bool CAddressToCoins::getCoinsAmount( uint160 const &_keyId, uint64_t & _amount )
{
_amount = 0;
CKeyType key( _keyId );
if ( !haveCoin(_keyId) )
return false;
uint64_t potential;
if ( !CAddressToCoinsDatabase::getCoinsAmount(_keyId, potential) )
return false;
while( potential-- )
{
uint256 coin;
if ( haveCoin((CKeyType&)++key) )
{
_amount++;
}
}
return true;
}
bool
CAddressToCoins::getCoins( uint160 const &_keyId, std::vector< uint256 > &_coins )
{
CKeyType key( _keyId );
uint64_t amount;
if ( !haveCoin(_keyId) )
return false;
if ( !CAddressToCoinsDatabase::getCoinsAmount(_keyId, amount) )
return false;
while( amount-- )
{
uint256 coin;
if ( haveCoin((CKeyType&)++key) )
{
getCoin( key, coin );
_coins.push_back( coin );
}
}
return true;
}
typedef std::map< uint256, uint256 > KeyToCoins;
bool CAddressToCoins::eraseCoin( uint160 const &_keyId, uint256 const & _coin )
{
KeyToCoins keyToCoins;
if ( !getCoins(_keyId, keyToCoins ) )
return false;
KeyToCoins::iterator iterator = keyToCoins.begin();
while( iterator != keyToCoins.end() )
{
if( iterator->second != _coin )
{
keyToCoins.erase(iterator++);
}
else
{
++iterator;
}
}
BOOST_FOREACH( KeyToCoins::value_type & coins, keyToCoins )
{
CAddressToCoinsDatabase::eraseCoin( coins.first );
}
return true;
}
bool
CAddressToCoins::getCoins( uint160 const &_keyId, std::map< uint256 , uint256 > &_coins )
{
CKeyType key( _keyId );
uint64_t amount;
if ( !haveCoin(_keyId) )
return false;
if ( !getCoinsAmount(_keyId, amount) )
return false;
while( amount-- )
{
uint256 coin;
if ( haveCoin((CKeyType&)++key) )
{
getCoin( key, coin );
_coins.insert(std::make_pair( key, coin ) );
}
}
return true;
}
bool
CAddressToCoins::setCoins( uint160 const &_keyId, uint256 const & _coin )
{
uint64_t amount;
if ( !getCoinsAmount(_keyId, amount) )
amount = 0;
if ( !setCoinsAmount(_keyId, ++amount ) )
return false;
CKeyType key( _keyId );
if ( !setCoin((CKeyType &)++key, _coin ) )
{
setCoinsAmount(_keyId, --amount );
return false;
}
return true;
}
bool
CAddressToCoins::batchWrite( std::multimap<uint160,uint256> const &mapCoins )
{
CBatchWrite< uint160, uint64_t, 'a' > amountBatch;
CBatchWrite< CKeyType, uint256, 'c' > coinsBatch;
std::multimap<uint160,uint256>::const_iterator iterator = mapCoins.begin(), end;
while( iterator != mapCoins.end() )
{
end = mapCoins.upper_bound( iterator->first );
uint64_t amount = 0;
CKeyType key( iterator->first );
uint160 firstKey = iterator->first;
getCoinsAmount(firstKey, amount);
key += amount;
while( iterator != end )
{
amount++;
coinsBatch.insert( (CKeyType&)++key, iterator->second );
iterator++;
}
amountBatch.insert( firstKey, amount );
}
CAddressToCoinsDatabase::batchWrite( amountBatch );
CAddressToCoinsDatabase::batchWrite( coinsBatch );
return true;
}
void
CAddressToCoins::clearView()
{
CAddressToCoinsDatabase::clearView();
}
CAddressToCoinsViewCache * CAddressToCoinsViewCache::ms_instance = NULL;
CAddressToCoinsViewCache*
CAddressToCoinsViewCache::getInstance()
{
if ( !ms_instance )
{
ms_instance = new CAddressToCoinsViewCache();
};
return ms_instance;
}
bool CAddressToCoinsViewCache::getCoins( uint160 const &_keyId, std::vector< uint256 > &_coins )
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
std::map<uint160,uint256>::iterator it = fetchCoins(_keyId);
while(it != cacheCoins.end() && it->first == _keyId)
{
_coins.push_back( it->second );
it++;
}
return !_coins.empty();
}
bool CAddressToCoinsViewCache::setCoins( uint160 const &_keyId, uint256 const & _coin )
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
insertCacheCoins.insert( std::make_pair( _keyId, _coin ) );
return true;
}
bool CAddressToCoinsViewCache::haveCoins(const uint160 &txid)
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
return fetchCoins(txid) != cacheCoins.end();
}
std::map<uint160,uint256>::iterator
CAddressToCoinsViewCache::fetchCoins(const uint160 &_keyId, bool secondPass )
{
std::map<uint160,uint256>::iterator it = cacheCoins.lower_bound(_keyId);
if ( it != cacheCoins.end() && it->first == _keyId )
{
unsigned int distance = std::distance( it, cacheCoins.upper_bound(_keyId));
uint64_t amount;
m_addressToCoins.getCoinsAmount( _keyId, amount );
if ( distance == amount )
return it;
if ( secondPass )// ugly way to indicate error
throw;
}
std::vector< uint256 > tmp;
if ( !m_addressToCoins.getCoins(_keyId,tmp) )
return cacheCoins.end();
BOOST_FOREACH( uint256 & coin, tmp )
{
it = cacheCoins.lower_bound( _keyId );
if ( it == cacheCoins.end() )
cacheCoins.insert(it, std::make_pair(_keyId, coin));
else
{
bool insert = true;
std::map<uint160,uint256>::iterator upper = cacheCoins.upper_bound(_keyId);
while( it!= upper )
{
if ( it->second == coin )
{
insert =false;
break;
}
it++;
}
if ( insert )
cacheCoins.insert(it, std::make_pair(_keyId, coin));
}
}
return fetchCoins(_keyId, true);
}
bool
CAddressToCoinsViewCache::eraseCoins( uint160 const &_keyId, uint256 const & _coin )
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
std::multimap<uint160,uint256>::iterator iterator = cacheCoins.find( _keyId );
if ( iterator != cacheCoins.end() && iterator->second == _coin )
cacheCoins.erase( _keyId );
m_addressToCoins.eraseCoin( _keyId, _coin );
return true;
}
bool
CAddressToCoinsViewCache::flush()
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
bool ok = m_addressToCoins.batchWrite(insertCacheCoins);
if (ok)
insertCacheCoins.clear();
return ok;
}
void
CAddressToCoinsViewCache::clearView()
{
boost::lock_guard<boost::mutex> lock( m_cacheLock );
insertCacheCoins.clear();
m_addressToCoins.clearView();
}
CAddressToCoinsViewCache::~CAddressToCoinsViewCache()
{
ms_instance = 0;
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "AbstractObject.h"
#include <Corrade/Utility/Assert.h>
#include <Corrade/Containers/ArrayView.h>
#include "Magnum/Context.h"
#include "Magnum/Extensions.h"
#include "Implementation/State.h"
#ifndef MAGNUM_TARGET_WEBGL
#include "Implementation/DebugState.h"
#endif
namespace Magnum {
#ifndef MAGNUM_TARGET_WEBGL
#ifndef CORRADE_TARGET_NACL
namespace {
inline GLenum extTypeFromKhrIdentifier(GLenum khrIdentifier) {
switch(khrIdentifier) {
#ifndef MAGNUM_TARGET_GLES
case GL_BUFFER:
#else
case GL_BUFFER_KHR:
#endif
return GL_BUFFER_OBJECT_EXT;
#ifndef MAGNUM_TARGET_GLES
case GL_SHADER:
#else
case GL_SHADER_KHR:
#endif
return GL_SHADER_OBJECT_EXT;
#ifndef MAGNUM_TARGET_GLES
case GL_PROGRAM:
#else
case GL_PROGRAM_KHR:
#endif
return GL_PROGRAM_OBJECT_EXT;
#ifndef MAGNUM_TARGET_GLES
case GL_VERTEX_ARRAY:
#else
case GL_VERTEX_ARRAY_KHR:
#endif
return GL_VERTEX_ARRAY_OBJECT_EXT;
#ifndef MAGNUM_TARGET_GLES
case GL_QUERY:
#else
case GL_QUERY_KHR:
#endif
return GL_QUERY_OBJECT_EXT;
/** @todo Why isn't `GL_PROGRAM_PIPELINE_KHR` in ES's KHR_debug? */
#ifndef MAGNUM_TARGET_GLES
case GL_PROGRAM_PIPELINE:
#else
case 0x82E4: //GL_PROGRAM_PIPELINE_KHR:
#endif
return GL_PROGRAM_PIPELINE_OBJECT_EXT;
/**
* @todo Shouldn't ES2's KHR_debug have `GL_TRANSFORM_FEEDBACK_KHR`
* instead of `GL_TRANSFORM_FEEDBACK`? (it's a new enum in 2.0)
* NaCl extension header doesn't have it at all. Also the
* original @es_extension{EXT,debug_label} mentions it only
* for ES3 (i.e. no mention of @es_extension{EXT,transform_feedback})
*/
#ifndef CORRADE_TARGET_NACL
case GL_TRANSFORM_FEEDBACK:
#endif
#ifndef MAGNUM_TARGET_GLES
case GL_SAMPLER:
#else
case GL_SAMPLER_KHR:
#endif
case GL_TEXTURE:
case GL_RENDERBUFFER:
case GL_FRAMEBUFFER:
return khrIdentifier;
}
CORRADE_ASSERT_UNREACHABLE();
}
}
#endif
Int AbstractObject::maxLabelLength() {
if(!Context::current().isExtensionSupported<Extensions::GL::KHR::debug>())
return 0;
GLint& value = Context::current().state().debug->maxLabelLength;
if(value == 0) {
#ifndef MAGNUM_TARGET_GLES
glGetIntegerv(GL_MAX_LABEL_LENGTH, &value);
#else
glGetIntegerv(GL_MAX_LABEL_LENGTH_KHR, &value);
#endif
}
return value;
}
void AbstractObject::labelImplementationNoOp(GLenum, GLuint, Containers::ArrayView<const char>) {}
void AbstractObject::labelImplementationKhr(const GLenum identifier, const GLuint name, const Containers::ArrayView<const char> label) {
#ifndef MAGNUM_TARGET_GLES
glObjectLabel(identifier, name, label.size(), label);
#elif !defined(CORRADE_TARGET_NACL)
glObjectLabelKHR(identifier, name, label.size(), label);
#else
static_cast<void>(identifier);
static_cast<void>(name);
static_cast<void>(label);
CORRADE_ASSERT_UNREACHABLE();
#endif
}
void AbstractObject::labelImplementationExt(const GLenum identifier, const GLuint name, const Containers::ArrayView<const char> label) {
#ifndef CORRADE_TARGET_NACL
const GLenum type = extTypeFromKhrIdentifier(identifier);
glLabelObjectEXT(type, name, label.size(), label);
#else
static_cast<void>(identifier);
static_cast<void>(name);
static_cast<void>(label);
CORRADE_ASSERT_UNREACHABLE();
#endif
}
std::string AbstractObject::getLabelImplementationNoOp(GLenum, GLuint) { return {}; }
std::string AbstractObject::getLabelImplementationKhr(const GLenum identifier, const GLuint name) {
/* Get label size (w/o null terminator). Specifying 0 as size is not
allowed, thus we pass the maximum instead. */
GLsizei size = 0;
#ifndef MAGNUM_TARGET_GLES
glGetObjectLabel(identifier, name, maxLabelLength(), &size, nullptr);
#elif !defined(CORRADE_TARGET_NACL)
glGetObjectLabelKHR(identifier, name, maxLabelLength(), &size, nullptr);
#else
static_cast<void>(identifier);
static_cast<void>(name);
CORRADE_ASSERT_UNREACHABLE();
#endif
/* Make place also for the null terminator */
std::string label;
label.resize(size+1);
#ifndef MAGNUM_TARGET_GLES
glGetObjectLabel(identifier, name, size+1, nullptr, &label[0]);
#elif !defined(CORRADE_TARGET_NACL)
glGetObjectLabelKHR(identifier, name, size+1, nullptr, &label[0]);
#else
CORRADE_ASSERT_UNREACHABLE();
#endif
/* Pop null terminator and return the string */
label.resize(size);
return label;
}
std::string AbstractObject::getLabelImplementationExt(const GLenum identifier, const GLuint name) {
GLsizei size = 0;
/* Get label size (w/o null terminator) */
#ifndef CORRADE_TARGET_NACL
const GLenum type = extTypeFromKhrIdentifier(identifier);
glGetObjectLabelEXT(type, name, 0, &size, nullptr);
#else
static_cast<void>(identifier);
static_cast<void>(name);
CORRADE_ASSERT_UNREACHABLE();
#endif
/* Make place also for the null terminator */
std::string label;
label.resize(size+1);
#ifndef CORRADE_TARGET_NACL
glGetObjectLabelEXT(identifier, name, size+1, nullptr, &label[0]);
#else
CORRADE_ASSERT_UNREACHABLE();
#endif
/* Pop null terminator and return the string */
label.resize(size);
return label;
}
#endif
}
<commit_msg>Fix object label queries with EXT_debug_label.<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "AbstractObject.h"
#include <Corrade/Utility/Assert.h>
#include <Corrade/Containers/ArrayView.h>
#include "Magnum/Context.h"
#include "Magnum/Extensions.h"
#include "Implementation/State.h"
#ifndef MAGNUM_TARGET_WEBGL
#include "Implementation/DebugState.h"
#endif
namespace Magnum {
#ifndef MAGNUM_TARGET_WEBGL
#ifndef CORRADE_TARGET_NACL
namespace {
inline GLenum extTypeFromKhrIdentifier(GLenum khrIdentifier) {
switch(khrIdentifier) {
#ifndef MAGNUM_TARGET_GLES
case GL_BUFFER:
#else
case GL_BUFFER_KHR:
#endif
return GL_BUFFER_OBJECT_EXT;
#ifndef MAGNUM_TARGET_GLES
case GL_SHADER:
#else
case GL_SHADER_KHR:
#endif
return GL_SHADER_OBJECT_EXT;
#ifndef MAGNUM_TARGET_GLES
case GL_PROGRAM:
#else
case GL_PROGRAM_KHR:
#endif
return GL_PROGRAM_OBJECT_EXT;
#ifndef MAGNUM_TARGET_GLES
case GL_VERTEX_ARRAY:
#else
case GL_VERTEX_ARRAY_KHR:
#endif
return GL_VERTEX_ARRAY_OBJECT_EXT;
#ifndef MAGNUM_TARGET_GLES
case GL_QUERY:
#else
case GL_QUERY_KHR:
#endif
return GL_QUERY_OBJECT_EXT;
/** @todo Why isn't `GL_PROGRAM_PIPELINE_KHR` in ES's KHR_debug? */
#ifndef MAGNUM_TARGET_GLES
case GL_PROGRAM_PIPELINE:
#else
case 0x82E4: //GL_PROGRAM_PIPELINE_KHR:
#endif
return GL_PROGRAM_PIPELINE_OBJECT_EXT;
/**
* @todo Shouldn't ES2's KHR_debug have `GL_TRANSFORM_FEEDBACK_KHR`
* instead of `GL_TRANSFORM_FEEDBACK`? (it's a new enum in 2.0)
* NaCl extension header doesn't have it at all. Also the
* original @es_extension{EXT,debug_label} mentions it only
* for ES3 (i.e. no mention of @es_extension{EXT,transform_feedback})
*/
#ifndef CORRADE_TARGET_NACL
case GL_TRANSFORM_FEEDBACK:
#endif
#ifndef MAGNUM_TARGET_GLES
case GL_SAMPLER:
#else
case GL_SAMPLER_KHR:
#endif
case GL_TEXTURE:
case GL_RENDERBUFFER:
case GL_FRAMEBUFFER:
return khrIdentifier;
}
CORRADE_ASSERT_UNREACHABLE();
}
}
#endif
Int AbstractObject::maxLabelLength() {
if(!Context::current().isExtensionSupported<Extensions::GL::KHR::debug>())
return 0;
GLint& value = Context::current().state().debug->maxLabelLength;
if(value == 0) {
#ifndef MAGNUM_TARGET_GLES
glGetIntegerv(GL_MAX_LABEL_LENGTH, &value);
#else
glGetIntegerv(GL_MAX_LABEL_LENGTH_KHR, &value);
#endif
}
return value;
}
void AbstractObject::labelImplementationNoOp(GLenum, GLuint, Containers::ArrayView<const char>) {}
void AbstractObject::labelImplementationKhr(const GLenum identifier, const GLuint name, const Containers::ArrayView<const char> label) {
#ifndef MAGNUM_TARGET_GLES
glObjectLabel(identifier, name, label.size(), label);
#elif !defined(CORRADE_TARGET_NACL)
glObjectLabelKHR(identifier, name, label.size(), label);
#else
static_cast<void>(identifier);
static_cast<void>(name);
static_cast<void>(label);
CORRADE_ASSERT_UNREACHABLE();
#endif
}
void AbstractObject::labelImplementationExt(const GLenum identifier, const GLuint name, const Containers::ArrayView<const char> label) {
#ifndef CORRADE_TARGET_NACL
const GLenum type = extTypeFromKhrIdentifier(identifier);
glLabelObjectEXT(type, name, label.size(), label);
#else
static_cast<void>(identifier);
static_cast<void>(name);
static_cast<void>(label);
CORRADE_ASSERT_UNREACHABLE();
#endif
}
std::string AbstractObject::getLabelImplementationNoOp(GLenum, GLuint) { return {}; }
std::string AbstractObject::getLabelImplementationKhr(const GLenum identifier, const GLuint name) {
/* Get label size (w/o null terminator). Specifying 0 as size is not
allowed, thus we pass the maximum instead. */
GLsizei size = 0;
#ifndef MAGNUM_TARGET_GLES
glGetObjectLabel(identifier, name, maxLabelLength(), &size, nullptr);
#elif !defined(CORRADE_TARGET_NACL)
glGetObjectLabelKHR(identifier, name, maxLabelLength(), &size, nullptr);
#else
static_cast<void>(identifier);
static_cast<void>(name);
CORRADE_ASSERT_UNREACHABLE();
#endif
/* Make place also for the null terminator */
std::string label;
label.resize(size+1);
#ifndef MAGNUM_TARGET_GLES
glGetObjectLabel(identifier, name, size+1, nullptr, &label[0]);
#elif !defined(CORRADE_TARGET_NACL)
glGetObjectLabelKHR(identifier, name, size+1, nullptr, &label[0]);
#else
CORRADE_ASSERT_UNREACHABLE();
#endif
/* Pop null terminator and return the string */
label.resize(size);
return label;
}
std::string AbstractObject::getLabelImplementationExt(const GLenum identifier, const GLuint name) {
GLsizei size = 0;
/* Get label size (w/o null terminator) */
#ifndef CORRADE_TARGET_NACL
const GLenum type = extTypeFromKhrIdentifier(identifier);
glGetObjectLabelEXT(type, name, 0, &size, nullptr);
#else
static_cast<void>(identifier);
static_cast<void>(name);
CORRADE_ASSERT_UNREACHABLE();
#endif
/* Make place also for the null terminator */
std::string label;
label.resize(size+1);
#ifndef CORRADE_TARGET_NACL
glGetObjectLabelEXT(type, name, size+1, nullptr, &label[0]);
#else
CORRADE_ASSERT_UNREACHABLE();
#endif
/* Pop null terminator and return the string */
label.resize(size);
return label;
}
#endif
}
<|endoftext|>
|
<commit_before>/*
Copyright 2013 SINTEF ICT, Applied Mathematics.
*/
extern int yylex();
extern int yyparse();
#include "SymbolTable.hpp"
#include "CheckASTVisitor.hpp"
#include "PrintASTVisitor.hpp"
#include "PrintEquelleASTVisitor.hpp"
#include "PrintCPUBackendASTVisitor.hpp"
#include "PrintMRSTBackendASTVisitor.hpp"
#include "PrintCUDABackendASTVisitor.hpp"
#include "PrintMPIBackendASTVisitor.hpp"
#include "PrintIOVisitor.hpp"
#include "ASTNodes.hpp"
#include "CommandLineOptions.hpp"
#include <iostream>
extern int yylex();
extern int yyparse();
extern FILE * yyin;
/**
* Trivial class to properly close yyin
*/
class YYInOwner {
public:
YYInOwner(const std::string filename_) {
yyin = fopen(filename_.c_str(),"r");
if (!yyin) {
throw std::runtime_error("Input file not found.");
}
}
~YYInOwner() {
fclose(yyin);
yyin = NULL;
}
};
int main(int argc, char** argv)
{
CommandLineOptions options;
boost::program_options::variables_map cli_vars;
boost::shared_ptr<YYInOwner> yyin_owner;
//Parse commandline
try {
cli_vars = options.parse(argc, argv);
if (cli_vars.count("help")) {
std::cout << "Usage: ./eq <options>" << std::endl;
std::cout << "The following options are supported:" << std::endl;
options.printOptions();
return -1;
}
if (cli_vars.count("verbose")) {
options.printVars(cli_vars);
}
}
catch (const std::exception& e) {
std::cerr << "Usage: ./eq <options>" << std::endl;
std::cerr << "The following options are supported:" << std::endl;
options.printOptions();
std::cerr << std::endl;
std::cerr << "Error parsing options: ";
std::cerr << e.what() << std::endl;
return -1;
}
//Get input file
if (cli_vars.count("input")) {
std::string infile = cli_vars["input"].as<std::string>();
if (infile != "-") { //"-" signifies use stdin
yyin_owner.reset(new YYInOwner(infile));
}
}
//Parse equelle program
yyparse();
// Check AST (and build symbol table)
const bool ignore_dimensions = cli_vars.count("nondimensional");
CheckASTVisitor check(ignore_dimensions);
SymbolTable::program()->accept(check);
// Dump the SymbolTable
if (cli_vars["dump"].as<std::string>() == "symboltable") {
SymbolTable::dump();
}
//Write output
else {
std::string backend = cli_vars["backend"].as<std::string>();
if (backend == "ast") {
PrintASTVisitor v;
SymbolTable::program()->accept(v);
}
else if (backend == "equelle_ast") {
PrintEquelleASTVisitor v;
SymbolTable::program()->accept(v);
}
else if (backend == "cpu") {
// Check if we use the Cartesian dialect
const bool use_cartesian = cli_vars.count("cartesian");
PrintCPUBackendASTVisitor v(use_cartesian);
SymbolTable::program()->accept(v);
}
else if (backend == "cuda") {
PrintCUDABackendASTVisitor v;
SymbolTable::program()->accept(v);
}
else if (backend == "mrst") {
PrintMRSTBackendASTVisitor v;
SymbolTable::program()->accept(v);
}
else if(backend == "MPI") {
PrintMPIBackendASTVisitor v;
SymbolTable::program()->accept(v);
}
else if(backend == "io") {
PrintIOVisitor v;
SymbolTable::program()->accept(v);
}
else {
std::cerr << "Unknown back-end choice: " << backend << '\n';
}
}
//This assumes that the printing went well.
if (check.isValid())
{
return 0;
}
else
{
return -1;
}
}
<commit_msg>Delete extra declarations.<commit_after>/*
Copyright 2013 SINTEF ICT, Applied Mathematics.
*/
#include "SymbolTable.hpp"
#include "CheckASTVisitor.hpp"
#include "PrintASTVisitor.hpp"
#include "PrintEquelleASTVisitor.hpp"
#include "PrintCPUBackendASTVisitor.hpp"
#include "PrintMRSTBackendASTVisitor.hpp"
#include "PrintCUDABackendASTVisitor.hpp"
#include "PrintMPIBackendASTVisitor.hpp"
#include "PrintIOVisitor.hpp"
#include "ASTNodes.hpp"
#include "CommandLineOptions.hpp"
#include <iostream>
extern int yylex();
extern int yyparse();
extern FILE * yyin;
/**
* Trivial class to properly close yyin
*/
class YYInOwner {
public:
YYInOwner(const std::string filename_) {
yyin = fopen(filename_.c_str(),"r");
if (!yyin) {
throw std::runtime_error("Input file not found.");
}
}
~YYInOwner() {
fclose(yyin);
yyin = NULL;
}
};
int main(int argc, char** argv)
{
CommandLineOptions options;
boost::program_options::variables_map cli_vars;
boost::shared_ptr<YYInOwner> yyin_owner;
//Parse commandline
try {
cli_vars = options.parse(argc, argv);
if (cli_vars.count("help")) {
std::cout << "Usage: ./eq <options>" << std::endl;
std::cout << "The following options are supported:" << std::endl;
options.printOptions();
return -1;
}
if (cli_vars.count("verbose")) {
options.printVars(cli_vars);
}
}
catch (const std::exception& e) {
std::cerr << "Usage: ./eq <options>" << std::endl;
std::cerr << "The following options are supported:" << std::endl;
options.printOptions();
std::cerr << std::endl;
std::cerr << "Error parsing options: ";
std::cerr << e.what() << std::endl;
return -1;
}
//Get input file
if (cli_vars.count("input")) {
std::string infile = cli_vars["input"].as<std::string>();
if (infile != "-") { //"-" signifies use stdin
yyin_owner.reset(new YYInOwner(infile));
}
}
//Parse equelle program
yyparse();
// Check AST (and build symbol table)
const bool ignore_dimensions = cli_vars.count("nondimensional");
CheckASTVisitor check(ignore_dimensions);
SymbolTable::program()->accept(check);
// Dump the SymbolTable
if (cli_vars["dump"].as<std::string>() == "symboltable") {
SymbolTable::dump();
}
//Write output
else {
std::string backend = cli_vars["backend"].as<std::string>();
if (backend == "ast") {
PrintASTVisitor v;
SymbolTable::program()->accept(v);
}
else if (backend == "equelle_ast") {
PrintEquelleASTVisitor v;
SymbolTable::program()->accept(v);
}
else if (backend == "cpu") {
// Check if we use the Cartesian dialect
const bool use_cartesian = cli_vars.count("cartesian");
PrintCPUBackendASTVisitor v(use_cartesian);
SymbolTable::program()->accept(v);
}
else if (backend == "cuda") {
PrintCUDABackendASTVisitor v;
SymbolTable::program()->accept(v);
}
else if (backend == "mrst") {
PrintMRSTBackendASTVisitor v;
SymbolTable::program()->accept(v);
}
else if(backend == "MPI") {
PrintMPIBackendASTVisitor v;
SymbolTable::program()->accept(v);
}
else if(backend == "io") {
PrintIOVisitor v;
SymbolTable::program()->accept(v);
}
else {
std::cerr << "Unknown back-end choice: " << backend << '\n';
}
}
//This assumes that the printing went well.
if (check.isValid())
{
return 0;
}
else
{
return -1;
}
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
#include <GameServer/Achievement/Managers/AchievementManager.hpp>
using namespace GameServer::Epoch;
using namespace GameServer::Human;
using namespace GameServer::Land;
using namespace GameServer::Persistence;
using namespace GameServer::User;
using namespace GameServer::World;
namespace GameServer
{
namespace Achievement
{
AchievementManager::AchievementManager(
IAchievementPersistenceFacadeShrPtr a_achievement_persistence_facade,
IEpochPersistenceFacadeShrPtr a_epoch_persistence_facade,
IHumanPersistenceFacadeShrPtr a_human_persistence_facade,
ILandPersistenceFacadeShrPtr a_land_persistence_facade,
IUserPersistenceFacadeShrPtr a_user_persistence_facade,
IWorldPersistenceFacadeShrPtr a_world_persistence_facade
)
: m_achievement_persistence_facade(a_achievement_persistence_facade),
m_epoch_persistence_facade(a_epoch_persistence_facade),
m_human_persistence_facade(a_human_persistence_facade),
m_land_persistence_facade(a_land_persistence_facade),
m_user_persistence_facade(a_user_persistence_facade),
m_world_persistence_facade(a_world_persistence_facade)
{
}
bool AchievementManager::grantAchievements(
ITransactionShrPtr a_transaction,
IWorldShrPtr const a_world
) const
{
try
{
// Get the epoch of the world.
IEpochShrPtr epoch = m_epoch_persistence_facade->getEpoch(a_transaction, a_world->getWorldName());
if (!epoch)
{
return false;
}
// Get the lands of the world.
ILandMap lands = m_land_persistence_facade->getLands(a_transaction, a_world);
// Grant achievements to every land.
for (ILandMap::const_iterator it = lands.begin(); it != lands.end(); ++it)
{
bool const result = grantAchievements(a_transaction, epoch, it->second);
if (!result)
{
return false;
}
}
return true;
}
catch (...)
{
return false;
}
}
bool AchievementManager::grantAchievements(
Persistence::ITransactionShrPtr a_transaction,
Epoch::IEpochShrPtr const a_epoch,
Land::ILandShrPtr const a_land
) const
{
int const turns = a_land->getTurns();
if (turns == 88 or turns == 44 or turns == 22)
{
IUserShrPtr user = m_user_persistence_facade->getUser(a_transaction, a_land->getLogin());
if (!user)
{
return false;
}
switch (turns)
{
case 88:
return m_achievement_persistence_facade->grantAchievement(a_transaction, a_epoch, user, "survived88");
case 44:
return m_achievement_persistence_facade->grantAchievement(a_transaction, a_epoch, user, "survived44");
case 22:
return m_achievement_persistence_facade->grantAchievement(a_transaction, a_epoch, user, "survived22");
default:
BOOST_ASSERT(false);
}
}
return true;
}
} // namespace Achievement
} // namespace GameServer
<commit_msg>Achievements granted only if there are more than 500 humans in the land.<commit_after>// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
#include <GameServer/Achievement/Managers/AchievementManager.hpp>
using namespace GameServer::Epoch;
using namespace GameServer::Human;
using namespace GameServer::Land;
using namespace GameServer::Persistence;
using namespace GameServer::User;
using namespace GameServer::World;
namespace GameServer
{
namespace Achievement
{
AchievementManager::AchievementManager(
IAchievementPersistenceFacadeShrPtr a_achievement_persistence_facade,
IEpochPersistenceFacadeShrPtr a_epoch_persistence_facade,
IHumanPersistenceFacadeShrPtr a_human_persistence_facade,
ILandPersistenceFacadeShrPtr a_land_persistence_facade,
IUserPersistenceFacadeShrPtr a_user_persistence_facade,
IWorldPersistenceFacadeShrPtr a_world_persistence_facade
)
: m_achievement_persistence_facade(a_achievement_persistence_facade),
m_epoch_persistence_facade(a_epoch_persistence_facade),
m_human_persistence_facade(a_human_persistence_facade),
m_land_persistence_facade(a_land_persistence_facade),
m_user_persistence_facade(a_user_persistence_facade),
m_world_persistence_facade(a_world_persistence_facade)
{
}
bool AchievementManager::grantAchievements(
ITransactionShrPtr a_transaction,
IWorldShrPtr const a_world
) const
{
try
{
// Get the epoch of the world.
IEpochShrPtr epoch = m_epoch_persistence_facade->getEpoch(a_transaction, a_world->getWorldName());
if (!epoch)
{
return false;
}
// Get the lands of the world.
ILandMap lands = m_land_persistence_facade->getLands(a_transaction, a_world);
// Grant achievements to every land.
for (ILandMap::const_iterator it = lands.begin(); it != lands.end(); ++it)
{
bool const result = grantAchievements(a_transaction, epoch, it->second);
if (!result)
{
return false;
}
}
return true;
}
catch (...)
{
return false;
}
}
bool AchievementManager::grantAchievements(
Persistence::ITransactionShrPtr a_transaction,
Epoch::IEpochShrPtr const a_epoch,
Land::ILandShrPtr const a_land
) const
{
int const turns = a_land->getTurns();
if (turns == 88 or turns == 44 or turns == 22)
{
// TODO: Hardcoded human number.
if (m_human_persistence_facade->countHumans(a_transaction, a_land->getLandName()) > 500)
{
IUserShrPtr user = m_user_persistence_facade->getUser(a_transaction, a_land->getLogin());
if (!user)
{
return false;
}
switch (turns)
{
case 88:
return m_achievement_persistence_facade->grantAchievement(a_transaction, a_epoch, user, "survived88");
case 44:
return m_achievement_persistence_facade->grantAchievement(a_transaction, a_epoch, user, "survived44");
case 22:
return m_achievement_persistence_facade->grantAchievement(a_transaction, a_epoch, user, "survived22");
default:
BOOST_ASSERT(false);
}
}
}
return true;
}
} // namespace Achievement
} // namespace GameServer
<|endoftext|>
|
<commit_before>/**
* Copyright 2014-2015 MongoDB, 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 "hphp/runtime/ext/extension.h"
#include "hphp/runtime/vm/native-data.h"
#include "../../../mongodb.h"
#include "../../../utils.h"
#include "ObjectID.h"
namespace HPHP {
const StaticString s_MongoBsonObjectID_className("MongoDB\\BSON\\ObjectID");
Class* MongoDBBsonObjectIDData::s_class = nullptr;
const StaticString MongoDBBsonObjectIDData::s_className("MongoDBBsonObjectID");
IMPLEMENT_GET_CLASS(MongoDBBsonObjectIDData);
void HHVM_METHOD(MongoDBBsonObjectID, __construct, const Variant &objectId)
{
MongoDBBsonObjectIDData* data = Native::data<MongoDBBsonObjectIDData>(this_);
const String& str_objectId = objectId.isNull() ? null_string : objectId.toString();
if (!objectId.isNull()) {
if (bson_oid_is_valid(str_objectId.c_str(), str_objectId.length())) {
bson_oid_init_from_string(&data->m_oid, str_objectId.c_str());
} else {
throw MongoDriver::Utils::throwInvalidArgumentException("Invalid BSON ID provided");
}
} else {
bson_oid_init(&data->m_oid, NULL);
}
}
static String oidAsString(MongoDBBsonObjectIDData* data)
{
String s;
char *data_s;
s = String(24, ReserveString);
data_s = s.bufferSlice().data();
bson_oid_to_string(&data->m_oid, data_s);
s.setSize(24);
return s;
}
String HHVM_METHOD(MongoDBBsonObjectID, __toString)
{
MongoDBBsonObjectIDData* data = Native::data<MongoDBBsonObjectIDData>(this_);
return oidAsString(data);
}
const StaticString s_oid("oid");
Array HHVM_METHOD(MongoDBBsonObjectID, __debugInfo)
{
Array retval = Array::Create();
MongoDBBsonObjectIDData* data = Native::data<MongoDBBsonObjectIDData>(this_);
retval.set(s_oid, oidAsString(data));
return retval;
}
}
<commit_msg>Fixed HHVM-188: ObjectID only supports lower case hexadecimal letters<commit_after>/**
* Copyright 2014-2015 MongoDB, 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 "hphp/runtime/ext/extension.h"
#include "hphp/runtime/vm/native-data.h"
#include "hphp/runtime/ext/string/ext_string.h"
#include "../../../mongodb.h"
#include "../../../utils.h"
#include "ObjectID.h"
namespace HPHP {
const StaticString s_MongoBsonObjectID_className("MongoDB\\BSON\\ObjectID");
Class* MongoDBBsonObjectIDData::s_class = nullptr;
const StaticString MongoDBBsonObjectIDData::s_className("MongoDBBsonObjectID");
IMPLEMENT_GET_CLASS(MongoDBBsonObjectIDData);
void HHVM_METHOD(MongoDBBsonObjectID, __construct, const Variant &objectId)
{
MongoDBBsonObjectIDData* data = Native::data<MongoDBBsonObjectIDData>(this_);
const String& str_objectId = objectId.isNull() ? null_string : objectId.toString();
if (!objectId.isNull()) {
if (bson_oid_is_valid((HHVM_FN(strtolower)(str_objectId)).c_str(), str_objectId.length())) {
bson_oid_init_from_string(&data->m_oid, (HHVM_FN(strtolower)(str_objectId)).c_str());
} else {
throw MongoDriver::Utils::throwInvalidArgumentException("Invalid BSON ID provided");
}
} else {
bson_oid_init(&data->m_oid, NULL);
}
}
static String oidAsString(MongoDBBsonObjectIDData* data)
{
String s;
char *data_s;
s = String(24, ReserveString);
data_s = s.bufferSlice().data();
bson_oid_to_string(&data->m_oid, data_s);
s.setSize(24);
return s;
}
String HHVM_METHOD(MongoDBBsonObjectID, __toString)
{
MongoDBBsonObjectIDData* data = Native::data<MongoDBBsonObjectIDData>(this_);
return oidAsString(data);
}
const StaticString s_oid("oid");
Array HHVM_METHOD(MongoDBBsonObjectID, __debugInfo)
{
Array retval = Array::Create();
MongoDBBsonObjectIDData* data = Native::data<MongoDBBsonObjectIDData>(this_);
retval.set(s_oid, oidAsString(data));
return retval;
}
}
<|endoftext|>
|
<commit_before>#ifndef ITER_ACCUMULATE_H_
#define ITER_ACCUMULATE_H_
#include "internal/iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
#include <functional>
#include <type_traits>
#include <memory>
namespace iter {
namespace impl {
template <typename Container, typename AccumulateFunc>
class Accumulator;
}
template <typename Container, typename AccumulateFunc>
impl::Accumulator<Container, AccumulateFunc> accumulate(
Container&&, AccumulateFunc);
template <typename T, typename AccumulateFunc>
impl::Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate(
std::initializer_list<T>, AccumulateFunc);
}
template <typename Container, typename AccumulateFunc>
class iter::impl::Accumulator {
private:
Container container;
AccumulateFunc accumulate_func;
friend Accumulator iter::accumulate<Container, AccumulateFunc>(
Container&&, AccumulateFunc);
template <typename T, typename AF>
friend Accumulator<std::initializer_list<T>, AF> iter::accumulate(
std::initializer_list<T>, AF);
// AccumVal must be default constructible
using AccumVal =
typename std::remove_reference<typename std::result_of<AccumulateFunc(
iterator_deref<Container>, iterator_deref<Container>)>::type>::type;
Accumulator(Container&& in_container, AccumulateFunc in_accumulate_func)
: container(std::forward<Container>(in_container)),
accumulate_func(in_accumulate_func) {}
public:
class Iterator : public std::iterator<std::input_iterator_tag, AccumVal> {
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
AccumulateFunc* accumulate_func;
std::unique_ptr<AccumVal> acc_val;
public:
Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end,
AccumulateFunc in_accumulate_func)
: sub_iter{std::move(iter)},
sub_end{std::move(end)},
accumulate_func(&in_accumulate_func),
// only get first value if not an end iterator
acc_val{!(iter != end) ? nullptr : new AccumVal(*iter)} {}
Iterator(const Iterator& other)
: sub_iter{other.sub_iter},
sub_end{other.sub_end},
accumulate_func{other.accumulate_func},
acc_val{other.acc_val ? new AccumVal(*other.acc_val) : nullptr} {}
Iterator& operator=(const Iterator& other) {
if (this == &other) return *this;
this->sub_iter = other.sub_iter;
this->sub_end = other.sub_end;
this->accumulate_func = other.accumulate_func;
this->acc_val.reset(
other.acc_val ? new AccumVal(*other.acc_val) : nullptr);
return *this;
}
Iterator(Iterator&&) = default;
Iterator& operator=(Iterator&&) = default;
const AccumVal& operator*() const {
return *this->acc_val;
}
const AccumVal* operator->() const {
return this->acc_val.get();
}
Iterator& operator++() {
++this->sub_iter;
if (this->sub_iter != this->sub_end) {
*this->acc_val = (*accumulate_func)(*this->acc_val, *this->sub_iter);
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container),
this->accumulate_func};
}
Iterator end() {
return {std::end(this->container), std::end(this->container),
this->accumulate_func};
}
};
template <typename Container, typename AccumulateFunc>
iter::impl::Accumulator<Container, AccumulateFunc> iter::accumulate(
Container&& container, AccumulateFunc accumulate_func) {
return {std::forward<Container>(container), accumulate_func};
}
template <typename T, typename AccumulateFunc>
iter::impl::Accumulator<std::initializer_list<T>, AccumulateFunc>
iter::accumulate(std::initializer_list<T> il, AccumulateFunc accumulate_func) {
return {std::move(il), accumulate_func};
}
namespace iter {
template <typename Container>
auto accumulate(Container&& container) -> decltype(accumulate(
std::forward<Container>(container),
std::plus<typename std::
remove_reference<impl::iterator_deref<Container>>::type>{})) {
return accumulate(
std::forward<Container>(container),
std::plus<typename std::
remove_reference<impl::iterator_deref<Container>>::type>{});
}
template <typename T>
auto accumulate(std::initializer_list<T> il)
-> decltype(accumulate(std::move(il), std::plus<T>{})) {
return accumulate(std::move(il), std::plus<T>{});
}
}
#endif
<commit_msg>makes accumulate implementation class move-only<commit_after>#ifndef ITER_ACCUMULATE_H_
#define ITER_ACCUMULATE_H_
#include "internal/iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
#include <functional>
#include <type_traits>
#include <memory>
namespace iter {
namespace impl {
template <typename Container, typename AccumulateFunc>
class Accumulator;
}
template <typename Container, typename AccumulateFunc>
impl::Accumulator<Container, AccumulateFunc> accumulate(
Container&&, AccumulateFunc);
template <typename T, typename AccumulateFunc>
impl::Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate(
std::initializer_list<T>, AccumulateFunc);
}
template <typename Container, typename AccumulateFunc>
class iter::impl::Accumulator {
private:
Container container;
AccumulateFunc accumulate_func;
friend Accumulator iter::accumulate<Container, AccumulateFunc>(
Container&&, AccumulateFunc);
template <typename T, typename AF>
friend Accumulator<std::initializer_list<T>, AF> iter::accumulate(
std::initializer_list<T>, AF);
// AccumVal must be default constructible
using AccumVal =
typename std::remove_reference<typename std::result_of<AccumulateFunc(
iterator_deref<Container>, iterator_deref<Container>)>::type>::type;
Accumulator(Container&& in_container, AccumulateFunc in_accumulate_func)
: container(std::forward<Container>(in_container)),
accumulate_func(in_accumulate_func) {}
public:
Accumulator(Accumulator&&) = default;
class Iterator : public std::iterator<std::input_iterator_tag, AccumVal> {
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
AccumulateFunc* accumulate_func;
std::unique_ptr<AccumVal> acc_val;
public:
Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end,
AccumulateFunc in_accumulate_fun)
: sub_iter{std::move(iter)},
sub_end{std::move(end)},
accumulate_func(&in_accumulate_func),
// only get first value if not an end iterator
acc_val{!(iter != end) ? nullptr : new AccumVal(*iter)} {}
Iterator(const Iterator& other)
: sub_iter{other.sub_iter},
sub_end{other.sub_end},
accumulate_func{other.accumulate_func},
acc_val{other.acc_val ? new AccumVal(*other.acc_val) : nullptr} {}
Iterator& operator=(const Iterator& other) {
if (this == &other) return *this;
this->sub_iter = other.sub_iter;
this->sub_end = other.sub_end;
this->accumulate_func = other.accumulate_func;
this->acc_val.reset(
other.acc_val ? new AccumVal(*other.acc_val) : nullptr);
return *this;
}
Iterator(Iterator&&) = default;
Iterator& operator=(Iterator&&) = default;
const AccumVal& operator*() const {
return *this->acc_val;
}
const AccumVal* operator->() const {
return this->acc_val.get();
}
Iterator& operator++() {
++this->sub_iter;
if (this->sub_iter != this->sub_end) {
*this->acc_val = (*accumulate_func)(*this->acc_val, *this->sub_iter);
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container),
this->accumulate_func};
}
Iterator end() {
return {std::end(this->container), std::end(this->container),
this->accumulate_func};
}
};
template <typename Container, typename AccumulateFunc>
iter::impl::Accumulator<Container, AccumulateFunc> iter::accumulate(
Container&& container, AccumulateFunc accumulate_func) {
return {std::forward<Container>(container), accumulate_func};
}
template <typename T, typename AccumulateFunc>
iter::impl::Accumulator<std::initializer_list<T>, AccumulateFunc>
iter::accumulate(std::initializer_list<T> il, AccumulateFunc accumulate_func) {
return {std::move(il), accumulate_func};
}
namespace iter {
template <typename Container>
auto accumulate(Container&& container) -> decltype(accumulate(
std::forward<Container>(container),
std::plus<typename std::
remove_reference<impl::iterator_deref<Container>>::type>{})) {
return accumulate(
std::forward<Container>(container),
std::plus<typename std::
remove_reference<impl::iterator_deref<Container>>::type>{});
}
template <typename T>
auto accumulate(std::initializer_list<T> il)
-> decltype(accumulate(std::move(il), std::plus<T>{})) {
return accumulate(std::move(il), std::plus<T>{});
}
}
#endif
<|endoftext|>
|
<commit_before>/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <Onsang/Log.hpp>
#include <Onsang/System/Session.hpp>
#include <Hord/Cmd/Defs.hpp>
#include <Hord/Cmd/Unit.hpp>
#include <iomanip>
#include <Onsang/detail/gr_core.hpp>
namespace Onsang {
namespace System {
#define ONSANG_SCOPE_CLASS System::Session
#define ONSANG_SCOPE_FUNC notify_exception_impl
void
Session::notify_exception_impl(
Hord::Cmd::UnitBase const& /*command*/,
Hord::Cmd::type_info const& type_info,
std::exception_ptr eptr
) noexcept {
Log::acquire(Log::error)
<< "exception caught in " << type_info.name << ": \n"
;
Log::report_error_ptr(std::move(eptr));
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC notify_complete_impl
void
Session::notify_complete_impl(
Hord::Cmd::UnitBase const& command,
Hord::Cmd::type_info const& type_info
) noexcept {
// TODO: Dispatch to observers
Log::acquire(Log::debug)
<< "notify_complete: "
<< std::hex << type_info.id
<< ' ' << type_info.name
<< " ok? " << std::boolalpha << command.ok()
<< " message: \"" << command.get_message() << '\"'
<< '\n'
;
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC open
void
Session::open() {
get_datastore().open(m_auto_create);
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC close
void
Session::close() {
get_datastore().close();
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC process
void
Session::process() {
// TODO: Update views
}
#undef ONSANG_SCOPE_FUNC
#undef ONSANG_SCOPE_CLASS
} // namespace System
} // namespace Onsang
<commit_msg>System::Session: output tidy.<commit_after>/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <Onsang/Log.hpp>
#include <Onsang/System/Session.hpp>
#include <Hord/Cmd/Defs.hpp>
#include <Hord/Cmd/Unit.hpp>
#include <iomanip>
#include <Onsang/detail/gr_core.hpp>
namespace Onsang {
namespace System {
#define ONSANG_SCOPE_CLASS System::Session
#define ONSANG_SCOPE_FUNC notify_exception_impl
void
Session::notify_exception_impl(
Hord::Cmd::UnitBase const& /*command*/,
Hord::Cmd::type_info const& type_info,
std::exception_ptr eptr
) noexcept {
Log::acquire(Log::error)
<< "exception caught in " << type_info.name << ": \n"
;
Log::report_error_ptr(std::move(eptr));
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC notify_complete_impl
void
Session::notify_complete_impl(
Hord::Cmd::UnitBase const& command,
Hord::Cmd::type_info const& type_info
) noexcept {
// TODO: Dispatch to observers
Log::acquire(Log::debug)
<< "notify_complete: "
<< std::hex << type_info.id
<< ' ' << type_info.name
<< ", ok: " << (command.ok() ? "yes" : "no")
<< ", message: \"" << command.get_message() << '\"'
<< '\n'
;
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC open
void
Session::open() {
get_datastore().open(m_auto_create);
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC close
void
Session::close() {
get_datastore().close();
}
#undef ONSANG_SCOPE_FUNC
#define ONSANG_SCOPE_FUNC process
void
Session::process() {
// TODO: Update views
}
#undef ONSANG_SCOPE_FUNC
#undef ONSANG_SCOPE_CLASS
} // namespace System
} // namespace Onsang
<|endoftext|>
|
<commit_before>#include <iostream>
class MyClass
{
int m_iID = -1;
public:
MyClass(int iID) : m_iID(iID)
{
std::cout << "Built and instance with ID: " << m_iID << std::endl;
}
MyClass() : MyClass(42)
{
std::cout << "Delegated construction" << m_iID << std::endl;
}
};
int main(int argc, char* argv[])
{
MyClass myInstance;
}
<commit_msg>Added member and destructor<commit_after>#include <iostream>
class MyClass
{
private:
int m_iID = -1;
public:
MyClass(int iID) : m_iID(iID)
{
std::cout << "Built and instance with ID: " << m_iID << std::endl;
}
MyClass() : MyClass(42)
{
std::cout << "Delegated construction" << m_iID << std::endl;
}
~MyClass()
{
}
};
int main(int argc, char* argv[])
{
MyClass myInstance;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $
Version: $Revision: 17179 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkSurfaceToSurfaceFilter.h"
#include "mitkSurface.h"
mitk::SurfaceToSurfaceFilter::SurfaceToSurfaceFilter()
: SurfaceSource()
{
}
mitk::SurfaceToSurfaceFilter::~SurfaceToSurfaceFilter()
{
}
void mitk::SurfaceToSurfaceFilter::SetInput( const mitk::Surface* surface )
{
this->SetInput( 0, const_cast<mitk::Surface*>( surface ) );
}
void mitk::SurfaceToSurfaceFilter::SetInput( unsigned int idx, const mitk::Surface* surface )
{
if ( this->GetInput(idx) != surface )
{
this->SetNthInput( idx, const_cast<mitk::Surface*>( surface ) );
this->CreateOutputsForAllInputs(idx);
this->Modified();
}
}
const mitk::Surface* mitk::SurfaceToSurfaceFilter::GetInput()
{
if (this->GetNumberOfInputs() < 1)
return NULL;
return static_cast<const mitk::Surface*>(this->ProcessObject::GetInput(0));
}
const mitk::Surface* mitk::SurfaceToSurfaceFilter::GetInput( unsigned int idx)
{
if (this->GetNumberOfInputs() < 1)
return NULL;
return static_cast<const mitk::Surface*>(this->ProcessObject::GetInput(idx));
}
void mitk::SurfaceToSurfaceFilter::CreateOutputsForAllInputs(unsigned int /*idx*/)
{
this->SetNumberOfOutputs( this->GetNumberOfInputs() );
for (unsigned int idx = 0; idx < this->GetNumberOfOutputs(); ++idx)
if (this->GetOutput(idx) == NULL)
{
DataObjectPointer newOutput = this->MakeOutput(idx);
this->SetNthOutput(idx, newOutput);
}
this->Modified();
}
void mitk::SurfaceToSurfaceFilter::RemoveInputs(mitk::Surface* input)
{
this->RemoveInput(input);
}<commit_msg>FIX (#3189): now grafting each input into its corresponding output -> output-surfaces are initialized correctly<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $
Version: $Revision: 17179 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkSurfaceToSurfaceFilter.h"
#include "mitkSurface.h"
mitk::SurfaceToSurfaceFilter::SurfaceToSurfaceFilter()
: SurfaceSource()
{
}
mitk::SurfaceToSurfaceFilter::~SurfaceToSurfaceFilter()
{
}
void mitk::SurfaceToSurfaceFilter::SetInput( const mitk::Surface* surface )
{
this->SetInput( 0, const_cast<mitk::Surface*>( surface ) );
}
void mitk::SurfaceToSurfaceFilter::SetInput( unsigned int idx, const mitk::Surface* surface )
{
if ( this->GetInput(idx) != surface )
{
this->SetNthInput( idx, const_cast<mitk::Surface*>( surface ) );
this->CreateOutputsForAllInputs(idx);
this->Modified();
}
}
const mitk::Surface* mitk::SurfaceToSurfaceFilter::GetInput()
{
if (this->GetNumberOfInputs() < 1)
return NULL;
return static_cast<const mitk::Surface*>(this->ProcessObject::GetInput(0));
}
const mitk::Surface* mitk::SurfaceToSurfaceFilter::GetInput( unsigned int idx)
{
if (this->GetNumberOfInputs() < 1)
return NULL;
return static_cast<const mitk::Surface*>(this->ProcessObject::GetInput(idx));
}
void mitk::SurfaceToSurfaceFilter::CreateOutputsForAllInputs(unsigned int /*idx*/)
{
this->SetNumberOfOutputs( this->GetNumberOfInputs() );
for (unsigned int idx = 0; idx < this->GetNumberOfOutputs(); ++idx)
{
if (this->GetOutput(idx) == NULL)
{
DataObjectPointer newOutput = this->MakeOutput(idx);
this->SetNthOutput(idx, newOutput);
}
this->GetOutput( idx )->Graft( this->GetInput( idx) );
}
this->Modified();
}
void mitk::SurfaceToSurfaceFilter::RemoveInputs(mitk::Surface* input)
{
this->RemoveInput(input);
}<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkLevelWindowManager.h"
#include <itkCommand.h>
#include "mitkDataStorage.h"
#include "mitkNodePredicateBase.h"
#include "mitkNodePredicateProperty.h"
#include "mitkNodePredicateDataType.h"
#include "mitkNodePredicateAnd.h"
#include "mitkNodePredicateOr.h"
#include "mitkNodePredicateNot.h"
#include "mitkProperties.h"
#include "mitkMessage.h"
mitk::LevelWindowManager::LevelWindowManager()
: m_DataStorage(NULL)
, m_LevelWindowProperty(NULL)
, m_AutoTopMost(true)
, m_IsObserverTagSet(false)
, m_CurrentImage(NULL)
, m_IsPropertyModifiedTagSet(false)
{
}
mitk::LevelWindowManager::~LevelWindowManager()
{
if (m_DataStorage.IsNotNull())
{
m_DataStorage->AddNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
m_DataStorage->RemoveNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
m_DataStorage = NULL;
}
if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
//clear both observer maps
this->ClearPropObserverLists();
}
void mitk::LevelWindowManager::SetDataStorage( mitk::DataStorage* ds )
{
if (ds == NULL) return;
/* remove listeners of old DataStorage */
if (m_DataStorage.IsNotNull())
{
m_DataStorage->AddNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
m_DataStorage->RemoveNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
}
/* register listener for new DataStorage */
m_DataStorage = ds; // register
m_DataStorage->AddNodeEvent.AddListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
m_DataStorage->RemoveNodeEvent.AddListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
this->DataStorageAddedNode(); // update us with new DataStorage
}
void mitk::LevelWindowManager::OnPropertyModified(const itk::EventObject& )
{
Modified();
}
void mitk::LevelWindowManager::SetAutoTopMostImage(bool autoTopMost, const mitk::DataNode* removedNode)
{
m_AutoTopMost = autoTopMost;
if (m_AutoTopMost == false)
return;
if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
/* search topmost image */
if (m_DataStorage.IsNull())
{
itkExceptionMacro("DataStorage not set");
}
int maxLayer = itk::NumericTraits<int>::min();
m_LevelWindowProperty = NULL;
mitk::DataNode::Pointer topLevelNode;
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin(); it != all->End(); ++it)
{
mitk::DataNode::Pointer node = it->Value();
if (node.IsNull() || (removedNode != NULL && node == removedNode))
continue;
node->SetBoolProperty( "imageForLevelWindow", false );
if (node->IsVisible(NULL) == false)
continue;
int layer = 0;
node->GetIntProperty("layer", layer);
if ( layer < maxLayer )
continue;
mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
if (levelWindowProperty.IsNull())
continue;
m_LevelWindowProperty = levelWindowProperty;
m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
topLevelNode = node;
maxLayer = layer;
}
if (topLevelNode.IsNotNull())
{
topLevelNode->SetBoolProperty( "imageForLevelWindow", true );
}
this->SetLevelWindowProperty( m_LevelWindowProperty );
if ( m_LevelWindowProperty.IsNull() )
{
Modified();
}
// else SetLevelWindowProperty will call Modified();
}
// sets an specific LevelWindowProperty, all changes will affect the image belonging to this property.
void mitk::LevelWindowManager::SetLevelWindowProperty(LevelWindowProperty::Pointer levelWindowProperty)
{
if (levelWindowProperty.IsNull())
return;
if (m_IsPropertyModifiedTagSet) // remove listener for old property
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
m_LevelWindowProperty = levelWindowProperty;
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New(); // register listener for new property
command->SetCallbackFunction(this, &LevelWindowManager::OnPropertyModified);
m_PropertyModifiedTag = m_LevelWindowProperty->AddObserver( itk::ModifiedEvent(), command );
m_IsPropertyModifiedTagSet = true;
/* search image than belongs to the property */
mitk::NodePredicateProperty::Pointer p = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
mitk::DataNode* n = m_DataStorage->GetNode(p);
if (n == NULL)
{
mitkThrow() << "No Image in DataStorage that belongs to LevelWindow property" << m_LevelWindowProperty;
}
m_CurrentImage = dynamic_cast<mitk::Image*>(n->GetData());
n->SetBoolProperty( "imageForLevelWindow", true );
this->Modified();
}
// returns the current mitkLevelWindowProperty object from the image that is affected by changes
mitk::LevelWindowProperty::Pointer mitk::LevelWindowManager::GetLevelWindowProperty()
{
return m_LevelWindowProperty;
}
// returns Level/Window values for the current image
const mitk::LevelWindow& mitk::LevelWindowManager::GetLevelWindow()
{
if (m_LevelWindowProperty.IsNotNull())
{
return m_LevelWindowProperty->GetLevelWindow();
}
else
{
itkExceptionMacro("No LevelWindow available!");
}
}
// sets new Level/Window values and informs all listeners about changes
void mitk::LevelWindowManager::SetLevelWindow(const mitk::LevelWindow& levelWindow)
{
if (m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->SetLevelWindow(levelWindow);
}
this->Modified();
}
void mitk::LevelWindowManager::DataStorageAddedNode( const mitk::DataNode* )
{
//update observers with new data storage
UpdateObservers();
//check if everything is still ok
if ((m_PropObserverToNode.size() != m_PropObserverToNode2.size()) || (m_PropObserverToNode2.size() != this->GetRelevantNodes()->size()))
{mitkThrow() << "Wrong number of observers in Level Window Manager!";}
}
void mitk::LevelWindowManager::DataStorageRemovedNode( const mitk::DataNode* removedNode )
{
//remember node which will be removed
m_NodeMarkedToDelete = removedNode;
//update observers
UpdateObservers();
/* search image than belongs to the property */
if (m_LevelWindowProperty.IsNull())
{
SetAutoTopMostImage(true, removedNode);
}
else
{
mitk::NodePredicateProperty::Pointer p2 = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
mitk::DataNode* n = m_DataStorage->GetNode(p2);
if (n == NULL || m_AutoTopMost) // if node was deleted, change our behaviour to AutoTopMost, if AutoTopMost is true change level window to topmost node
{
SetAutoTopMostImage(true, removedNode);
}
}
//reset variable
m_NodeMarkedToDelete = NULL;
//check if everything is still ok
if ((m_PropObserverToNode.size() != m_PropObserverToNode2.size()) || (m_PropObserverToNode2.size() != (this->GetRelevantNodes()->size()-1)))
{mitkThrow() << "Wrong number of observers in Level Window Manager!";}
}
void mitk::LevelWindowManager::UpdateObservers()
{
this->ClearPropObserverLists(); //remove old observers
CreatePropObserverLists(); //create new observer lists
}
int mitk::LevelWindowManager::GetNumberOfObservers()
{
return m_PropObserverToNode.size();
}
mitk::DataStorage* mitk::LevelWindowManager::GetDataStorage()
{
return m_DataStorage.GetPointer();
}
// true if changes on slider or line-edits will affect always the topmost layer image
bool mitk::LevelWindowManager::isAutoTopMost()
{
return m_AutoTopMost;
}
void mitk::LevelWindowManager::Update(const itk::EventObject&) // visible property of a image has changed
{
if (m_AutoTopMost)
{
SetAutoTopMostImage(true);
return;
}
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
mitk::DataNode::Pointer node = it->Value();
if (node.IsNull())
continue;
node->SetBoolProperty( "imageForLevelWindow", false );
if (node->IsVisible(NULL) == false)
continue;
mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
if (levelWindowProperty.IsNull())
continue;
m_LevelWindowProperty = levelWindowProperty;
m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
node->SetBoolProperty( "imageForLevelWindow", true );
if (m_LevelWindowProperty.IsNull() && m_LevelWindowProperty.GetPointer() == levelWindowProperty) // we found our m_LevelWindowProperty
{
return;
}
}
Modified();
}
mitk::DataStorage::SetOfObjects::ConstPointer mitk::LevelWindowManager::GetRelevantNodes()
{
if (m_DataStorage.IsNull())
return mitk::DataStorage::SetOfObjects::ConstPointer(mitk::DataStorage::SetOfObjects::New()); // return empty set
mitk::BoolProperty::Pointer trueProp = mitk::BoolProperty::New(true);
mitk::NodePredicateProperty::Pointer notBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(false));
mitk::NodePredicateProperty::Pointer hasLevelWindow = mitk::NodePredicateProperty::New("levelwindow", NULL);
mitk::NodePredicateDataType::Pointer isImage = mitk::NodePredicateDataType::New("Image");
mitk::NodePredicateDataType::Pointer isDImage = mitk::NodePredicateDataType::New("DiffusionImage");
mitk::NodePredicateDataType::Pointer isTImage = mitk::NodePredicateDataType::New("TensorImage");
mitk::NodePredicateDataType::Pointer isQImage = mitk::NodePredicateDataType::New("QBallImage");
mitk::NodePredicateOr::Pointer predicateTypes = mitk::NodePredicateOr::New();
predicateTypes->AddPredicate(isImage);
predicateTypes->AddPredicate(isDImage);
predicateTypes->AddPredicate(isTImage);
predicateTypes->AddPredicate(isQImage);
mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New();
predicate->AddPredicate(notBinary);
predicate->AddPredicate(hasLevelWindow);
predicate->AddPredicate(predicateTypes);
mitk::DataStorage::SetOfObjects::ConstPointer relevantNodes = m_DataStorage->GetSubset( predicate );
return relevantNodes;
}
mitk::Image* mitk::LevelWindowManager::GetCurrentImage()
{
return m_CurrentImage;
}
void mitk::LevelWindowManager::ClearPropObserverLists()
{
for( ObserverToPropertyMap::iterator iter = m_PropObserverToNode.begin();
iter != m_PropObserverToNode.end();
++iter )
{
(*iter).second->RemoveObserver((*iter).first.first);
(*iter).second = 0;
}
m_PropObserverToNode.clear();
for( ObserverToPropertyMap::iterator iter = m_PropObserverToNode2.begin();
iter != m_PropObserverToNode2.end();
++iter )
{
(*iter).second->RemoveObserver((*iter).first.first);
(*iter).second = 0;
}
m_PropObserverToNode2.clear();
}
void mitk::LevelWindowManager::CreatePropObserverLists()
{
if (m_DataStorage.IsNull()) //check if data storage is set
{itkExceptionMacro("DataStorage not set");}
/* add observers for all relevant nodes */
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
if ((it->Value().IsNull()) || (it->Value() == m_NodeMarkedToDelete))
{continue;}
/* register listener for changes in visible property */
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New();
command->SetCallbackFunction(this, &LevelWindowManager::Update);
unsigned long idx = it->Value()->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command );
m_PropObserverToNode[PropDataPair(idx, it->Value())] = it->Value()->GetProperty("visible");
}
/* add observers for all layer properties*/
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
if ((it->Value().IsNull()) || (it->Value() == m_NodeMarkedToDelete))
{continue;}
/* register listener for changes in layer property */
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command2 = itk::ReceptorMemberCommand<LevelWindowManager>::New();
command2->SetCallbackFunction(this, &LevelWindowManager::Update);
unsigned long idx = it->Value()->GetProperty("layer")->AddObserver( itk::ModifiedEvent(), command2 );
m_PropObserverToNode2[PropDataPair(idx, it->Value())] = it->Value()->GetProperty("layer");
}
}
<commit_msg>added a check if the removed node is relevant<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkLevelWindowManager.h"
#include <itkCommand.h>
#include "mitkDataStorage.h"
#include "mitkNodePredicateBase.h"
#include "mitkNodePredicateProperty.h"
#include "mitkNodePredicateDataType.h"
#include "mitkNodePredicateAnd.h"
#include "mitkNodePredicateOr.h"
#include "mitkNodePredicateNot.h"
#include "mitkProperties.h"
#include "mitkMessage.h"
mitk::LevelWindowManager::LevelWindowManager()
: m_DataStorage(NULL)
, m_LevelWindowProperty(NULL)
, m_AutoTopMost(true)
, m_IsObserverTagSet(false)
, m_CurrentImage(NULL)
, m_IsPropertyModifiedTagSet(false)
{
}
mitk::LevelWindowManager::~LevelWindowManager()
{
if (m_DataStorage.IsNotNull())
{
m_DataStorage->AddNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
m_DataStorage->RemoveNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
m_DataStorage = NULL;
}
if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
//clear both observer maps
this->ClearPropObserverLists();
}
void mitk::LevelWindowManager::SetDataStorage( mitk::DataStorage* ds )
{
if (ds == NULL) return;
/* remove listeners of old DataStorage */
if (m_DataStorage.IsNotNull())
{
m_DataStorage->AddNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
m_DataStorage->RemoveNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
}
/* register listener for new DataStorage */
m_DataStorage = ds; // register
m_DataStorage->AddNodeEvent.AddListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
m_DataStorage->RemoveNodeEvent.AddListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
this->DataStorageAddedNode(); // update us with new DataStorage
}
void mitk::LevelWindowManager::OnPropertyModified(const itk::EventObject& )
{
Modified();
}
void mitk::LevelWindowManager::SetAutoTopMostImage(bool autoTopMost, const mitk::DataNode* removedNode)
{
m_AutoTopMost = autoTopMost;
if (m_AutoTopMost == false)
return;
if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
/* search topmost image */
if (m_DataStorage.IsNull())
{
itkExceptionMacro("DataStorage not set");
}
int maxLayer = itk::NumericTraits<int>::min();
m_LevelWindowProperty = NULL;
mitk::DataNode::Pointer topLevelNode;
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin(); it != all->End(); ++it)
{
mitk::DataNode::Pointer node = it->Value();
if (node.IsNull() || (removedNode != NULL && node == removedNode))
continue;
node->SetBoolProperty( "imageForLevelWindow", false );
if (node->IsVisible(NULL) == false)
continue;
int layer = 0;
node->GetIntProperty("layer", layer);
if ( layer < maxLayer )
continue;
mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
if (levelWindowProperty.IsNull())
continue;
m_LevelWindowProperty = levelWindowProperty;
m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
topLevelNode = node;
maxLayer = layer;
}
if (topLevelNode.IsNotNull())
{
topLevelNode->SetBoolProperty( "imageForLevelWindow", true );
}
this->SetLevelWindowProperty( m_LevelWindowProperty );
if ( m_LevelWindowProperty.IsNull() )
{
Modified();
}
// else SetLevelWindowProperty will call Modified();
}
// sets an specific LevelWindowProperty, all changes will affect the image belonging to this property.
void mitk::LevelWindowManager::SetLevelWindowProperty(LevelWindowProperty::Pointer levelWindowProperty)
{
if (levelWindowProperty.IsNull())
return;
if (m_IsPropertyModifiedTagSet) // remove listener for old property
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
m_LevelWindowProperty = levelWindowProperty;
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New(); // register listener for new property
command->SetCallbackFunction(this, &LevelWindowManager::OnPropertyModified);
m_PropertyModifiedTag = m_LevelWindowProperty->AddObserver( itk::ModifiedEvent(), command );
m_IsPropertyModifiedTagSet = true;
/* search image than belongs to the property */
mitk::NodePredicateProperty::Pointer p = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
mitk::DataNode* n = m_DataStorage->GetNode(p);
if (n == NULL)
{
mitkThrow() << "No Image in DataStorage that belongs to LevelWindow property" << m_LevelWindowProperty;
}
m_CurrentImage = dynamic_cast<mitk::Image*>(n->GetData());
n->SetBoolProperty( "imageForLevelWindow", true );
this->Modified();
}
// returns the current mitkLevelWindowProperty object from the image that is affected by changes
mitk::LevelWindowProperty::Pointer mitk::LevelWindowManager::GetLevelWindowProperty()
{
return m_LevelWindowProperty;
}
// returns Level/Window values for the current image
const mitk::LevelWindow& mitk::LevelWindowManager::GetLevelWindow()
{
if (m_LevelWindowProperty.IsNotNull())
{
return m_LevelWindowProperty->GetLevelWindow();
}
else
{
itkExceptionMacro("No LevelWindow available!");
}
}
// sets new Level/Window values and informs all listeners about changes
void mitk::LevelWindowManager::SetLevelWindow(const mitk::LevelWindow& levelWindow)
{
if (m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->SetLevelWindow(levelWindow);
}
this->Modified();
}
void mitk::LevelWindowManager::DataStorageAddedNode( const mitk::DataNode* )
{
//update observers with new data storage
UpdateObservers();
//check if everything is still ok
if ((m_PropObserverToNode.size() != m_PropObserverToNode2.size()) || (m_PropObserverToNode2.size() != this->GetRelevantNodes()->size()))
{mitkThrow() << "Wrong number of observers in Level Window Manager!";}
}
void mitk::LevelWindowManager::DataStorageRemovedNode( const mitk::DataNode* removedNode )
{
//first: check if deleted node is part of relevant nodes. If not, abort method because there is no need change anything.
if ((this->GetRelevantNodes()->size() == 0)) return;
for (mitk::DataStorage::SetOfObjects::ConstIterator it = this->GetRelevantNodes()->Begin();
it != this->GetRelevantNodes()->End();
++it)
{if (it->Value() == removedNode) {return;}}
//remember node which will be removed
m_NodeMarkedToDelete = removedNode;
//update observers
UpdateObservers();
/* search image than belongs to the property */
if (m_LevelWindowProperty.IsNull())
{
SetAutoTopMostImage(true, removedNode);
}
else
{
mitk::NodePredicateProperty::Pointer p2 = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
mitk::DataNode* n = m_DataStorage->GetNode(p2);
if (n == NULL || m_AutoTopMost) // if node was deleted, change our behaviour to AutoTopMost, if AutoTopMost is true change level window to topmost node
{
SetAutoTopMostImage(true, removedNode);
}
}
//reset variable
m_NodeMarkedToDelete = NULL;
//check if everything is still ok
MITK_INFO << "Size Observers 1: " << m_PropObserverToNode.size();
MITK_INFO << "Size Observers 2: " << m_PropObserverToNode2.size();
MITK_INFO << "Size Observers Relevant Nodes: " << GetRelevantNodes()->size();
if ((m_PropObserverToNode.size() != m_PropObserverToNode2.size()) || (m_PropObserverToNode2.size() != (this->GetRelevantNodes()->size()-1)))
{
MITK_ERROR << "Wrong number of observers in Level Window Manager!";
mitkThrow() << "Wrong number of observers in Level Window Manager!";
}
}
void mitk::LevelWindowManager::UpdateObservers()
{
this->ClearPropObserverLists(); //remove old observers
CreatePropObserverLists(); //create new observer lists
}
int mitk::LevelWindowManager::GetNumberOfObservers()
{
return m_PropObserverToNode.size();
}
mitk::DataStorage* mitk::LevelWindowManager::GetDataStorage()
{
return m_DataStorage.GetPointer();
}
// true if changes on slider or line-edits will affect always the topmost layer image
bool mitk::LevelWindowManager::isAutoTopMost()
{
return m_AutoTopMost;
}
void mitk::LevelWindowManager::Update(const itk::EventObject&) // visible property of a image has changed
{
if (m_AutoTopMost)
{
SetAutoTopMostImage(true);
return;
}
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
mitk::DataNode::Pointer node = it->Value();
if (node.IsNull())
continue;
node->SetBoolProperty( "imageForLevelWindow", false );
if (node->IsVisible(NULL) == false)
continue;
mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
if (levelWindowProperty.IsNull())
continue;
m_LevelWindowProperty = levelWindowProperty;
m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
node->SetBoolProperty( "imageForLevelWindow", true );
if (m_LevelWindowProperty.IsNull() && m_LevelWindowProperty.GetPointer() == levelWindowProperty) // we found our m_LevelWindowProperty
{
return;
}
}
Modified();
}
mitk::DataStorage::SetOfObjects::ConstPointer mitk::LevelWindowManager::GetRelevantNodes()
{
if (m_DataStorage.IsNull())
return mitk::DataStorage::SetOfObjects::ConstPointer(mitk::DataStorage::SetOfObjects::New()); // return empty set
mitk::BoolProperty::Pointer trueProp = mitk::BoolProperty::New(true);
mitk::NodePredicateProperty::Pointer notBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(false));
mitk::NodePredicateProperty::Pointer hasLevelWindow = mitk::NodePredicateProperty::New("levelwindow", NULL);
mitk::NodePredicateDataType::Pointer isImage = mitk::NodePredicateDataType::New("Image");
mitk::NodePredicateDataType::Pointer isDImage = mitk::NodePredicateDataType::New("DiffusionImage");
mitk::NodePredicateDataType::Pointer isTImage = mitk::NodePredicateDataType::New("TensorImage");
mitk::NodePredicateDataType::Pointer isQImage = mitk::NodePredicateDataType::New("QBallImage");
mitk::NodePredicateOr::Pointer predicateTypes = mitk::NodePredicateOr::New();
predicateTypes->AddPredicate(isImage);
predicateTypes->AddPredicate(isDImage);
predicateTypes->AddPredicate(isTImage);
predicateTypes->AddPredicate(isQImage);
mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New();
predicate->AddPredicate(notBinary);
predicate->AddPredicate(hasLevelWindow);
predicate->AddPredicate(predicateTypes);
mitk::DataStorage::SetOfObjects::ConstPointer relevantNodes = m_DataStorage->GetSubset( predicate );
return relevantNodes;
}
mitk::Image* mitk::LevelWindowManager::GetCurrentImage()
{
return m_CurrentImage;
}
void mitk::LevelWindowManager::ClearPropObserverLists()
{
for( ObserverToPropertyMap::iterator iter = m_PropObserverToNode.begin();
iter != m_PropObserverToNode.end();
++iter )
{
(*iter).second->RemoveObserver((*iter).first.first);
(*iter).second = 0;
}
m_PropObserverToNode.clear();
for( ObserverToPropertyMap::iterator iter = m_PropObserverToNode2.begin();
iter != m_PropObserverToNode2.end();
++iter )
{
(*iter).second->RemoveObserver((*iter).first.first);
(*iter).second = 0;
}
m_PropObserverToNode2.clear();
}
void mitk::LevelWindowManager::CreatePropObserverLists()
{
if (m_DataStorage.IsNull()) //check if data storage is set
{itkExceptionMacro("DataStorage not set");}
/* add observers for all relevant nodes */
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
if ((it->Value().IsNull()) || (it->Value() == m_NodeMarkedToDelete))
{continue;}
/* register listener for changes in visible property */
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New();
command->SetCallbackFunction(this, &LevelWindowManager::Update);
unsigned long idx = it->Value()->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command );
m_PropObserverToNode[PropDataPair(idx, it->Value())] = it->Value()->GetProperty("visible");
}
/* add observers for all layer properties*/
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
if ((it->Value().IsNull()) || (it->Value() == m_NodeMarkedToDelete))
{continue;}
/* register listener for changes in layer property */
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command2 = itk::ReceptorMemberCommand<LevelWindowManager>::New();
command2->SetCallbackFunction(this, &LevelWindowManager::Update);
unsigned long idx = it->Value()->GetProperty("layer")->AddObserver( itk::ModifiedEvent(), command2 );
m_PropObserverToNode2[PropDataPair(idx, it->Value())] = it->Value()->GetProperty("layer");
}
}
<|endoftext|>
|
<commit_before>/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015 OSRE ( Open Source Render Engine ) by Kim Kulling
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------------------------*/
#include <osre/Scene/GeometryBuilder.h>
#include <GL/glew.h>
#include <GL/gl.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <vector>
namespace OSRE {
namespace Scene {
using namespace ::OSRE::RenderBackend;
const String VsSrc =
"#version 400 core\n"
"\n"
"layout(location = 0) in vec3 position; // object space vertex position\n"
"layout(location = 1) in vec3 normal; // object space vertex normal\n"
"layout(location = 2) in vec3 color0; // per-vertex colour\n"
"\n"
"// output from the vertex shader\n"
"smooth out vec4 vSmoothColor; //smooth colour to fragment shader\n"
"\n"
"// uniform\n"
"uniform mat4 MVP; //combined modelview projection matrix\n"
"\n"
"void main()\n"
"{\n"
" //assign the per-vertex color to vSmoothColor varying\n"
" vSmoothColor = vec4(color0,1);\n"
"\n"
" //get the clip space position by multiplying the combined MVP matrix with the object space\n"
" //vertex position\n"
" gl_Position = MVP*vec4(position,1);\n"
"}\n";
const String FsSrc =
"#version 400 core\n"
"\n"
"layout(location=0) out vec4 vFragColor; //fragment shader output\n"
"\n"
"//input form the vertex shader\n"
"smooth in vec4 vSmoothColor; //interpolated colour to fragment shader\n"
"\n"
"void main()\n"
"{\n"
" //set the interpolated color as the shader output\n"
" vFragColor = vSmoothColor;\n"
"}\n";
static const String TextVsSrc =
"layout(location = 0) in vec3 position; // object space vertex position\n"
"layout(location = 1) in vec3 normal; // object space vertex normal\n"
"layout(location = 2) in vec2 texcoord0; // texture coordinate\n"
"out vec2 vUV;\n"
"\n"
"void main() {\n"
" vec3 vertexPosition_homoneneousspace = position;\n"
" gl_Position = vec4(position, 1 );\n"
" // UV of the vertex. No special space for this one.\n"
" UV = texcoord0;\n"
"};\n";
static const String TextFsSrc =
"in vec2 vUV;\n"
"// Output data\n"
"out vec4 vFragColor;\n"
"uniform sampler2D tex0;\n"
"void main() {\n"
" vFragColor = texture( tex0, vUV );\n"
"};\n";
//-------------------------------------------------------------------------------------------------
GeometryBuilder::GeometryBuilder() {
// empty
}
//-------------------------------------------------------------------------------------------------
GeometryBuilder::~GeometryBuilder() {
// empty
}
//-------------------------------------------------------------------------------------------------
RenderBackend::Geometry *GeometryBuilder::createEmptyGeometry( RenderBackend::VertexType type ) {
Geometry *geo = new Geometry;
geo->m_vertextype = type;
geo->m_indextype = UnsignedShort;
return geo;
}
//-------------------------------------------------------------------------------------------------
RenderBackend::Geometry *GeometryBuilder::createTriangle() {
Geometry *geo = new Geometry;
geo->m_vertextype = ColorVertex;
geo->m_indextype = UnsignedShort;
// setup triangle vertices
static const ui32 NumVert = 3;
ColorVert vertices[ NumVert ];
vertices[ 0 ].color = glm::vec3( 1, 0, 0 );
vertices[ 1 ].color = glm::vec3( 0, 1, 0 );
vertices[ 2 ].color = glm::vec3( 0, 0, 1 );
vertices[ 0 ].position = glm::vec3( -1, -1, 0 );
vertices[ 1 ].position = glm::vec3( 0, 1, 0 );
vertices[ 2 ].position = glm::vec3( 1, -1, 0 );
ui32 size( sizeof( ColorVert ) * NumVert );
geo->m_vb = BufferData::alloc( VertexBuffer, size, ReadOnly );
::memcpy( geo->m_vb->m_pData, vertices, size );
// setup triangle indices
static const ui32 NumIndices = 3;
GLushort indices[ NumIndices ];
indices[ 0 ] = 0;
indices[ 1 ] = 1;
indices[ 2 ] = 2;
size = sizeof( GLushort ) * NumIndices;
geo->m_ib = BufferData::alloc( IndexBuffer, size, ReadOnly );
::memcpy( geo->m_ib->m_pData, indices, size );
// setup primitives
geo->m_numPrimGroups = 1;
geo->m_pPrimGroups = new PrimitiveGroup[ geo->m_numPrimGroups ];
geo->m_pPrimGroups[ 0 ].m_indexType = UnsignedShort;
geo->m_pPrimGroups[ 0 ].m_numPrimitives = 3 * geo->m_numPrimGroups;
geo->m_pPrimGroups[ 0 ].m_primitive = TriangleList;
geo->m_pPrimGroups[ 0 ].m_startIndex = 0;
// setup material
geo->m_material = new Material;
geo->m_material->m_numTextures = 0;
geo->m_material->m_type = ShaderMaterial;
geo->m_material->m_pShader = new Shader;
geo->m_material->m_pShader->m_src[ SH_VertexShaderType ] = VsSrc;
geo->m_material->m_pShader->m_src[ SH_FragmentShaderType ] = FsSrc;
// setup shader attributes and variables
if( nullptr != geo->m_material->m_pShader ) {
ui32 numAttribs( ColorVert::getNumAttributes() );
const String *attribs( ColorVert::getAttributes() );
geo->m_material->m_pShader->m_attributes.add(attribs, numAttribs);
geo->m_material->m_pShader->m_parameters.add( "MVP" );
}
return geo;
}
//-------------------------------------------------------------------------------------------------
RenderBackend::Geometry *GeometryBuilder::createBox( f32 w, f32 h, f32 d ) {
Geometry *pGeometry = new Geometry;
pGeometry->m_vertextype = ColorVertex;
pGeometry->m_indextype = UnsignedShort;
static const ui32 NumVert = 8;
ColorVert vertices[ NumVert ];
f32 x(0.0f), y(0.0f), z( 0.0f );
vertices[ 0 ].position = glm::vec3( x, y, z );
vertices[ 1 ].position = glm::vec3( x + w, y, z );
vertices[ 2 ].position = glm::vec3( x + w, y + h, z );
vertices[ 3 ].position = glm::vec3( x, y + h, z );
vertices[ 4 ].position = glm::vec3( x, y, z + d );
vertices[ 5 ].position = glm::vec3( x + w, y, z + d );
vertices[ 6 ].position = glm::vec3( x + w, y + h, z + d );
vertices[ 7 ].position = glm::vec3( x, y + h, z + d );
ui32 size( sizeof( ColorVert ) * NumVert );
pGeometry->m_vb = BufferData::alloc( VertexBuffer, size, ReadOnly );
::memcpy( pGeometry->m_vb->m_pData, vertices, size );
static const ui32 NumIndices = 36;
GLushort indices[ NumIndices ];
indices[ 0 ] = 0;
indices[ 1 ] = 1;
indices[ 2 ] = 2;
indices[ 3 ] = 0+3;
indices[ 4 ] = 1+3;
indices[ 5 ] = 2+3;
indices[ 6 ] = 0+6;
indices[ 7 ] = 1+6;
indices[ 8 ] = 2+6;
indices[ 9 ] = 0+9;
indices[ 10 ] = 1+9;
indices[ 11 ] = 2+9;
indices[ 12 ] = 0+12;
indices[ 13 ] = 1+12;
indices[ 14 ] = 2+12;
indices[ 15 ] = 0+15;
indices[ 16 ] = 1+15;
indices[ 17 ] = 2+15;
indices[ 18 ] = 0+18;
indices[ 19 ] = 1 + 18;
indices[ 20 ] = 2 + 18;
indices[ 21 ] = 0+21;
indices[ 22 ] = 1 + 21;
indices[ 23 ] = 2 + 21;
indices[ 24 ] = 0+24;
indices[ 25 ] = 1 + 24;
indices[ 26 ] = 2 + 24;
indices[ 27 ] = 0+27;
indices[ 28 ] = 1 + 27;
indices[ 29 ] = 2 + 27;
indices[ 30 ] = 0+30;
indices[ 31 ] = 1 + 30;
indices[ 32 ] = 2 + 30;
indices[ 33 ] = 0+33;
indices[ 34 ] = 1 + 33;
indices[ 35 ] = 2 + 33;
size = sizeof( GLushort ) * NumIndices;
pGeometry->m_ib = BufferData::alloc( IndexBuffer, size, ReadOnly );
::memcpy( pGeometry->m_ib->m_pData, indices, size );
return pGeometry;
}
//-------------------------------------------------------------------------------------------------
RenderBackend::Geometry *GeometryBuilder::createTextBox( f32 x, f32 y, f32 size, const String &text ) {
if ( text.empty() ) {
return nullptr;
}
Geometry *geo = new Geometry;
std::vector<RenderVert> vertices;
std::vector<GLushort> indices;
for (ui32 i = 0; i <text.size(); i++) {
RenderVert vert[ 4 ];
vert[ 0 ].position = glm::vec3( x + i*size, y + size, 0 );
vert[ 1 ].position = glm::vec3( x + i*size + size, y + size, 0 );
vert[ 2 ].position = glm::vec3( x + i*size + size, y, 0 );
vert[ 3 ].position = glm::vec3( x + i*size, y, 0 );
char character = text[ i ];
float uv_x = ( character % 16 ) / 16.0f;
float uv_y = ( character / 16 ) / 16.0f;
vert[ 0 ].tex0 = glm::vec2( uv_x, 1.0f - uv_y );
vert[ 1 ].tex0 = glm::vec2( uv_x + 1.0f / 16.0f, 1.0f - uv_y );
vert[ 2 ].tex0 = glm::vec2( uv_x + 1.0f / 16.0f, 1.0f - ( uv_y + 1.0f / 16.0f ) );
vert[ 3 ].tex0 = glm::vec2( uv_x, 1.0f - ( uv_y + 1.0f / 16.0f ) );
for (ui32 j = 0; j < 4; j++) {
vertices.push_back( vert[ j ] );
}
// setup indices
static const ui32 NumIndices = 6;
GLushort quad[ NumIndices ];
quad[ 0 ] = 0;
quad[ 1 ] = 1;
quad[ 2 ] = 2;
quad[ 0 ] = 2;
quad[ 1 ] = 3;
quad[ 2 ] = 1;
for (ui32 j = 0; j < 6; ++j) {
indices.push_back( quad[ i ] + (i*4) );
}
}
const ui32 vertSize( vertices.size() * sizeof( RenderVert ) );
BufferData *bufferData = BufferData::alloc( VertexBuffer, vertSize, ReadWrite );
::memcpy( bufferData->m_pData, &vertices[ 0 ], vertSize );
geo->m_vb = bufferData;
size = sizeof( GLushort ) * text.size() * 6;
geo->m_ib = BufferData::alloc( IndexBuffer, size, ReadOnly );
::memcpy( geo->m_ib->m_pData, &indices[ 0 ], size );
geo->m_numPrimGroups = 1;
geo->m_pPrimGroups = new PrimitiveGroup[ geo->m_numPrimGroups ];
geo->m_pPrimGroups[ 0 ].m_indexType = UnsignedShort;
geo->m_pPrimGroups[ 0 ].m_numPrimitives = text.size()*2;
geo->m_pPrimGroups[ 0 ].m_primitive = TriangleList;
geo->m_pPrimGroups[ 0 ].m_startIndex = 0;
// setup material
geo->m_material = new Material;
geo->m_material->m_numTextures = 0;
geo->m_material->m_type = ShaderMaterial;
geo->m_material->m_pShader = new Shader;
geo->m_material->m_pShader->m_src[ SH_VertexShaderType ] = VsSrc;
geo->m_material->m_pShader->m_src[ SH_FragmentShaderType ] = FsSrc;
// setup shader attributes and variables
if (nullptr != geo->m_material->m_pShader) {
ui32 numAttribs( ColorVert::getNumAttributes() );
const String *attribs( ColorVert::getAttributes() );
geo->m_material->m_pShader->m_attributes.add( attribs, numAttribs );
geo->m_material->m_pShader->m_parameters.add( "MVP" );
}
return geo;
}
//-------------------------------------------------------------------------------------------------
} // Namespace Scene
} // namespace OSRE
<commit_msg>RenderBackend: add missing cpp-file OGLCommon.cpp<commit_after>/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015 OSRE ( Open Source Render Engine ) by Kim Kulling
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------------------------*/
#include <osre/Scene/GeometryBuilder.h>
#include <GL/glew.h>
#include <GL/gl.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <vector>
namespace OSRE {
namespace Scene {
using namespace ::OSRE::RenderBackend;
const String VsSrc =
"#version 400 core\n"
"\n"
"layout(location = 0) in vec3 position; // object space vertex position\n"
"layout(location = 1) in vec3 normal; // object space vertex normal\n"
"layout(location = 2) in vec3 color0; // per-vertex colour\n"
"\n"
"// output from the vertex shader\n"
"smooth out vec4 vSmoothColor; //smooth colour to fragment shader\n"
"\n"
"// uniform\n"
"uniform mat4 MVP; //combined modelview projection matrix\n"
"\n"
"void main()\n"
"{\n"
" //assign the per-vertex color to vSmoothColor varying\n"
" vSmoothColor = vec4(color0,1);\n"
"\n"
" //get the clip space position by multiplying the combined MVP matrix with the object space\n"
" //vertex position\n"
" gl_Position = MVP*vec4(position,1);\n"
"}\n";
const String FsSrc =
"#version 400 core\n"
"\n"
"layout(location=0) out vec4 vFragColor; //fragment shader output\n"
"\n"
"//input form the vertex shader\n"
"smooth in vec4 vSmoothColor; //interpolated colour to fragment shader\n"
"\n"
"void main()\n"
"{\n"
" //set the interpolated color as the shader output\n"
" vFragColor = vSmoothColor;\n"
"}\n";
static const String TextVsSrc =
"layout(location = 0) in vec3 position; // object space vertex position\n"
"layout(location = 1) in vec3 normal; // object space vertex normal\n"
"layout(location = 2) in vec2 texcoord0; // texture coordinate\n"
"out vec2 vUV;\n"
"\n"
"void main() {\n"
" vec3 vertexPosition_homoneneousspace = position;\n"
" gl_Position = vec4(position, 1 );\n"
" // UV of the vertex. No special space for this one.\n"
" UV = texcoord0;\n"
"};\n";
static const String TextFsSrc =
"in vec2 vUV;\n"
"// Output data\n"
"out vec4 vFragColor;\n"
"uniform sampler2D tex0;\n"
"void main() {\n"
" vFragColor = texture( tex0, vUV );\n"
"};\n";
//-------------------------------------------------------------------------------------------------
GeometryBuilder::GeometryBuilder() {
// empty
}
//-------------------------------------------------------------------------------------------------
GeometryBuilder::~GeometryBuilder() {
// empty
}
//-------------------------------------------------------------------------------------------------
RenderBackend::Geometry *GeometryBuilder::createEmptyGeometry( RenderBackend::VertexType type ) {
Geometry *geo = new Geometry;
geo->m_vertextype = type;
geo->m_indextype = UnsignedShort;
return geo;
}
//-------------------------------------------------------------------------------------------------
RenderBackend::Geometry *GeometryBuilder::createTriangle() {
Geometry *geo = new Geometry;
geo->m_vertextype = ColorVertex;
geo->m_indextype = UnsignedShort;
// setup triangle vertices
static const ui32 NumVert = 3;
ColorVert vertices[ NumVert ];
vertices[ 0 ].color = glm::vec3( 1, 0, 0 );
vertices[ 1 ].color = glm::vec3( 0, 1, 0 );
vertices[ 2 ].color = glm::vec3( 0, 0, 1 );
vertices[ 0 ].position = glm::vec3( -1, -1, 0 );
vertices[ 1 ].position = glm::vec3( 0, 1, 0 );
vertices[ 2 ].position = glm::vec3( 1, -1, 0 );
ui32 size( sizeof( ColorVert ) * NumVert );
geo->m_vb = BufferData::alloc( VertexBuffer, size, ReadOnly );
::memcpy( geo->m_vb->m_pData, vertices, size );
// setup triangle indices
static const ui32 NumIndices = 3;
GLushort indices[ NumIndices ];
indices[ 0 ] = 0;
indices[ 1 ] = 1;
indices[ 2 ] = 2;
size = sizeof( GLushort ) * NumIndices;
geo->m_ib = BufferData::alloc( IndexBuffer, size, ReadOnly );
::memcpy( geo->m_ib->m_pData, indices, size );
// setup primitives
geo->m_numPrimGroups = 1;
geo->m_pPrimGroups = new PrimitiveGroup[ geo->m_numPrimGroups ];
geo->m_pPrimGroups[ 0 ].m_indexType = UnsignedShort;
geo->m_pPrimGroups[ 0 ].m_numPrimitives = 3 * geo->m_numPrimGroups;
geo->m_pPrimGroups[ 0 ].m_primitive = TriangleList;
geo->m_pPrimGroups[ 0 ].m_startIndex = 0;
// setup material
geo->m_material = new Material;
geo->m_material->m_numTextures = 0;
geo->m_material->m_type = ShaderMaterial;
geo->m_material->m_pShader = new Shader;
geo->m_material->m_pShader->m_src[ SH_VertexShaderType ] = VsSrc;
geo->m_material->m_pShader->m_src[ SH_FragmentShaderType ] = FsSrc;
// setup shader attributes and variables
if( nullptr != geo->m_material->m_pShader ) {
ui32 numAttribs( ColorVert::getNumAttributes() );
const String *attribs( ColorVert::getAttributes() );
geo->m_material->m_pShader->m_attributes.add(attribs, numAttribs);
geo->m_material->m_pShader->m_parameters.add( "MVP" );
}
return geo;
}
//-------------------------------------------------------------------------------------------------
RenderBackend::Geometry *GeometryBuilder::createBox( f32 w, f32 h, f32 d ) {
Geometry *pGeometry = new Geometry;
pGeometry->m_vertextype = ColorVertex;
pGeometry->m_indextype = UnsignedShort;
static const ui32 NumVert = 8;
ColorVert vertices[ NumVert ];
f32 x(0.0f), y(0.0f), z( 0.0f );
vertices[ 0 ].position = glm::vec3( x, y, z );
vertices[ 1 ].position = glm::vec3( x + w, y, z );
vertices[ 2 ].position = glm::vec3( x + w, y + h, z );
vertices[ 3 ].position = glm::vec3( x, y + h, z );
vertices[ 4 ].position = glm::vec3( x, y, z + d );
vertices[ 5 ].position = glm::vec3( x + w, y, z + d );
vertices[ 6 ].position = glm::vec3( x + w, y + h, z + d );
vertices[ 7 ].position = glm::vec3( x, y + h, z + d );
ui32 size( sizeof( ColorVert ) * NumVert );
pGeometry->m_vb = BufferData::alloc( VertexBuffer, size, ReadOnly );
::memcpy( pGeometry->m_vb->m_pData, vertices, size );
static const ui32 NumIndices = 36;
GLushort indices[ NumIndices ];
indices[ 0 ] = 0;
indices[ 1 ] = 1;
indices[ 2 ] = 2;
indices[ 3 ] = 0+3;
indices[ 4 ] = 1+3;
indices[ 5 ] = 2+3;
indices[ 6 ] = 0+6;
indices[ 7 ] = 1+6;
indices[ 8 ] = 2+6;
indices[ 9 ] = 0+9;
indices[ 10 ] = 1+9;
indices[ 11 ] = 2+9;
indices[ 12 ] = 0+12;
indices[ 13 ] = 1+12;
indices[ 14 ] = 2+12;
indices[ 15 ] = 0+15;
indices[ 16 ] = 1+15;
indices[ 17 ] = 2+15;
indices[ 18 ] = 0+18;
indices[ 19 ] = 1 + 18;
indices[ 20 ] = 2 + 18;
indices[ 21 ] = 0+21;
indices[ 22 ] = 1 + 21;
indices[ 23 ] = 2 + 21;
indices[ 24 ] = 0+24;
indices[ 25 ] = 1 + 24;
indices[ 26 ] = 2 + 24;
indices[ 27 ] = 0+27;
indices[ 28 ] = 1 + 27;
indices[ 29 ] = 2 + 27;
indices[ 30 ] = 0+30;
indices[ 31 ] = 1 + 30;
indices[ 32 ] = 2 + 30;
indices[ 33 ] = 0+33;
indices[ 34 ] = 1 + 33;
indices[ 35 ] = 2 + 33;
size = sizeof( GLushort ) * NumIndices;
pGeometry->m_ib = BufferData::alloc( IndexBuffer, size, ReadOnly );
::memcpy( pGeometry->m_ib->m_pData, indices, size );
return pGeometry;
}
//-------------------------------------------------------------------------------------------------
RenderBackend::Geometry *GeometryBuilder::createTextBox( f32 x, f32 y, f32 size, const String &text ) {
if ( text.empty() ) {
return nullptr;
}
Geometry *geo = new Geometry;
std::vector<RenderVert> vertices;
std::vector<GLushort> indices;
static const ui32 NumIndices = 6;
GLushort quad[ NumIndices ];
quad[ 0 ] = 0;
quad[ 1 ] = 1;
quad[ 2 ] = 2;
quad[ 0 ] = 2;
quad[ 1 ] = 3;
quad[ 2 ] = 1;
for (ui32 i = 0; i <text.size(); i++) {
RenderVert vert[ 4 ];
vert[ 0 ].position = glm::vec3( x + i*size, y + size, 0 );
vert[ 1 ].position = glm::vec3( x + i*size + size, y + size, 0 );
vert[ 2 ].position = glm::vec3( x + i*size + size, y, 0 );
vert[ 3 ].position = glm::vec3( x + i*size, y, 0 );
char character = text[ i ];
float uv_x = ( character % 16 ) / 16.0f;
float uv_y = ( character / 16 ) / 16.0f;
vert[ 0 ].tex0 = glm::vec2( uv_x, 1.0f - uv_y );
vert[ 1 ].tex0 = glm::vec2( uv_x + 1.0f / 16.0f, 1.0f - uv_y );
vert[ 2 ].tex0 = glm::vec2( uv_x + 1.0f / 16.0f, 1.0f - ( uv_y + 1.0f / 16.0f ) );
vert[ 3 ].tex0 = glm::vec2( uv_x, 1.0f - ( uv_y + 1.0f / 16.0f ) );
for (ui32 j = 0; j < 4; j++) {
vertices.push_back( vert[ j ] );
}
// setup indices
for (ui32 j = 0; j < 6; ++j) {
indices.push_back( quad[ i ] + (i*4) );
}
}
const ui32 vertSize( vertices.size() * sizeof( RenderVert ) );
BufferData *bufferData = BufferData::alloc( VertexBuffer, vertSize, ReadWrite );
::memcpy( bufferData->m_pData, &vertices[ 0 ], vertSize );
geo->m_vb = bufferData;
size = sizeof( GLushort ) * text.size() * 6;
geo->m_ib = BufferData::alloc( IndexBuffer, size, ReadOnly );
::memcpy( geo->m_ib->m_pData, &indices[ 0 ], size );
geo->m_numPrimGroups = 1;
geo->m_pPrimGroups = new PrimitiveGroup[ geo->m_numPrimGroups ];
geo->m_pPrimGroups[ 0 ].m_indexType = UnsignedShort;
geo->m_pPrimGroups[ 0 ].m_numPrimitives = text.size()*2;
geo->m_pPrimGroups[ 0 ].m_primitive = TriangleList;
geo->m_pPrimGroups[ 0 ].m_startIndex = 0;
// setup material
geo->m_material = new Material;
geo->m_material->m_numTextures = 0;
geo->m_material->m_type = ShaderMaterial;
geo->m_material->m_pShader = new Shader;
geo->m_material->m_pShader->m_src[ SH_VertexShaderType ] = VsSrc;
geo->m_material->m_pShader->m_src[ SH_FragmentShaderType ] = FsSrc;
// setup shader attributes and variables
if ( nullptr != geo->m_material->m_pShader) {
ui32 numAttribs( ColorVert::getNumAttributes() );
const String *attribs( ColorVert::getAttributes() );
geo->m_material->m_pShader->m_attributes.add( attribs, numAttribs );
geo->m_material->m_pShader->m_parameters.add( "MVP" );
}
return geo;
}
//-------------------------------------------------------------------------------------------------
} // Namespace Scene
} // namespace OSRE
<|endoftext|>
|
<commit_before>#pragma XOD evaluate_on_pin disable
#pragma XOD evaluate_on_pin enable input_UPD
/*
* Datasheet can be found at
* https://cdn-shop.adafruit.com/datasheets/DS18B20.pdf
*
* Most code comments are quotes from that datasheet
*/
enum {
CMD_CONVERT = 0x44,
CMD_READ_SCRATCHPAD = 0xBE,
CMD_SKIP_ROM = 0xCC
};
void writeByte(uint8_t pin, uint8_t data) {
pinMode(pin, OUTPUT);
// There are two types of write time slots: “Write 1” time slots and “Write
// 0” time slots. The bus master uses a Write 1 time slot to write a logic
// 1 to the DS18B20 and a Write 0 time slot to write a logic 0 to the
// DS18B20. All write time slots must be a minimum of 60µs in duration with
// a minimum of a 1µs recovery time between individual write slots. Both
// types of write time slots are initiated by the master pulling the 1-Wire
// bus low
for (uint8_t i = 8; i--; data >>= 1) {
bool bit = data & 0x01;
// To generate a Write 1 time slot, after pulling the 1-Wire bus low,
// the bus master must release the 1-Wire bus within 15µs. When the bus
// is released, the 5kΩ pullup resistor will pull the bus high. To
// generate a Write 0 time slot, after pulling the 1-Wire bus low, the
// bus master must continue to hold the bus low for the duration of the
// time slot (at least 60µs)
digitalWrite(pin, LOW);
delayMicroseconds(bit ? 10 : 50);
digitalWrite(pin, HIGH);
delayMicroseconds(bit ? 50 : 10);
}
pinMode(pin, INPUT); // release the bus
}
uint8_t readByte(uint8_t pin) {
uint8_t r = 0;
for (uint8_t i = 0; i < 8; ++i) {
// All read time slots must be a minimum of 60µs in duration with a
// minimum of a 1µs recovery time between slots. A read time slot is
// initiated by the master device pulling the 1-Wire bus low for a
// minimum of 1µs and then releasing the bus.
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delayMicroseconds(1);
pinMode(pin, INPUT);
// Output data from the DS18B20 is valid for 15µs after the falling
// edge that initiated the read time slot. Therefore, the master must
// release the bus and then sample the bus state within 15µs from the
// start of the slot.
delayMicroseconds(5);
// After the master initiates the read time slot, the DS18B20 will
// begin transmitting a 1 or 0 on bus. The DS18B20 transmits a 1 by
// leaving the bus high and transmits a 0 by pulling the bus low. When
// transmitting a 0, the DS18B20 will release the bus by the end of the
// time slot, and the bus will be pulled back to its high idle state by
// the pullup resister.
r |= digitalRead(pin) << i;
delayMicroseconds(54); // complete the cycle
}
return r;
}
bool init(uint8_t pin) {
// All communication with the DS18B20 begins with an initialization
// sequence that consists of a reset pulse from the master followed by a
// presence pulse from the DS18B20...
// During the initialization sequence the bus master transmits (TX) the
// reset pulse by pulling the 1-Wire bus low for a minimum of 480µs. The
// bus master then releases the bus and goes into receive mode (RX).
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delayMicroseconds(480);
pinMode(pin, INPUT);
// When the bus is released, the 5kΩ pullup resistor pulls the 1-Wire bus
// high. When the DS18B20 detects this rising edge, it waits 15µs to 60µs
// and then transmits a presence pulse by pulling the 1-Wire bus low for
// 60µs to 240µs.
delayMicroseconds(60);
if (digitalRead(pin))
return false; // no presence
delayMicroseconds(420); // complete initialization procedure
return true;
}
bool readTemperature(uint8_t pin, Number* out) {
if (!init(pin))
return false;
writeByte(pin, CMD_SKIP_ROM);
writeByte(pin, CMD_CONVERT);
if (!init(pin))
return false;
writeByte(pin, CMD_SKIP_ROM);
writeByte(pin, CMD_READ_SCRATCHPAD);
int16_t hi = readByte(pin);
int16_t lo = readByte(pin);
*out = (Number)(hi | lo << 8) / 16.0;
return true;
}
struct State {
};
{{ GENERATED_CODE }}
void evaluate(Context ctx) {
static_assert(isValidDigitalPort(constant_input_PORT), "must be a valid digital port");
if (!isInputDirty<input_UPD>(ctx))
return;
Number tc;
bool success = readTemperature(port, &tc);
if (!success) {
raiseError(ctx); // Initialization sequence error
return;
}
emitValue<output_Tc>(ctx, tc);
emitValue<output_DONE>(ctx, 1);
}
<commit_msg>fix(stdlib): fix typo in implementation of xod/common-hardware/ds18b20-thermometer<commit_after>#pragma XOD evaluate_on_pin disable
#pragma XOD evaluate_on_pin enable input_UPD
/*
* Datasheet can be found at
* https://cdn-shop.adafruit.com/datasheets/DS18B20.pdf
*
* Most code comments are quotes from that datasheet
*/
enum {
CMD_CONVERT = 0x44,
CMD_READ_SCRATCHPAD = 0xBE,
CMD_SKIP_ROM = 0xCC
};
void writeByte(uint8_t pin, uint8_t data) {
pinMode(pin, OUTPUT);
// There are two types of write time slots: “Write 1” time slots and “Write
// 0” time slots. The bus master uses a Write 1 time slot to write a logic
// 1 to the DS18B20 and a Write 0 time slot to write a logic 0 to the
// DS18B20. All write time slots must be a minimum of 60µs in duration with
// a minimum of a 1µs recovery time between individual write slots. Both
// types of write time slots are initiated by the master pulling the 1-Wire
// bus low
for (uint8_t i = 8; i--; data >>= 1) {
bool bit = data & 0x01;
// To generate a Write 1 time slot, after pulling the 1-Wire bus low,
// the bus master must release the 1-Wire bus within 15µs. When the bus
// is released, the 5kΩ pullup resistor will pull the bus high. To
// generate a Write 0 time slot, after pulling the 1-Wire bus low, the
// bus master must continue to hold the bus low for the duration of the
// time slot (at least 60µs)
digitalWrite(pin, LOW);
delayMicroseconds(bit ? 10 : 50);
digitalWrite(pin, HIGH);
delayMicroseconds(bit ? 50 : 10);
}
pinMode(pin, INPUT); // release the bus
}
uint8_t readByte(uint8_t pin) {
uint8_t r = 0;
for (uint8_t i = 0; i < 8; ++i) {
// All read time slots must be a minimum of 60µs in duration with a
// minimum of a 1µs recovery time between slots. A read time slot is
// initiated by the master device pulling the 1-Wire bus low for a
// minimum of 1µs and then releasing the bus.
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delayMicroseconds(1);
pinMode(pin, INPUT);
// Output data from the DS18B20 is valid for 15µs after the falling
// edge that initiated the read time slot. Therefore, the master must
// release the bus and then sample the bus state within 15µs from the
// start of the slot.
delayMicroseconds(5);
// After the master initiates the read time slot, the DS18B20 will
// begin transmitting a 1 or 0 on bus. The DS18B20 transmits a 1 by
// leaving the bus high and transmits a 0 by pulling the bus low. When
// transmitting a 0, the DS18B20 will release the bus by the end of the
// time slot, and the bus will be pulled back to its high idle state by
// the pullup resister.
r |= digitalRead(pin) << i;
delayMicroseconds(54); // complete the cycle
}
return r;
}
bool init(uint8_t pin) {
// All communication with the DS18B20 begins with an initialization
// sequence that consists of a reset pulse from the master followed by a
// presence pulse from the DS18B20...
// During the initialization sequence the bus master transmits (TX) the
// reset pulse by pulling the 1-Wire bus low for a minimum of 480µs. The
// bus master then releases the bus and goes into receive mode (RX).
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delayMicroseconds(480);
pinMode(pin, INPUT);
// When the bus is released, the 5kΩ pullup resistor pulls the 1-Wire bus
// high. When the DS18B20 detects this rising edge, it waits 15µs to 60µs
// and then transmits a presence pulse by pulling the 1-Wire bus low for
// 60µs to 240µs.
delayMicroseconds(60);
if (digitalRead(pin))
return false; // no presence
delayMicroseconds(420); // complete initialization procedure
return true;
}
bool readTemperature(uint8_t pin, Number* out) {
if (!init(pin))
return false;
writeByte(pin, CMD_SKIP_ROM);
writeByte(pin, CMD_CONVERT);
if (!init(pin))
return false;
writeByte(pin, CMD_SKIP_ROM);
writeByte(pin, CMD_READ_SCRATCHPAD);
int16_t hi = readByte(pin);
int16_t lo = readByte(pin);
*out = (Number)(hi | lo << 8) / 16.0;
return true;
}
struct State {
};
{{ GENERATED_CODE }}
void evaluate(Context ctx) {
static_assert(isValidDigitalPort(constant_input_PORT), "must be a valid digital port");
if (!isInputDirty<input_UPD>(ctx))
return;
Number tc;
bool success = readTemperature(constant_input_PORT, &tc);
if (!success) {
raiseError(ctx); // Initialization sequence error
return;
}
emitValue<output_Tc>(ctx, tc);
emitValue<output_DONE>(ctx, 1);
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 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 Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "nepomukcontactfeeder.h"
#include <kabc/addressee.h>
#include <libakonadi/changerecorder.h>
#include <nepomuk/resource.h>
#include <nepomuk/variant.h>
#include <kurl.h>
// ontology includes
#include "personcontact.h"
#include "bbsnumber.h"
#include "carphonenumber.h"
#include "cellphonenumber.h"
#include "faxnumber.h"
#include "isdnnumber.h"
#include "messagingnumber.h"
#include "modemnumber.h"
#include "pagernumber.h"
#include "pcsnumber.h"
#include "videotelephonenumber.h"
#include "voicephonenumber.h"
using namespace Akonadi;
NepomukContactFeeder::NepomukContactFeeder( const QString &id )
: AgentBase( id )
{
monitor()->fetchAllParts();
monitor()->monitorMimeType( "text/directory" );
monitor()->setChangeRecordingEnabled( false );
}
void NepomukContactFeeder::itemAdded( const Akonadi::Item &item, const Akonadi::Collection& )
{
itemChanged( item, QStringList() );
}
void NepomukContactFeeder::itemChanged( const Akonadi::Item &item, const QStringList& )
{
if ( !item.hasPayload<KABC::Addressee>() )
return;
const KABC::Addressee addressee = item.payload<KABC::Addressee>();
Nepomuk::PersonContact contact( item.url() );
contact.setNameGivens( QStringList( addressee.givenName() ) );
contact.setNameAdditionals( QStringList( addressee.additionalName() ) );
contact.setNameFamilys( QStringList( addressee.familyName() ) );
contact.setNameHonorificPrefixs( QStringList( addressee.prefix() ) );
contact.setNameHonorificSuffixs( QStringList( addressee.suffix() ) );
contact.setLocations( QStringList( addressee.geo().toString() ) ); // make it better
// keys
// sounds
// logos
// photos
contact.setNotes( QStringList( addressee.note() ) );
contact.setNicknames( QStringList( addressee.nickName() ) );
contact.setContactUIDs( QStringList( addressee.uid() ) );
contact.setFullnames( QStringList( addressee.name() ) );
contact.setBirthDate( addressee.birthday().date() );
// phone numbers
// first clean all
contact.setPhoneNumbers( QList<Nepomuk::PhoneNumber>() );
// add all existing
const KABC::PhoneNumber::List phoneNumbers = addressee.phoneNumbers();
for ( int i = 0; i < phoneNumbers.count(); ++i ) {
if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Bbs ) {
Nepomuk::BbsNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Car ) {
Nepomuk::CarPhoneNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Cell ) {
Nepomuk::CellPhoneNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Fax ) {
Nepomuk::FaxNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Isdn ) {
Nepomuk::IsdnNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Msg ) {
Nepomuk::MessagingNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Modem ) {
Nepomuk::ModemNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Pager ) {
Nepomuk::PagerNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Pcs ) {
Nepomuk::PcsNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Video ) {
Nepomuk::VideoTelephoneNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Voice ) {
Nepomuk::VoicePhoneNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else { // matches Home and Work
Nepomuk::PhoneNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
}
}
}
void NepomukContactFeeder::itemRemoved( const Akonadi::DataReference &ref )
{
Item item( ref );
Nepomuk::PersonContact contact( item.url() );
QList<Nepomuk::PhoneNumber> numbers = contact.phoneNumbers();
Q_FOREACH( Nepomuk::PhoneNumber number, numbers ) {
number.remove();
}
contact.remove();
}
int main( int argc, char **argv )
{
return AgentBase::init<NepomukContactFeeder>( argc, argv );
}
#include "nepomukcontactfeeder.moc"
<commit_msg>extended nepomuk feeder to feed email and postal addresses into nepomuk<commit_after>/*
Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 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 Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "nepomukcontactfeeder.h"
#include <kabc/addressee.h>
#include <libakonadi/changerecorder.h>
#include <nepomuk/resource.h>
#include <nepomuk/variant.h>
#include <kurl.h>
// ontology includes
#include "bbsnumber.h"
#include "carphonenumber.h"
#include "cellphonenumber.h"
#include "emailaddress.h"
#include "faxnumber.h"
#include "isdnnumber.h"
#include "messagingnumber.h"
#include "modemnumber.h"
#include "pagernumber.h"
#include "personcontact.h"
#include "pcsnumber.h"
#include "postaladdress.h"
#include "videotelephonenumber.h"
#include "voicephonenumber.h"
using namespace Akonadi;
NepomukContactFeeder::NepomukContactFeeder( const QString &id )
: AgentBase( id )
{
monitor()->fetchAllParts();
monitor()->monitorMimeType( "text/directory" );
monitor()->setChangeRecordingEnabled( false );
}
void NepomukContactFeeder::itemAdded( const Akonadi::Item &item, const Akonadi::Collection& )
{
itemChanged( item, QStringList() );
}
void NepomukContactFeeder::itemChanged( const Akonadi::Item &item, const QStringList& )
{
if ( !item.hasPayload<KABC::Addressee>() )
return;
const KABC::Addressee addressee = item.payload<KABC::Addressee>();
Nepomuk::PersonContact contact( item.url() );
contact.setNameGivens( QStringList( addressee.givenName() ) );
contact.setNameAdditionals( QStringList( addressee.additionalName() ) );
contact.setNameFamilys( QStringList( addressee.familyName() ) );
contact.setNameHonorificPrefixs( QStringList( addressee.prefix() ) );
contact.setNameHonorificSuffixs( QStringList( addressee.suffix() ) );
contact.setLocations( QStringList( addressee.geo().toString() ) ); // make it better
// keys
// sounds
// logos
// photos
contact.setNotes( QStringList( addressee.note() ) );
contact.setNicknames( QStringList( addressee.nickName() ) );
contact.setContactUIDs( QStringList( addressee.uid() ) );
contact.setFullnames( QStringList( addressee.name() ) );
contact.setBirthDate( addressee.birthday().date() );
// phone numbers
// first clean all
contact.setPhoneNumbers( QList<Nepomuk::PhoneNumber>() );
// add all existing
const KABC::PhoneNumber::List phoneNumbers = addressee.phoneNumbers();
for ( int i = 0; i < phoneNumbers.count(); ++i ) {
if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Bbs ) {
Nepomuk::BbsNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Car ) {
Nepomuk::CarPhoneNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Cell ) {
Nepomuk::CellPhoneNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Fax ) {
Nepomuk::FaxNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Isdn ) {
Nepomuk::IsdnNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Msg ) {
Nepomuk::MessagingNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Modem ) {
Nepomuk::ModemNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Pager ) {
Nepomuk::PagerNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Pcs ) {
Nepomuk::PcsNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Video ) {
Nepomuk::VideoTelephoneNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Voice ) {
Nepomuk::VoicePhoneNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
} else { // matches Home and Work
Nepomuk::PhoneNumber number;
number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
contact.addPhoneNumber( number );
}
}
// im accounts
// email addresses
contact.setEmailAddresss( QList<Nepomuk::EmailAddress>() );
const QStringList emails = addressee.emails();
for ( int i = 0; i < emails.count(); ++i ) {
Nepomuk::EmailAddress email;
email.setEmailAddress( emails[ i ] );
contact.addEmailAddress( email );
}
// addresses
contact.setPostalAddresss( QList<Nepomuk::PostalAddress>() );
const KABC::Address::List addresses = addressee.addresses();
for ( int i = 0; i < addresses.count(); ++i ) {
Nepomuk::PostalAddress address;
address.addStreetAddress( addresses[ i ].street() );
address.setPostalcode( addresses[ i ].postalCode() );
address.setLocality( addresses[ i ].locality() );
address.setRegion( addresses[ i ].region() );
address.addPobox( addresses[ i ].postOfficeBox() );
address.setCountry( addresses[ i ].country() );
address.addExtendedAddress( addresses[ i ].extended() );
contact.addPostalAddress( address );
}
}
void NepomukContactFeeder::itemRemoved( const Akonadi::DataReference &ref )
{
Item item( ref );
Nepomuk::PersonContact contact( item.url() );
QList<Nepomuk::PhoneNumber> numbers = contact.phoneNumbers();
Q_FOREACH( Nepomuk::PhoneNumber number, numbers ) {
number.remove();
}
QList<Nepomuk::EmailAddress> emails = contact.emailAddresss();
Q_FOREACH( Nepomuk::EmailAddress email, emails ) {
email.remove();
}
QList<Nepomuk::PostalAddress> addresses = contact.postalAddresss();
Q_FOREACH( Nepomuk::PostalAddress address, addresses ) {
address.remove();
}
contact.remove();
}
int main( int argc, char **argv )
{
return AgentBase::init<NepomukContactFeeder>( argc, argv );
}
#include "nepomukcontactfeeder.moc"
<|endoftext|>
|
<commit_before>/*
* rpi_spi.cpp
*
* Created on: 2016. 2. 26.
* Author: hwang
*/
#include "rpi_spi.hpp"
#include <cossb.hpp>
#include <string>
#include <3rdparty/bcm2835.h>
#include <tuple>
using namespace std;
#define PIN RPI_BPLUS_GPIO_J8_05
using namespace std;
USE_COMPONENT_INTERFACE(rpi_spi)
rpi_spi::rpi_spi()
:cossb::interface::icomponent(COMPONENT(rpi_spi)){
// TODO Auto-generated constructor stub
}
rpi_spi::~rpi_spi() {
}
bool rpi_spi::setup()
{
if(!bcm2835_init())
return false;
if(!bcm2835_spi_begin())
return false;
//set gpio as input
//bcm2835_gpio_fsel(PIN, BCM2835_GPIO_FSEL_INPT);
bcm2835_gpio_fsel(PIN, BCM2835_GPIO_FSEL_OUTP);
//bcm2835_gpio_set_pud(PIN, BCM2835_GPIO_PUD_UP);
//set default spi
bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST); // The default
bcm2835_spi_setDataMode(BCM2835_SPI_MODE0); // The default
bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536); // The default
bcm2835_spi_chipSelect(BCM2835_SPI_CS0); // The default
bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW); // the default
return true;
}
bool rpi_spi::run()
{
//1. check gpio
//unsigned char value = bcm2835_gpio_lev(PIN);
bcm2835_gpio_write(PIN, HIGH);
//cossb_log->log(log::loglevel::INFO, fmt::format("GPIO : {}", value));
/*if(value!=0x00){
//cossb_log->log(log::loglevel::INFO, "GPIO : HIGH");
unsigned char readata = bcm2835_spi_transfer(_write_byte);
cossb_log->log(log::loglevel::INFO, fmt::format("Read SPI : {}", readata));
}
else {
//cossb_log->log(log::loglevel::INFO, "GPIO : LOW");
}*/
return true;
}
bool rpi_spi::stop()
{
//1. close spi
bcm2835_spi_end();
if(!bcm2835_close())
return false;
return true;
}
void rpi_spi::request(cossb::message* const msg)
{
switch(msg->get_frame()->type) {
case cossb::base::msg_type::REQUEST: break;
case cossb::base::msg_type::DATA: {
//subscribe emotion data
try {
unsigned char emotion_data = boost::any_cast<unsigned char>(*msg);
_write_byte = emotion_data; //copy
cossb_log->log(log::loglevel::INFO, fmt::format("SPI write : {}", emotion_data));
}
catch(const boost::bad_any_cast&){
cossb_log->log(log::loglevel::ERROR, "Invalid type casting..");
}
} break;
case cossb::base::msg_type::RESPONSE: break;
case cossb::base::msg_type::EVENT: break;
}
}
void rpi_spi::read()
{
}
<commit_msg>- update<commit_after>/*
* rpi_spi.cpp
*
* Created on: 2016. 2. 26.
* Author: hwang
*/
#include "rpi_spi.hpp"
#include <cossb.hpp>
#include <string>
#include <3rdparty/bcm2835.h>
#include <tuple>
using namespace std;
#define PIN RPI_BPLUS_GPIO_J8_05
using namespace std;
USE_COMPONENT_INTERFACE(rpi_spi)
rpi_spi::rpi_spi()
:cossb::interface::icomponent(COMPONENT(rpi_spi)){
// TODO Auto-generated constructor stub
}
rpi_spi::~rpi_spi() {
}
bool rpi_spi::setup()
{
if(!bcm2835_init())
return false;
if(!bcm2835_spi_begin())
return false;
//set gpio as input
bcm2835_gpio_fsel(PIN, BCM2835_GPIO_FSEL_INPT);
//bcm2835_gpio_set_pud(PIN, BCM2835_GPIO_PUD_UP);
//set default spi
bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST); // The default
bcm2835_spi_setDataMode(BCM2835_SPI_MODE0); // The default
bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536); // The default
bcm2835_spi_chipSelect(BCM2835_SPI_CS0); // The default
bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW); // the default
return true;
}
bool rpi_spi::run()
{
//1. check gpio
unsigned char value = bcm2835_gpio_lev(PIN);
cossb_log->log(log::loglevel::INFO, fmt::format("GPIO : {}", value));
if(value!=0x00){
//cossb_log->log(log::loglevel::INFO, "GPIO : HIGH");
unsigned char readata = bcm2835_spi_transfer(_write_byte);
cossb_log->log(log::loglevel::INFO, fmt::format("Read SPI : {}", readata));
}
else {
//cossb_log->log(log::loglevel::INFO, "GPIO : LOW");
}
return true;
}
bool rpi_spi::stop()
{
//1. close spi
bcm2835_spi_end();
if(!bcm2835_close())
return false;
return true;
}
void rpi_spi::request(cossb::message* const msg)
{
switch(msg->get_frame()->type) {
case cossb::base::msg_type::REQUEST: break;
case cossb::base::msg_type::DATA: {
//subscribe emotion data
try {
unsigned char emotion_data = boost::any_cast<unsigned char>(*msg);
_write_byte = emotion_data; //copy
cossb_log->log(log::loglevel::INFO, fmt::format("SPI write : {}", emotion_data));
}
catch(const boost::bad_any_cast&){
cossb_log->log(log::loglevel::ERROR, "Invalid type casting..");
}
} break;
case cossb::base::msg_type::RESPONSE: break;
case cossb::base::msg_type::EVENT: break;
}
}
void rpi_spi::read()
{
}
<|endoftext|>
|
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <Trigger.hpp>
void trigger(const Options &options, const unsigned int padding, const unsigned int integration, const AstroData::Observation &observation, const HostMemory &hostMemory, TriggeredEvents &triggeredEvents)
{
unsigned int nrDMs = 0;
if (options.subbandDedispersion)
{
nrDMs = observation.getNrDMs(true) * observation.getNrDMs();
}
else
{
nrDMs = observation.getNrDMs();
}
#pragma omp parallel for
for (unsigned int beam = 0; beam < observation.getNrSynthesizedBeams(); beam++)
{
for (unsigned int dm = 0; dm < nrDMs; dm++)
{
unsigned int maxIndex = 0;
outputDataType maxSNR = 0;
outputDataType maxSNR_mad = 0;
if (options.snrMode == SNRMode::Standard)
{
maxSNR = hostMemory.snrData.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
maxIndex = hostMemory.snrSamples.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
}
else if (options.snrMode == SNRMode::Momad)
{
maxSNR_mad = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48);
maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
}
if ( (std::isnormal(maxSNR)) && (maxSNR >= options.threshold) )
{
// std::cout<<"\n\n=TRIGGER=" << "\tSNR_mad: "<< maxSNR_mad << "\tSNR_stdev: " << maxSNR << "\tDM: " << dm << "\tthreshold: " << options.threshold << std::endl;
// std::cout<<"integration: " << integration << "\tstdev: "<<hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)<<"\tmad*1.48: "<<(hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48)<<std::endl;
// std::cout << std::endl;
TriggeredEvent event;
event.beam = beam;
event.sample = maxIndex;
event.integration = integration;
event.DM = dm;
event.SNR = maxSNR;
try
{
// Add event to its existing list
triggeredEvents.at(beam).at(dm).push_back(event);
}
catch (std::out_of_range &err)
{
// Add event to new list
std::vector<TriggeredEvent> events;
events.push_back(event);
triggeredEvents.at(beam).insert(std::pair<unsigned int, std::vector<TriggeredEvent>>(dm, events));
}
}
}
}
}
void compact(const AstroData::Observation &observation, const TriggeredEvents &triggeredEvents, CompactedEvents &compactedEvents)
{
CompactedEvents temporaryEvents(observation.getNrSynthesizedBeams());
// Compact integration
for (auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents)
{
for (auto dmEvents = beamEvents->begin(); dmEvents != beamEvents->end(); ++dmEvents)
{
CompactedEvent event;
for (auto dmEvent = dmEvents->second.begin(); dmEvent != dmEvents->second.end(); ++dmEvent)
{
if (dmEvent->SNR > event.SNR)
{
event.beam = dmEvent->beam;
event.sample = dmEvent->sample;
event.integration = dmEvent->integration;
event.DM = dmEvent->DM;
event.SNR = dmEvent->SNR;
}
}
event.compactedIntegration = dmEvents->second.size();
temporaryEvents.at(event.beam).push_back(event);
}
}
// Compact DM
for (auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents)
{
for (auto event = beamEvents->begin(); event != beamEvents->end(); ++event)
{
CompactedEvent finalEvent;
unsigned int window = 0;
while ( (event->DM + window) == (event + window)->DM && ((event + window) != beamEvents->end()) )
{
if ((event + window)->SNR > finalEvent.SNR)
{
finalEvent.beam = (event + window)->beam;
finalEvent.sample = (event + window)->sample;
finalEvent.integration = (event + window)->integration;
finalEvent.compactedIntegration = (event + window)->compactedIntegration;
finalEvent.DM = (event + window)->DM;
finalEvent.SNR = (event + window)->SNR;
}
window++;
}
finalEvent.compactedDMs = window;
compactedEvents.at(finalEvent.beam).push_back(finalEvent);
// Move the iterator forward
event += (window - 1);
}
}
}
<commit_msg>Add 3sig factor<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <Trigger.hpp>
void trigger(const Options &options, const unsigned int padding, const unsigned int integration, const AstroData::Observation &observation, const HostMemory &hostMemory, TriggeredEvents &triggeredEvents)
{
unsigned int nrDMs = 0;
if (options.subbandDedispersion)
{
nrDMs = observation.getNrDMs(true) * observation.getNrDMs();
}
else
{
nrDMs = observation.getNrDMs();
}
#pragma omp parallel for
for (unsigned int beam = 0; beam < observation.getNrSynthesizedBeams(); beam++)
{
for (unsigned int dm = 0; dm < nrDMs; dm++)
{
unsigned int maxIndex = 0;
outputDataType maxSNR = 0;
outputDataType maxSNR_mad = 0;
if (options.snrMode == SNRMode::Standard)
{
maxSNR = hostMemory.snrData.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
maxIndex = hostMemory.snrSamples.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
}
else if (options.snrMode == SNRMode::Momad)
{
//maxSNR_mad = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48);
//maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (1.014*hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm));
maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (1.014f*hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm));
maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
std::cout << hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) << std::endl;
}
if ( (std::isnormal(maxSNR)) && (maxSNR >= options.threshold) )
{
// std::cout<<"\n\n=TRIGGER=" << "\tSNR_mad: "<< maxSNR_mad << "\tSNR_stdev: " << maxSNR << "\tDM: " << dm << "\tthreshold: " << options.threshold << std::endl;
// std::cout<<"integration: " << integration << "\tstdev: "<<hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)<<"\tmad*1.48: "<<(hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48)<<std::endl;
// std::cout << std::endl;
TriggeredEvent event;
event.beam = beam;
event.sample = maxIndex;
event.integration = integration;
event.DM = dm;
event.SNR = maxSNR;
try
{
// Add event to its existing list
triggeredEvents.at(beam).at(dm).push_back(event);
}
catch (std::out_of_range &err)
{
// Add event to new list
std::vector<TriggeredEvent> events;
events.push_back(event);
triggeredEvents.at(beam).insert(std::pair<unsigned int, std::vector<TriggeredEvent>>(dm, events));
}
}
}
}
}
void compact(const AstroData::Observation &observation, const TriggeredEvents &triggeredEvents, CompactedEvents &compactedEvents)
{
CompactedEvents temporaryEvents(observation.getNrSynthesizedBeams());
// Compact integration
for (auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents)
{
for (auto dmEvents = beamEvents->begin(); dmEvents != beamEvents->end(); ++dmEvents)
{
CompactedEvent event;
for (auto dmEvent = dmEvents->second.begin(); dmEvent != dmEvents->second.end(); ++dmEvent)
{
if (dmEvent->SNR > event.SNR)
{
event.beam = dmEvent->beam;
event.sample = dmEvent->sample;
event.integration = dmEvent->integration;
event.DM = dmEvent->DM;
event.SNR = dmEvent->SNR;
}
}
event.compactedIntegration = dmEvents->second.size();
temporaryEvents.at(event.beam).push_back(event);
}
}
// Compact DM
for (auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents)
{
for (auto event = beamEvents->begin(); event != beamEvents->end(); ++event)
{
CompactedEvent finalEvent;
unsigned int window = 0;
while ( (event->DM + window) == (event + window)->DM && ((event + window) != beamEvents->end()) )
{
if ((event + window)->SNR > finalEvent.SNR)
{
finalEvent.beam = (event + window)->beam;
finalEvent.sample = (event + window)->sample;
finalEvent.integration = (event + window)->integration;
finalEvent.compactedIntegration = (event + window)->compactedIntegration;
finalEvent.DM = (event + window)->DM;
finalEvent.SNR = (event + window)->SNR;
}
window++;
}
finalEvent.compactedDMs = window;
compactedEvents.at(finalEvent.beam).push_back(finalEvent);
// Move the iterator forward
event += (window - 1);
}
}
}
<|endoftext|>
|
<commit_before>#ifndef INCLUDE_ACKWARD_CORE_PROPERTY_HPP
#define INCLUDE_ACKWARD_CORE_PROPERTY_HPP
#include <iostream>
#include <string>
#include <boost/call_traits.hpp>
#include <ackward/core/ExceptionTranslator.hpp>
#include <ackward/core/Object.hpp>
namespace ackward {
namespace core {
/** Property<T> is a value-like C++ interface to an underlying Python
property. It provides a C++ API for properties which is similar to
what you get in Python.
\rst
General use is like this::
class MyClass {
public:
Property<int> myProperty;
};
...
MyClass c;
c.myProperty = 3;
int x = c.myProperty;
\endrst
*/
template <typename T>
class Property : private Object
{
public:
typedef T value_type;
/** Construct a new property.
@param obj The underlying Python object.
@param pythonName The name of the property on `obj`.
*/
Property(boost::python::object obj,
const std::string& pythonName) :
Object (obj),
pythonName_ (pythonName)
{}
/** Get the underlying property value.
*/
operator value_type () const
{
try {
return boost::python::extract<value_type>(
obj().attr(pythonName_.c_str()));
} TRANSLATE_PYTHON_EXCEPTION();
}
/** Assign to the underlying property.
@param v The value to assign.
@returns This object.
*/
Property<value_type>& operator=(typename boost::call_traits<value_type>::const_reference v)
{
try {
obj().attr(pythonName_.c_str()) = v;
} TRANSLATE_PYTHON_EXCEPTION();
return *this;
}
using Object::obj;
private:
std::string pythonName_;
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const Property<T>& p)
{
os << static_cast<T>(p);
return os;
}
}
}
#endif
<commit_msg>split core::Property up into ROProperty and Property<commit_after>#ifndef INCLUDE_ACKWARD_CORE_PROPERTY_HPP
#define INCLUDE_ACKWARD_CORE_PROPERTY_HPP
#include <iostream>
#include <string>
#include <boost/call_traits.hpp>
#include <ackward/core/ExceptionTranslator.hpp>
#include <ackward/core/Object.hpp>
namespace ackward {
namespace core {
/** Property<T> is a value-like C++ interface to an underlying Python
property. It provides a C++ API for properties which is similar to
what you get in Python.
\rst
General use is like this::
class MyClass {
public:
Property<int> myProperty;
};
...
MyClass c;
c.myProperty = 3;
int x = c.myProperty;
\endrst
*/
template <typename T>
class ROProperty : private Object
{
public:
typedef T value_type;
/** Construct a new read-only property.
@param obj The underlying Python object.
@param pythonName The name of the property on `obj`.
*/
ROProperty(boost::python::object obj,
const std::string& pythonName) :
Object (obj),
pythonName_ (pythonName)
{}
/** Get the underlying property value.
*/
operator value_type () const
{
try {
return boost::python::extract<value_type>(
obj().attr(pythonName_.c_str()));
} TRANSLATE_PYTHON_EXCEPTION();
}
using Object::obj;
const std::string& pythonName() const
{
return pythonName_;
}
private:
std::string pythonName_;
};
template <typename T>
class Property : public ROProperty<T>
{
public:
typedef typename ROProperty<T>::value_type value_type;
/** Construct a new property.
@param obj The underlying Python object.
@param pythonName The name of the property on `obj`.
*/
Property(boost::python::object obj,
const std::string& pythonName) :
ROProperty<T>(obj, pythonName)
{}
/** Assign to the underlying property.
@param v The value to assign.
@returns This object.
*/
Property<value_type>& operator=(typename boost::call_traits<value_type>::const_reference v)
{
try {
obj().attr(this->pythonName().c_str()) = v;
} TRANSLATE_PYTHON_EXCEPTION();
return *this;
}
using ROProperty<T>::obj;
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const ROProperty<T>& p)
{
os << static_cast<T>(p);
return os;
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* AscEmu Framework based on ArcEmu MMORPG Server
* Copyright (C) 2014-2015 AscEmu Team <http://www.ascemu.org/>
* Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
* Copyright (C) 2005-2007 Ascent Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
const char* GetDifficultyString(uint8 difficulty)
{
switch (difficulty)
{
case MODE_NORMAL:
return "normal";
case MODE_HEROIC:
return "heroic";
default:
return "unknown";
}
}
const char* GetRaidDifficultyString(uint8 diff)
{
switch (diff)
{
case MODE_NORMAL_10MEN:
return "normal 10men";
case MODE_NORMAL_25MEN:
return "normal 25men";
case MODE_HEROIC_10MEN:
return "heroic 10men";
case MODE_HEROIC_25MEN:
return "heroic 25men";
default:
return "unknown";
}
}
const char* GetMapTypeString(uint8 type)
{
switch (type)
{
case INSTANCE_NULL:
return "Continent";
case INSTANCE_RAID:
return "Raid";
case INSTANCE_NONRAID:
return "Non-Raid";
case INSTANCE_BATTLEGROUND:
return "PvP";
case INSTANCE_MULTIMODE:
return "MultiMode";
default:
return "Unknown";
}
}
bool ChatHandler::HandleResetAllInstancesCommand(const char* args, WorldSession* m_session)
{
Player* plr;
if (strlen(args) == 0)
plr = getSelectedChar(m_session, true);
else
plr = objmgr.GetPlayer(args, false);;
if (!plr)
{
RedSystemMessage(m_session, "Player not found");
return true;
}
SystemMessage(m_session, "Trying to reset all instances of player %s...", plr->GetName());
sInstanceMgr.ResetSavedInstances(plr);
SystemMessage(m_session, "...done");
sGMLog.writefromsession(m_session, "used reset all instances command on %s,", plr->GetName());
return true;
}
bool ChatHandler::HandleResetInstanceCommand(const char* args, WorldSession* m_session)
{
uint32 instanceId;
int argc = 1;
char* playername = NULL;
char* guidString = (char*)args;
// Parse arguments
char* space = (char*)strchr(args, ' ');
if (space)
{
*space = '\0';
playername = space + 1;
argc = 2;
}
instanceId = atoi(guidString);
if (!instanceId)
{
RedSystemMessage(m_session, "You must specify an instance id.");
return true;
}
Player* plr;
if (argc == 1)
plr = getSelectedChar(m_session, true);
else
plr = objmgr.GetPlayer((const char*)playername, false);;
if (!plr)
{
RedSystemMessage(m_session, "Player not found");
return true;
}
Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
if (instance == NULL)
{
RedSystemMessage(m_session, "There's no instance with id %u.", instanceId);
return true;
}
if (IS_PERSISTENT_INSTANCE(instance))
{
if (m_session->CanUseCommand('z'))
{
bool foundSomething = false;
plr->getPlayerInfo()->savedInstanceIdsLock.Acquire();
for (uint32 difficulty = 0; difficulty < NUM_INSTANCE_MODES; difficulty++)
{
PlayerInstanceMap::iterator itr = plr->getPlayerInfo()->savedInstanceIds[difficulty].find(instance->m_mapId);
if (itr == plr->getPlayerInfo()->savedInstanceIds[difficulty].end() || (*itr).second != instance->m_instanceId)
continue;
plr->SetPersistentInstanceId(instance->m_mapId, difficulty, 0);
SystemMessage(m_session, "Instance with id %u (%s) is persistent and will only be revoked from player.", instanceId, GetDifficultyString(static_cast<uint8>(difficulty)));
foundSomething = true;
}
plr->getPlayerInfo()->savedInstanceIdsLock.Release();
if (!foundSomething)
RedSystemMessage(m_session, "Player is not assigned to persistent instance with id %u.", instanceId);
return true;
}
else
{
RedSystemMessage(m_session, "Instance with id %u is persistent and can only be removed from player by admins.", instanceId);
return true;
}
}
if (instance->m_mapMgr && instance->m_mapMgr->HasPlayers())
{
RedSystemMessage(m_session, "Failed to reset non-persistent instance with id %u, due to player still inside.", instanceId);
return true;
}
if (instance->m_creatorGroup)
{
Group* group = plr->GetGroup();
if (group == NULL || instance->m_creatorGroup != group->GetID())
{
RedSystemMessage(m_session, "Player %s is not a member of the group assigned to the non-persistent instance with id %u.", plr->GetName(), instanceId);
return true;
}
}
else if (instance->m_creatorGuid == 0 || instance->m_creatorGuid != plr->GetLowGUID())
{
RedSystemMessage(m_session, "Player %s is not assigned to instance with id %u.", plr->GetName(), instanceId);
return true;
}
// tell player the instance was reset
WorldPacket data(SMSG_INSTANCE_RESET, 4);
data << instance->m_mapId;
plr->GetSession()->SendPacket(&data);
// shut down instance
sInstanceMgr.DeleteBattlegroundInstance(instance->m_mapId, instance->m_instanceId);
instance->m_mapMgr->InstanceShutdown();
// RedSystemMessage(m_session, "Resetting single non-persistent instances is not available yet.");
sGMLog.writefromsession(m_session, "used reset instance command on %s, instance %u,", plr->GetName(), instanceId);
return true;
}
bool ChatHandler::HandleShutdownInstanceCommand(const char* args, WorldSession* m_session)
{
uint32 instanceId = (args ? atoi(args) : 0);
if (instanceId == 0)
return false;
Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
if (instance == NULL)
{
RedSystemMessage(m_session, "There's no instance with id %u.", instanceId);
return true;
}
if (instance->m_mapMgr == NULL)
{
RedSystemMessage(m_session, "Instance with id %u already shut down.", instanceId);
return true;
}
SystemMessage(m_session, "Attempting to shutdown instance with id %u...", instanceId);
sInstanceMgr.SafeDeleteInstance(instance->m_mapMgr);
instance = NULL;
SystemMessage(m_session, "...done");
sGMLog.writefromsession(m_session, "used shutdown instance command on instance %u,", instanceId);
return true;
}
//bool ChatHandler::HandleDeleteInstanceCommand(const char* args, WorldSession* m_session)
//{
// RedSystemMessage(m_session, "Command not implemented yet.");
// return true;
// //sGMLog.writefromsession(m_session, "used delete instance command on instance %u,", 0);
//}
bool ChatHandler::HandleGetInstanceInfoCommand(const char* args, WorldSession* m_session)
{
Player* plr = m_session->GetPlayer();
if (plr == NULL)
return false;
bool userInput = true;
uint32 instanceId = (args ? atoi(args) : 0);
if (instanceId == 0)
{
userInput = false;
instanceId = plr->GetInstanceID();
if (instanceId == 0)
return false;
}
Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
if (instance == NULL)
{
if (userInput)
{
RedSystemMessage(m_session, "Instance with id %u not found.", instanceId);
return true;
}
return false;
}
std::stringstream ss;
ss << "Instance ID: " << MSG_COLOR_CYAN << instance->m_instanceId << "|r (" << MSG_COLOR_CYAN;
if (instance->m_mapInfo == NULL)
ss << instance->m_mapId;
else
ss << instance->m_mapInfo->name;
ss << "|r)\n";
ss << "Persistent: " << MSG_COLOR_CYAN << (instance->m_persistent ? "Yes" : "No") << "|r\n";
if (instance->m_mapInfo != NULL)
{
ss << "Type: " << MSG_COLOR_CYAN << GetMapTypeString(static_cast<uint8>(instance->m_mapInfo->type)) << "|r";
if (instance->m_mapInfo->type == INSTANCE_MULTIMODE)
{
ss << " (" << MSG_COLOR_CYAN << GetDifficultyString(static_cast<uint8>(instance->m_difficulty)) << "|r)";
}
if (instance->m_mapInfo->type == INSTANCE_RAID)
{
ss << " (" << MSG_COLOR_CYAN << GetRaidDifficultyString(static_cast<uint8>(instance->m_difficulty)) << "|r)";
}
ss << "\n";
}
ss << "Created: " << MSG_COLOR_CYAN << ConvertTimeStampToDataTime((uint32)instance->m_creation) << "|r\n";
if (instance->m_expiration != 0)
ss << "Expires: " << MSG_COLOR_CYAN << ConvertTimeStampToDataTime((uint32)instance->m_expiration) << "|r\n";
if (instance->m_mapMgr == NULL)
{
ss << "Status: " << MSG_COLOR_LIGHTRED << "Shut Down|r\n";
}
else if (!instance->m_mapMgr->HasPlayers())
{
ss << "Status: " << MSG_COLOR_LIGHTRED << "Idle|r";
if (instance->m_mapMgr->InactiveMoveTime && instance->m_mapMgr->GetMapInfo()->type != INSTANCE_NULL)
ss << " (" << MSG_COLOR_CYAN << "Shutdown in " << MSG_COLOR_LIGHTRED << (((long)instance->m_mapMgr->InactiveMoveTime - UNIXTIME) / 60) << MSG_COLOR_CYAN << " minutes|r)";
ss << "\n";
}
else
{
ss << "Status: " << MSG_COLOR_GREEN << "In use|r (" << MSG_COLOR_GREEN << (uint32)instance->m_mapMgr->GetPlayerCount() << MSG_COLOR_CYAN << " players inside|r)\n";
}
SendMultilineMessage(m_session, ss.str().c_str());
return true;
}
bool ChatHandler::HandleCreateInstanceCommand(const char* args, WorldSession* m_session)
{
Player* plr = getSelectedChar(m_session, true);
float x, y, z;
uint32 mapid;
if (sscanf(args, "%u %f %f %f", (unsigned int*)&mapid, &x, &y, &z) != 4)
return false;
if (!plr)
{
plr = m_session->GetPlayer();
SystemMessage(m_session, "Auto-targeting self.");
}
if (!plr) return false;
/* Create Map Manager */
MapMgr* mgr = sInstanceMgr.CreateInstance(INSTANCE_NONRAID, mapid);
if (mgr == NULL)
{
sLog.Error("CreateInstanceGMCommand", "CreateInstance() call failed for map %u", mapid);
return false; // Shouldn't happen
}
Log.Notice("CreateInstanceGMCommand", "GM created instance for map %u", mapid);
LocationVector vec(x, y, z);
m_session->GetPlayer()->SafeTeleport(mgr, vec);
return true;
}
bool ChatHandler::HandleExitInstanceCommand(const char* args, WorldSession* m_session)
{
BlueSystemMessage(m_session, "Attempting to exit from instance...");
bool result = m_session->GetPlayer()->ExitInstance();
if (!result)
{
RedSystemMessage(m_session, "Entry points not found.");
return true;
}
else
{
GreenSystemMessage(m_session, "Removal successful.");
return true;
}
}
bool ChatHandler::HandleShowInstancesCommand(const char* args, WorldSession* m_session)
{
Player* plr = getSelectedChar(m_session, true);
if (!plr)
return true;
uint32 count = 0;
std::stringstream ss;
ss << "Show persistent instances of " << MSG_COLOR_CYAN << plr->GetName() << "|r\n";
plr->getPlayerInfo()->savedInstanceIdsLock.Acquire();
for (uint32 difficulty = 0; difficulty < NUM_INSTANCE_MODES; difficulty++)
{
for (PlayerInstanceMap::iterator itr = plr->getPlayerInfo()->savedInstanceIds[difficulty].begin(); itr != plr->getPlayerInfo()->savedInstanceIds[difficulty].end(); ++itr)
{
count++;
ss << " - " << MSG_COLOR_CYAN << (*itr).second << "|r";
MapInfo* mapInfo = WorldMapInfoStorage.LookupEntry((*itr).first);
if (mapInfo != NULL)
ss << " (" << MSG_COLOR_CYAN << mapInfo->name << "|r)";
Instance* pInstance = sInstanceMgr.GetInstanceByIds((*itr).first, (*itr).second);
if (pInstance == NULL)
ss << " - " << MSG_COLOR_RED << "Expired!|r";
else
{
ss << " [" << GetMapTypeString(static_cast<uint8>(pInstance->m_mapInfo->type)) << "]";
if (pInstance->m_mapInfo->type == INSTANCE_MULTIMODE)
{
ss << " [" << GetDifficultyString(static_cast<uint8>(pInstance->m_difficulty)) << "]";
}
ss << " - ";
if (pInstance->m_mapMgr == NULL)
ss << MSG_COLOR_LIGHTRED << "Shut Down|r";
else
{
if (!pInstance->m_mapMgr->HasPlayers())
ss << MSG_COLOR_LIGHTRED << "Idle|r";
else
ss << MSG_COLOR_GREEN << "In use|r";
}
}
ss << "\n";
}
}
plr->getPlayerInfo()->savedInstanceIdsLock.Release();
if (count == 0)
ss << "Player is not assigned to any persistent instances.\n";
else
ss << "Player is assigned to " << MSG_COLOR_CYAN << count << "|r persistent instances.\n";
SendMultilineMessage(m_session, ss.str().c_str());
sGMLog.writefromsession(m_session, "used show instances command on %s,", plr->GetName());
return true;
}
<commit_msg>Dereference after null check CID 52655 (InstanceCommands.cpp): sInstanceMgr.DeleteBattlegroundInstance calls InstanceShutdown. No need to call it twice.<commit_after>/*
* AscEmu Framework based on ArcEmu MMORPG Server
* Copyright (C) 2014-2015 AscEmu Team <http://www.ascemu.org/>
* Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
* Copyright (C) 2005-2007 Ascent Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
const char* GetDifficultyString(uint8 difficulty)
{
switch (difficulty)
{
case MODE_NORMAL:
return "normal";
case MODE_HEROIC:
return "heroic";
default:
return "unknown";
}
}
const char* GetRaidDifficultyString(uint8 diff)
{
switch (diff)
{
case MODE_NORMAL_10MEN:
return "normal 10men";
case MODE_NORMAL_25MEN:
return "normal 25men";
case MODE_HEROIC_10MEN:
return "heroic 10men";
case MODE_HEROIC_25MEN:
return "heroic 25men";
default:
return "unknown";
}
}
const char* GetMapTypeString(uint8 type)
{
switch (type)
{
case INSTANCE_NULL:
return "Continent";
case INSTANCE_RAID:
return "Raid";
case INSTANCE_NONRAID:
return "Non-Raid";
case INSTANCE_BATTLEGROUND:
return "PvP";
case INSTANCE_MULTIMODE:
return "MultiMode";
default:
return "Unknown";
}
}
bool ChatHandler::HandleResetAllInstancesCommand(const char* args, WorldSession* m_session)
{
Player* plr;
if (strlen(args) == 0)
plr = getSelectedChar(m_session, true);
else
plr = objmgr.GetPlayer(args, false);;
if (!plr)
{
RedSystemMessage(m_session, "Player not found");
return true;
}
SystemMessage(m_session, "Trying to reset all instances of player %s...", plr->GetName());
sInstanceMgr.ResetSavedInstances(plr);
SystemMessage(m_session, "...done");
sGMLog.writefromsession(m_session, "used reset all instances command on %s,", plr->GetName());
return true;
}
bool ChatHandler::HandleResetInstanceCommand(const char* args, WorldSession* m_session)
{
uint32 instanceId;
int argc = 1;
char* playername = NULL;
char* guidString = (char*)args;
// Parse arguments
char* space = (char*)strchr(args, ' ');
if (space)
{
*space = '\0';
playername = space + 1;
argc = 2;
}
instanceId = atoi(guidString);
if (!instanceId)
{
RedSystemMessage(m_session, "You must specify an instance id.");
return true;
}
Player* plr;
if (argc == 1)
plr = getSelectedChar(m_session, true);
else
plr = objmgr.GetPlayer((const char*)playername, false);;
if (!plr)
{
RedSystemMessage(m_session, "Player not found");
return true;
}
Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
if (instance == NULL)
{
RedSystemMessage(m_session, "There's no instance with id %u.", instanceId);
return true;
}
if (IS_PERSISTENT_INSTANCE(instance))
{
if (m_session->CanUseCommand('z'))
{
bool foundSomething = false;
plr->getPlayerInfo()->savedInstanceIdsLock.Acquire();
for (uint32 difficulty = 0; difficulty < NUM_INSTANCE_MODES; difficulty++)
{
PlayerInstanceMap::iterator itr = plr->getPlayerInfo()->savedInstanceIds[difficulty].find(instance->m_mapId);
if (itr == plr->getPlayerInfo()->savedInstanceIds[difficulty].end() || (*itr).second != instance->m_instanceId)
continue;
plr->SetPersistentInstanceId(instance->m_mapId, difficulty, 0);
SystemMessage(m_session, "Instance with id %u (%s) is persistent and will only be revoked from player.", instanceId, GetDifficultyString(static_cast<uint8>(difficulty)));
foundSomething = true;
}
plr->getPlayerInfo()->savedInstanceIdsLock.Release();
if (!foundSomething)
RedSystemMessage(m_session, "Player is not assigned to persistent instance with id %u.", instanceId);
return true;
}
else
{
RedSystemMessage(m_session, "Instance with id %u is persistent and can only be removed from player by admins.", instanceId);
return true;
}
}
if (instance->m_mapMgr && instance->m_mapMgr->HasPlayers())
{
RedSystemMessage(m_session, "Failed to reset non-persistent instance with id %u, due to player still inside.", instanceId);
return true;
}
if (instance->m_creatorGroup)
{
Group* group = plr->GetGroup();
if (group == NULL || instance->m_creatorGroup != group->GetID())
{
RedSystemMessage(m_session, "Player %s is not a member of the group assigned to the non-persistent instance with id %u.", plr->GetName(), instanceId);
return true;
}
}
else if (instance->m_creatorGuid == 0 || instance->m_creatorGuid != plr->GetLowGUID())
{
RedSystemMessage(m_session, "Player %s is not assigned to instance with id %u.", plr->GetName(), instanceId);
return true;
}
// tell player the instance was reset
WorldPacket data(SMSG_INSTANCE_RESET, 4);
data << instance->m_mapId;
plr->GetSession()->SendPacket(&data);
// shut down instance
sInstanceMgr.DeleteBattlegroundInstance(instance->m_mapId, instance->m_instanceId);
// RedSystemMessage(m_session, "Resetting single non-persistent instances is not available yet.");
sGMLog.writefromsession(m_session, "used reset instance command on %s, instance %u,", plr->GetName(), instanceId);
return true;
}
bool ChatHandler::HandleShutdownInstanceCommand(const char* args, WorldSession* m_session)
{
uint32 instanceId = (args ? atoi(args) : 0);
if (instanceId == 0)
return false;
Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
if (instance == NULL)
{
RedSystemMessage(m_session, "There's no instance with id %u.", instanceId);
return true;
}
if (instance->m_mapMgr == NULL)
{
RedSystemMessage(m_session, "Instance with id %u already shut down.", instanceId);
return true;
}
SystemMessage(m_session, "Attempting to shutdown instance with id %u...", instanceId);
sInstanceMgr.SafeDeleteInstance(instance->m_mapMgr);
instance = NULL;
SystemMessage(m_session, "...done");
sGMLog.writefromsession(m_session, "used shutdown instance command on instance %u,", instanceId);
return true;
}
//bool ChatHandler::HandleDeleteInstanceCommand(const char* args, WorldSession* m_session)
//{
// RedSystemMessage(m_session, "Command not implemented yet.");
// return true;
// //sGMLog.writefromsession(m_session, "used delete instance command on instance %u,", 0);
//}
bool ChatHandler::HandleGetInstanceInfoCommand(const char* args, WorldSession* m_session)
{
Player* plr = m_session->GetPlayer();
if (plr == NULL)
return false;
bool userInput = true;
uint32 instanceId = (args ? atoi(args) : 0);
if (instanceId == 0)
{
userInput = false;
instanceId = plr->GetInstanceID();
if (instanceId == 0)
return false;
}
Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
if (instance == NULL)
{
if (userInput)
{
RedSystemMessage(m_session, "Instance with id %u not found.", instanceId);
return true;
}
return false;
}
std::stringstream ss;
ss << "Instance ID: " << MSG_COLOR_CYAN << instance->m_instanceId << "|r (" << MSG_COLOR_CYAN;
if (instance->m_mapInfo == NULL)
ss << instance->m_mapId;
else
ss << instance->m_mapInfo->name;
ss << "|r)\n";
ss << "Persistent: " << MSG_COLOR_CYAN << (instance->m_persistent ? "Yes" : "No") << "|r\n";
if (instance->m_mapInfo != NULL)
{
ss << "Type: " << MSG_COLOR_CYAN << GetMapTypeString(static_cast<uint8>(instance->m_mapInfo->type)) << "|r";
if (instance->m_mapInfo->type == INSTANCE_MULTIMODE)
{
ss << " (" << MSG_COLOR_CYAN << GetDifficultyString(static_cast<uint8>(instance->m_difficulty)) << "|r)";
}
if (instance->m_mapInfo->type == INSTANCE_RAID)
{
ss << " (" << MSG_COLOR_CYAN << GetRaidDifficultyString(static_cast<uint8>(instance->m_difficulty)) << "|r)";
}
ss << "\n";
}
ss << "Created: " << MSG_COLOR_CYAN << ConvertTimeStampToDataTime((uint32)instance->m_creation) << "|r\n";
if (instance->m_expiration != 0)
ss << "Expires: " << MSG_COLOR_CYAN << ConvertTimeStampToDataTime((uint32)instance->m_expiration) << "|r\n";
if (instance->m_mapMgr == NULL)
{
ss << "Status: " << MSG_COLOR_LIGHTRED << "Shut Down|r\n";
}
else if (!instance->m_mapMgr->HasPlayers())
{
ss << "Status: " << MSG_COLOR_LIGHTRED << "Idle|r";
if (instance->m_mapMgr->InactiveMoveTime && instance->m_mapMgr->GetMapInfo()->type != INSTANCE_NULL)
ss << " (" << MSG_COLOR_CYAN << "Shutdown in " << MSG_COLOR_LIGHTRED << (((long)instance->m_mapMgr->InactiveMoveTime - UNIXTIME) / 60) << MSG_COLOR_CYAN << " minutes|r)";
ss << "\n";
}
else
{
ss << "Status: " << MSG_COLOR_GREEN << "In use|r (" << MSG_COLOR_GREEN << (uint32)instance->m_mapMgr->GetPlayerCount() << MSG_COLOR_CYAN << " players inside|r)\n";
}
SendMultilineMessage(m_session, ss.str().c_str());
return true;
}
bool ChatHandler::HandleCreateInstanceCommand(const char* args, WorldSession* m_session)
{
Player* plr = getSelectedChar(m_session, true);
float x, y, z;
uint32 mapid;
if (sscanf(args, "%u %f %f %f", (unsigned int*)&mapid, &x, &y, &z) != 4)
return false;
if (!plr)
{
plr = m_session->GetPlayer();
SystemMessage(m_session, "Auto-targeting self.");
}
if (!plr) return false;
/* Create Map Manager */
MapMgr* mgr = sInstanceMgr.CreateInstance(INSTANCE_NONRAID, mapid);
if (mgr == NULL)
{
sLog.Error("CreateInstanceGMCommand", "CreateInstance() call failed for map %u", mapid);
return false; // Shouldn't happen
}
Log.Notice("CreateInstanceGMCommand", "GM created instance for map %u", mapid);
LocationVector vec(x, y, z);
m_session->GetPlayer()->SafeTeleport(mgr, vec);
return true;
}
bool ChatHandler::HandleExitInstanceCommand(const char* args, WorldSession* m_session)
{
BlueSystemMessage(m_session, "Attempting to exit from instance...");
bool result = m_session->GetPlayer()->ExitInstance();
if (!result)
{
RedSystemMessage(m_session, "Entry points not found.");
return true;
}
else
{
GreenSystemMessage(m_session, "Removal successful.");
return true;
}
}
bool ChatHandler::HandleShowInstancesCommand(const char* args, WorldSession* m_session)
{
Player* plr = getSelectedChar(m_session, true);
if (!plr)
return true;
uint32 count = 0;
std::stringstream ss;
ss << "Show persistent instances of " << MSG_COLOR_CYAN << plr->GetName() << "|r\n";
plr->getPlayerInfo()->savedInstanceIdsLock.Acquire();
for (uint32 difficulty = 0; difficulty < NUM_INSTANCE_MODES; difficulty++)
{
for (PlayerInstanceMap::iterator itr = plr->getPlayerInfo()->savedInstanceIds[difficulty].begin(); itr != plr->getPlayerInfo()->savedInstanceIds[difficulty].end(); ++itr)
{
count++;
ss << " - " << MSG_COLOR_CYAN << (*itr).second << "|r";
MapInfo* mapInfo = WorldMapInfoStorage.LookupEntry((*itr).first);
if (mapInfo != NULL)
ss << " (" << MSG_COLOR_CYAN << mapInfo->name << "|r)";
Instance* pInstance = sInstanceMgr.GetInstanceByIds((*itr).first, (*itr).second);
if (pInstance == NULL)
ss << " - " << MSG_COLOR_RED << "Expired!|r";
else
{
ss << " [" << GetMapTypeString(static_cast<uint8>(pInstance->m_mapInfo->type)) << "]";
if (pInstance->m_mapInfo->type == INSTANCE_MULTIMODE)
{
ss << " [" << GetDifficultyString(static_cast<uint8>(pInstance->m_difficulty)) << "]";
}
ss << " - ";
if (pInstance->m_mapMgr == NULL)
ss << MSG_COLOR_LIGHTRED << "Shut Down|r";
else
{
if (!pInstance->m_mapMgr->HasPlayers())
ss << MSG_COLOR_LIGHTRED << "Idle|r";
else
ss << MSG_COLOR_GREEN << "In use|r";
}
}
ss << "\n";
}
}
plr->getPlayerInfo()->savedInstanceIdsLock.Release();
if (count == 0)
ss << "Player is not assigned to any persistent instances.\n";
else
ss << "Player is assigned to " << MSG_COLOR_CYAN << count << "|r persistent instances.\n";
SendMultilineMessage(m_session, ss.str().c_str());
sGMLog.writefromsession(m_session, "used show instances command on %s,", plr->GetName());
return true;
}
<|endoftext|>
|
<commit_before>#include <world/world.hpp>
#include <limits>
#include <cstring>
namespace MCPP {
Vector<Byte> ColumnContainer::ToChunkData (const ColumnID & id) const {
// First we need to convert the sane
// in memory format to the insane
// Mojang format
Word size=(
// One byte per block
// for block type
(16*16*16*16)+
// Half a byte per block
// for metadata
((16*16*16*16)/2)+
// Half a byte per block
// for light
((16*16*16*16)/2)+
// One byte per column for
// biome information
(16*16)
);
// Do we have to send "add"?
bool add=false;
for (Word i=0;i<(16*16*16*16);++i) {
if (Blocks[i].GetType()>std::numeric_limits<Byte>::max()) {
add=true;
break;
}
}
// If we have to send add it's
// one half byte per block
if (add) size+=(16*16*16*16)/2;
// If we have to send skylight it's
// one half byte per block
bool skylight=HasSkylight(id.Dimension);
if (skylight) size+=(16*16*16*16)/2;
// Allocate enough space to hold
// the column in Mojang format
Vector<Byte> column(size);
column.SetCount(size);
Word offset=0;
// Loop for block types
for (const auto & b : Blocks) column[offset++]=static_cast<Byte>(b.GetType());
// Loop for block metadata
bool even=true;
for (const auto & b : Blocks) {
if (even) {
column[offset]=b.GetMetadata()<<4;
even=false;
} else {
column[offset++]|=b.GetMetadata();
even=true;
}
}
// Loop for light
even=true;
for (const auto & b : Blocks) {
if (even) {
column[offset]=b.GetLight()<<4;
even=false;
} else {
column[offset++]|=b.GetLight();
even=true;
}
}
// Loop for skylight if applicable
if (skylight) {
even=true;
for (const auto & b : Blocks) {
if (even) {
column[offset]=b.GetSkylight()<<4;
even=false;
} else {
column[offset++]|=b.GetSkylight();
even=true;
}
}
}
// Loop for "add" if applicable
if (add) {
even=true;
for (const auto & b : Blocks) {
auto type=b.GetType();
Byte val=(type>std::numeric_limits<Byte>::max()) ? static_cast<Byte>(type>>8) : 0;
if (even) {
column[offset]=val<<4;
even=false;
} else {
column[offset++]|=val;
even=true;
}
}
}
// Copy biomes
memcpy(
&column[offset],
Biomes,
sizeof(Biomes)
);
// Prepare the final buffer
size=(
// X-coordinate of this chunk
sizeof(Int32)+
// Z-coordinate of this chunk
sizeof(Int32)+
// Group-up continuous
sizeof(bool)+
// Primary bit mask
sizeof(UInt16)+
// "Add" bit mask
sizeof(UInt16)+
// Size of compressed data
sizeof(Int32)+
// Largest possible size for
// compressed column data
DeflateBound(
column.Count()
)
);
// Allocate sufficient memory
Vector<Byte> buffer(size);
PacketHelper<Int32>::ToBytes(
id.X,
buffer
);
PacketHelper<Int32>::ToBytes(
id.Z,
buffer
);
PacketHelper<bool>::ToBytes(
true,
buffer
);
PacketHelper<UInt16>::ToBytes(
std::numeric_limits<UInt16>::max(),
buffer
);
PacketHelper<UInt16>::ToBytes(
std::numeric_limits<UInt16>::max(),
buffer
);
// Push end point of buffer past
// where the size will go
// (as we do not yet know the size)
Word size_loc=buffer.Count();
buffer.SetCount(size_loc+sizeof(Int32));
// Compress
Deflate(
column.begin(),
column.end(),
&buffer
);
// Get compressed size
SafeWord compressed_size(buffer.Count()-size_loc-sizeof(Int32));
Word final_size=buffer.Count();
// Insert compressed size
buffer.SetCount(size_loc);
PacketHelper<Int32>::ToBytes(
Int32(compressed_size),
buffer
);
buffer.SetCount(final_size);
return buffer;
}
}
<commit_msg>ColumnContainer Bugfix<commit_after>#include <world/world.hpp>
#include <limits>
#include <cstring>
namespace MCPP {
Vector<Byte> ColumnContainer::ToChunkData (const ColumnID & id) const {
// First we need to convert the sane
// in memory format to the insane
// Mojang format
Word size=(
// One byte per block
// for block type
(16*16*16*16)+
// Half a byte per block
// for metadata
((16*16*16*16)/2)+
// Half a byte per block
// for light
((16*16*16*16)/2)+
// One byte per column for
// biome information
(16*16)
);
// Do we have to send "add"?
bool add=false;
for (Word i=0;i<(16*16*16*16);++i) {
if (Blocks[i].GetType()>std::numeric_limits<Byte>::max()) {
add=true;
break;
}
}
// If we have to send add it's
// one half byte per block
if (add) size+=(16*16*16*16)/2;
// If we have to send skylight it's
// one half byte per block
bool skylight=HasSkylight(id.Dimension);
if (skylight) size+=(16*16*16*16)/2;
// Allocate enough space to hold
// the column in Mojang format
Vector<Byte> column(size);
column.SetCount(size);
Word offset=0;
// Loop for block types
for (const auto & b : Blocks) column[offset++]=static_cast<Byte>(b.GetType());
// Loop for block metadata
bool even=true;
for (const auto & b : Blocks) {
if (even) {
column[offset]=b.GetMetadata()<<4;
even=false;
} else {
column[offset++]|=b.GetMetadata();
even=true;
}
}
// Loop for light
even=true;
for (const auto & b : Blocks) {
if (even) {
column[offset]=b.GetLight()<<4;
even=false;
} else {
column[offset++]|=b.GetLight();
even=true;
}
}
// Loop for skylight if applicable
if (skylight) {
even=true;
for (const auto & b : Blocks) {
if (even) {
column[offset]=b.GetSkylight()<<4;
even=false;
} else {
column[offset++]|=b.GetSkylight();
even=true;
}
}
}
// Loop for "add" if applicable
if (add) {
even=true;
for (const auto & b : Blocks) {
auto type=b.GetType();
Byte val=(type>std::numeric_limits<Byte>::max()) ? static_cast<Byte>(type>>8) : 0;
if (even) {
column[offset]=val<<4;
even=false;
} else {
column[offset++]|=val;
even=true;
}
}
}
// Copy biomes
memcpy(
&column[offset],
Biomes,
sizeof(Biomes)
);
// Prepare the final buffer
size=(
// Packet type
sizeof(Byte)+
// X-coordinate of this chunk
sizeof(Int32)+
// Z-coordinate of this chunk
sizeof(Int32)+
// Group-up continuous
sizeof(bool)+
// Primary bit mask
sizeof(UInt16)+
// "Add" bit mask
sizeof(UInt16)+
// Size of compressed data
sizeof(Int32)+
// Largest possible size for
// compressed column data
DeflateBound(
column.Count()
)
);
// Allocate sufficient memory
Vector<Byte> buffer(size);
buffer.Add(0x33);
PacketHelper<Int32>::ToBytes(
id.X,
buffer
);
PacketHelper<Int32>::ToBytes(
id.Z,
buffer
);
PacketHelper<bool>::ToBytes(
true,
buffer
);
PacketHelper<UInt16>::ToBytes(
std::numeric_limits<UInt16>::max(),
buffer
);
PacketHelper<UInt16>::ToBytes(
std::numeric_limits<UInt16>::max(),
buffer
);
// Push end point of buffer past
// where the size will go
// (as we do not yet know the size)
Word size_loc=buffer.Count();
buffer.SetCount(size_loc+sizeof(Int32));
// Compress
Deflate(
column.begin(),
column.end(),
&buffer
);
// Get compressed size
SafeWord compressed_size(buffer.Count()-size_loc-sizeof(Int32));
Word final_size=buffer.Count();
// Insert compressed size
buffer.SetCount(size_loc);
PacketHelper<Int32>::ToBytes(
Int32(compressed_size),
buffer
);
buffer.SetCount(final_size);
return buffer;
}
}
<|endoftext|>
|
<commit_before>#include <x0/io/fileinfo_service.hpp>
#include <x0/strutils.hpp>
#include <boost/tokenizer.hpp>
namespace x0 {
fileinfo_service::fileinfo_service(struct ::ev_loop *loop) :
loop_(loop),
#if defined(HAVE_SYS_INOTIFY_H)
handle_(),
inotify_(loop_),
wd_(),
#endif
cache_(),
etag_consider_mtime_(true),
etag_consider_size_(true),
etag_consider_inode_(false),
mimetypes_(),
default_mimetype_("text/plain")
{
#if defined(HAVE_SYS_INOTIFY_H)
handle_ = inotify_init();
if (handle_ != -1)
{
fcntl(handle_, F_SETFL, O_NONBLOCK | FD_CLOEXEC);
inotify_.set<fileinfo_service, &fileinfo_service::on_inotify>(this);
inotify_.start(handle_, ev::READ);
}
#endif
}
fileinfo_service::~fileinfo_service()
{
#if defined(HAVE_SYS_INOTIFY_H)
if (handle_ != -1)
{
::close(handle_);
}
#endif
}
void fileinfo_service::on_inotify(ev::io& w, int revents)
{
DEBUG("fileinfo_service::on_inotify()");
char buf[4096];
ssize_t rv = ::read(handle_, &buf, sizeof(buf));
if (rv > 0)
{
inotify_event *i = (inotify_event *)buf;
inotify_event *e = i + rv;
while (i < e && i->wd != 0)
{
auto wi = wd_.find(i->wd);
if (wi != wd_.end())
{
auto k = cache_.find(wi->second);
// on_invalidate(k->first, k->second);
cache_.erase(k);
wd_.erase(wi);
}
i += sizeof(*i) + i->len;
}
}
}
void fileinfo_service::load_mimetypes(const std::string& filename)
{
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
std::string input(x0::read_file(filename));
tokenizer lines(input, boost::char_separator<char>("\n"));
mimetypes_.clear();
for (tokenizer::iterator i = lines.begin(), e = lines.end(); i != e; ++i)
{
std::string line(x0::trim(*i));
tokenizer columns(line, boost::char_separator<char>(" \t"));
tokenizer::iterator ci = columns.begin(), ce = columns.end();
std::string mime = ci != ce ? *ci++ : std::string();
if (!mime.empty() && mime[0] != '#')
{
for (; ci != ce; ++ci)
{
mimetypes_[*ci] = mime;
}
}
}
}
} // namespace x0
<commit_msg>core: code cleanup<commit_after>#include <x0/io/fileinfo_service.hpp>
#include <x0/strutils.hpp>
#include <boost/tokenizer.hpp>
namespace x0 {
fileinfo_service::fileinfo_service(struct ::ev_loop *loop) :
loop_(loop),
#if defined(HAVE_SYS_INOTIFY_H)
handle_(),
inotify_(loop_),
wd_(),
#endif
cache_(),
etag_consider_mtime_(true),
etag_consider_size_(true),
etag_consider_inode_(false),
mimetypes_(),
default_mimetype_("text/plain")
{
#if defined(HAVE_SYS_INOTIFY_H)
handle_ = inotify_init();
if (handle_ != -1)
{
fcntl(handle_, F_SETFL, O_NONBLOCK | FD_CLOEXEC);
inotify_.set<fileinfo_service, &fileinfo_service::on_inotify>(this);
inotify_.start(handle_, ev::READ);
}
#endif
}
fileinfo_service::~fileinfo_service()
{
#if defined(HAVE_SYS_INOTIFY_H)
if (handle_ != -1)
{
::close(handle_);
}
#endif
}
void fileinfo_service::on_inotify(ev::io& w, int revents)
{
//DEBUG("fileinfo_service::on_inotify()");
char buf[4096];
ssize_t rv = ::read(handle_, &buf, sizeof(buf));
if (rv > 0)
{
inotify_event *i = (inotify_event *)buf;
inotify_event *e = i + rv;
while (i < e && i->wd != 0)
{
auto wi = wd_.find(i->wd);
if (wi != wd_.end())
{
auto k = cache_.find(wi->second);
// on_invalidate(k->first, k->second);
cache_.erase(k);
wd_.erase(wi);
}
i += sizeof(*i) + i->len;
}
}
}
void fileinfo_service::load_mimetypes(const std::string& filename)
{
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
std::string input(x0::read_file(filename));
tokenizer lines(input, boost::char_separator<char>("\n"));
mimetypes_.clear();
for (tokenizer::iterator i = lines.begin(), e = lines.end(); i != e; ++i)
{
std::string line(x0::trim(*i));
tokenizer columns(line, boost::char_separator<char>(" \t"));
tokenizer::iterator ci = columns.begin(), ce = columns.end();
std::string mime = ci != ce ? *ci++ : std::string();
if (!mime.empty() && mime[0] != '#')
{
for (; ci != ce; ++ci)
{
mimetypes_[*ci] = mime;
}
}
}
}
} // namespace x0
<|endoftext|>
|
<commit_before>#include <vector>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <Windows.h>
char appplication_folder[1024];
void set_application_folder( char const* application_path )
{
int length = strrchr( application_path, '\\' ) - application_path + 1;
memcpy( appplication_folder, application_path, length );
appplication_folder[length] = 0;
}
char const* get_application_folder()
{
return appplication_folder;
}
BOOL run( char* command_line )
{
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
BOOL result = CreateProcess( 0, command_line, 0, 0, FALSE, 0, NULL, NULL, &si, &pi );
if( !result )
{
printf( "ERROR: Could not run '%s'!\n", command_line );
return -1;
}
else
{
WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return 0;
}
}
struct compiler
{
compiler( char const* compiler_path )
: path( compiler_path )
{
int ext_begin = strrchr(compiler_path, '\\') - compiler_path + 1;
int ext_end = strrchr(compiler_path, '.') - compiler_path - ext_begin;
extension = path.substr(ext_begin, ext_end);
}
void compile( char const* asset_path, char const* output_folder )
{
char command_line[1024];
sprintf( command_line, "%s \"%s\" \"%s\"", path.c_str(), asset_path, output_folder );
run( command_line );
}
std::string extension;
std::string path;
};
typedef std::vector< std::string > file_list;
typedef std::vector< compiler* > compiler_list;
void list_files( char const* folder, char const* extension, file_list& files )
{
char search_key[1024];
sprintf( search_key, "%s\\*", folder, extension );
WIN32_FIND_DATA find_data;
HANDLE find_handle = FindFirstFile( search_key, &find_data );
if( find_handle != INVALID_HANDLE_VALUE )
{
do
{
if( strstr( find_data.cFileName, extension ) && strlen( strstr( find_data.cFileName, extension ) ) == strlen( extension ) )
{
char file_path[1024];
sprintf( file_path, "%s\\%s", folder, find_data.cFileName );
files.push_back( file_path );
}
else if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( find_data.cFileName[0] != '.' )
{
char subfolder[2048];
sprintf( subfolder, "%s\\%s", folder, find_data.cFileName );
list_files( subfolder, extension, files );
}
}
}while( FindNextFile( find_handle, &find_data ) );
}
}
void list_folders( char const* path, file_list& folders )
{
char search_key[1024];
sprintf( search_key, "%s\\*", path );
WIN32_FIND_DATA find_data;
HANDLE find_handle = FindFirstFile( search_key, &find_data );
if( find_handle != INVALID_HANDLE_VALUE )
{
do
{
if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( find_data.cFileName[0] != '.' )
{
char subfolder[2048];
sprintf( subfolder, "%s\\%s", path, find_data.cFileName );
folders.push_back( subfolder );
}
}
}while( FindNextFile( find_handle, &find_data ) );
}
}
compiler_list get_compilers( char const* folder )
{
file_list paths;
list_files( folder, "exe", paths );
compiler_list compilers;
for( file_list::iterator iter = paths.begin(); iter != paths.end(); ++iter )
{
char const* path = (*iter).c_str();
compilers.push_back( new compiler( path ) );
}
return compilers;
}
void compile_folder( compiler* c, char const* asset_folder, char const* mod_folder )
{
file_list files;
list_files( asset_folder, c->extension.c_str(), files );
for( file_list::iterator file_iter = files.begin(); file_iter != files.end(); ++file_iter )
{
c->compile( file_iter->c_str(), mod_folder );
}
}
void get_asset_folders( compiler& c, file_list& asset_folders )
{
std::string asset_list_path = c.path + std::string( ".txt" );
std::ifstream in = std::ifstream( asset_list_path.c_str() );
char path[1024];
while( !in.eof() )
{
in.getline( path, sizeof( path ) );
asset_folders.push_back( path );
}
}
int main( int argument_count, char** arguments )
{
char module_name[1024];
GetModuleFileName( 0, module_name, 1024 );
set_application_folder( module_name );
file_list mod_folders;
char mods_folder[1024];
sprintf( mods_folder, "%s..\\..\\mods", get_application_folder() );
list_folders( mods_folder, mod_folders );
sprintf( mods_folder, "%s..\\..\\dont_starve\\mods", get_application_folder() );
list_folders( mods_folder, mod_folders );
char compilers_folder[1024] ;
sprintf( compilers_folder, "%scompilers", get_application_folder() );
compiler_list compilers = get_compilers( compilers_folder );
for( compiler_list::iterator iter = compilers.begin(); iter != compilers.end(); ++iter )
{
compiler* c = *iter;
file_list asset_folders;
get_asset_folders( *c, asset_folders );
for( file_list::iterator mod_folder_iter = mod_folders.begin(); mod_folder_iter != mod_folders.end(); ++mod_folder_iter )
{
for( file_list::iterator asset_folder_iter = asset_folders.begin(); asset_folder_iter != asset_folders.end(); ++asset_folder_iter )
{
char asset_folder[1024];
sprintf( asset_folder, "%s/%s", mod_folder_iter->c_str(), asset_folder_iter->c_str() );
compile_folder( c, asset_folder, mod_folder_iter->c_str() );
}
}
}
return 0;
}<commit_msg>Removed some dependencies on 'Windows.h'.<commit_after>#include <vector>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <Windows.h>
char appplication_folder[1024];
void set_application_folder( char const* application_path )
{
int length = strrchr( application_path, '\\' ) - application_path + 1;
memcpy( appplication_folder, application_path, length );
appplication_folder[length] = 0;
}
char const* get_application_folder()
{
return appplication_folder;
}
bool run( char* command_line )
{
return system( command_line ) == 0;
}
struct compiler
{
compiler( char const* compiler_path )
: path( compiler_path )
{
int ext_begin = strrchr(compiler_path, '\\') - compiler_path + 1;
int ext_end = strrchr(compiler_path, '.') - compiler_path - ext_begin;
extension = path.substr(ext_begin, ext_end);
}
void compile( char const* asset_path, char const* output_folder )
{
char command_line[1024];
sprintf( command_line, "%s \"%s\" \"%s\"", path.c_str(), asset_path, output_folder );
run( command_line );
}
std::string extension;
std::string path;
};
typedef std::vector< std::string > file_list;
typedef std::vector< compiler* > compiler_list;
void list_files( char const* folder, char const* extension, file_list& files )
{
char search_key[1024];
sprintf( search_key, "%s\\*", folder, extension );
WIN32_FIND_DATA find_data;
HANDLE find_handle = FindFirstFile( search_key, &find_data );
if( find_handle != INVALID_HANDLE_VALUE )
{
do
{
if( strstr( find_data.cFileName, extension ) && strlen( strstr( find_data.cFileName, extension ) ) == strlen( extension ) )
{
char file_path[1024];
sprintf( file_path, "%s\\%s", folder, find_data.cFileName );
files.push_back( file_path );
}
else if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( find_data.cFileName[0] != '.' )
{
char subfolder[2048];
sprintf( subfolder, "%s\\%s", folder, find_data.cFileName );
list_files( subfolder, extension, files );
}
}
}while( FindNextFile( find_handle, &find_data ) );
}
}
void list_folders( char const* path, file_list& folders )
{
char search_key[1024];
sprintf( search_key, "%s\\*", path );
WIN32_FIND_DATA find_data;
HANDLE find_handle = FindFirstFile( search_key, &find_data );
if( find_handle != INVALID_HANDLE_VALUE )
{
do
{
if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( find_data.cFileName[0] != '.' )
{
char subfolder[2048];
sprintf( subfolder, "%s\\%s", path, find_data.cFileName );
folders.push_back( subfolder );
}
}
}while( FindNextFile( find_handle, &find_data ) );
}
}
compiler_list get_compilers( char const* folder )
{
file_list paths;
list_files( folder, "exe", paths );
compiler_list compilers;
for( file_list::iterator iter = paths.begin(); iter != paths.end(); ++iter )
{
char const* path = (*iter).c_str();
compilers.push_back( new compiler( path ) );
}
return compilers;
}
void compile_folder( compiler* c, char const* asset_folder, char const* mod_folder )
{
file_list files;
list_files( asset_folder, c->extension.c_str(), files );
for( file_list::iterator file_iter = files.begin(); file_iter != files.end(); ++file_iter )
{
c->compile( file_iter->c_str(), mod_folder );
}
}
void get_asset_folders( compiler& c, file_list& asset_folders )
{
std::string asset_list_path = c.path + std::string( ".txt" );
std::ifstream in = std::ifstream( asset_list_path.c_str() );
char path[1024];
while( !in.eof() )
{
in.getline( path, sizeof( path ) );
asset_folders.push_back( path );
}
}
int main( int argument_count, char** arguments )
{
char module_name[1024];
GetModuleFileName( 0, module_name, 1024 );
set_application_folder( module_name );
file_list mod_folders;
char mods_folder[1024];
sprintf( mods_folder, "%s..\\..\\mods", get_application_folder() );
list_folders( mods_folder, mod_folders );
sprintf( mods_folder, "%s..\\..\\dont_starve\\mods", get_application_folder() );
list_folders( mods_folder, mod_folders );
char compilers_folder[1024] ;
sprintf( compilers_folder, "%scompilers", get_application_folder() );
compiler_list compilers = get_compilers( compilers_folder );
for( compiler_list::iterator iter = compilers.begin(); iter != compilers.end(); ++iter )
{
compiler* c = *iter;
file_list asset_folders;
get_asset_folders( *c, asset_folders );
for( file_list::iterator mod_folder_iter = mod_folders.begin(); mod_folder_iter != mod_folders.end(); ++mod_folder_iter )
{
for( file_list::iterator asset_folder_iter = asset_folders.begin(); asset_folder_iter != asset_folders.end(); ++asset_folder_iter )
{
char asset_folder[1024];
sprintf( asset_folder, "%s/%s", mod_folder_iter->c_str(), asset_folder_iter->c_str() );
compile_folder( c, asset_folder, mod_folder_iter->c_str() );
}
}
}
return 0;
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tbxcustomshapes.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-10-12 12:03:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <string> // HACK: prevent conflict between STLPORT and Workshop headers
#ifndef _SVX_SVXIDS_HRC
#include <svxids.hrc>
#endif
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#include <sfx2/imagemgr.hxx>
#include <vcl/svapp.hxx>
#ifndef _SVX_TBXCUSTOMSHAPES_HXX
#include "tbxcustomshapes.hxx"
#endif
SFX_IMPL_TOOLBOX_CONTROL(SvxTbxCtlCustomShapes, SfxBoolItem);
/*************************************************************************
|*
|*
|*
\************************************************************************/
SvxTbxCtlCustomShapes::SvxTbxCtlCustomShapes( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :
SfxToolBoxControl( nSlotId, nId, rTbx ),
m_aSubTbxResName( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/" ) )
{
switch( nSlotId )
{
default :
{
DBG_ASSERT( false, "SvxTbxCtlCustomShapes: unknown slot executed. ?" );
}
case SID_DRAWTBX_CS_BASIC :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:BasicShapes.diamond" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "basicshapes" ) );
}
break;
case SID_DRAWTBX_CS_SYMBOL :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:SymbolShapes.smiley" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "symbolshapes" ) );
}
break;
case SID_DRAWTBX_CS_ARROW :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:ArrowShapes.left-right-arrow" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "arrowshapes" ) );
}
break;
case SID_DRAWTBX_CS_FLOWCHART :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:FlowChartShapes.flowchart-internal-storage" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "flowchartshapes" ) );
}
break;
case SID_DRAWTBX_CS_CALLOUT :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:CalloutShapes.round-rectangular-callout" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "calloutshapes" ) );
}
break;
case SID_DRAWTBX_CS_STAR :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:StarShapes.star5" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "starshapes" ) );
}
break;
}
m_aSubTbxResName += m_aSubTbName;
rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
rTbx.Invalidate();
}
/*************************************************************************
|*
|* Benachrichtigung, wenn sich der Applikationsstatus geaendert hat
|*
\************************************************************************/
void SvxTbxCtlCustomShapes::StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState )
{
SfxToolBoxControl::StateChanged( nSID, eState, pState );
}
/*************************************************************************
|*
|* Wenn man ein PopupWindow erzeugen will
|*
\************************************************************************/
SfxPopupWindowType SvxTbxCtlCustomShapes::GetPopupWindowType() const
{
return( m_aCommand.getLength() == 0 ? SFX_POPUPWINDOW_ONCLICK : SFX_POPUPWINDOW_ONTIMEOUT);
}
/*************************************************************************
|*
|* Hier wird das Fenster erzeugt
|* Lage der Toolbox mit GetToolBox() abfragbar
|* rItemRect sind die Screen-Koordinaten
|*
\************************************************************************/
SfxPopupWindow* SvxTbxCtlCustomShapes::CreatePopupWindow()
{
createAndPositionSubToolBar( m_aSubTbxResName );
return NULL;
}
// -----------------------------------------------------------------------
void SvxTbxCtlCustomShapes::Select( BOOL /*bMod1*/ )
{
if ( m_aCommand.getLength() > 0 )
{
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > aParamSeq( 0 );
Dispatch( m_aCommand, aParamSeq );
}
}
::sal_Bool SAL_CALL SvxTbxCtlCustomShapes::opensSubToolbar() throw (::com::sun::star::uno::RuntimeException)
{
// We control a sub-toolbar therefor, we have to return true.
return sal_True;
}
::rtl::OUString SAL_CALL SvxTbxCtlCustomShapes::getSubToolbarName() throw (::com::sun::star::uno::RuntimeException)
{
// Provide the controlled sub-toolbar name, so we are notified whenever
// this toolbar executes a function.
return m_aSubTbName;
}
void SAL_CALL SvxTbxCtlCustomShapes::functionSelected( const ::rtl::OUString& rCommand ) throw (::com::sun::star::uno::RuntimeException)
{
// remind the new command
m_aCommand = rCommand;
// Our sub-toolbar wants to execute a function.
// We have to change the image of our toolbar button to reflect the new function.
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( !m_bDisposed )
{
if ( m_aCommand.getLength() > 0 )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame( getFrameInterface());
Image aImage = GetImage( xFrame, m_aCommand, hasBigImages(), isHighContrast() );
if ( !!aImage )
GetToolBox().SetItemImage( GetId(), aImage );
}
}
}
void SAL_CALL SvxTbxCtlCustomShapes::updateImage( ) throw (::com::sun::star::uno::RuntimeException)
{
// We should update the button image of our parent (toolbar).
// Use the stored command to set the correct current image.
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( m_aCommand.getLength() > 0 )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame( getFrameInterface());
Image aImage = GetImage( xFrame, m_aCommand, hasBigImages(), isHighContrast() );
if ( !!aImage )
GetToolBox().SetItemImage( GetId(), aImage );
}
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.9.322); FILE MERGED 2007/06/04 13:26:10 vg 1.9.322.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tbxcustomshapes.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:44:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <string> // HACK: prevent conflict between STLPORT and Workshop headers
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#include <sfx2/imagemgr.hxx>
#include <vcl/svapp.hxx>
#ifndef _SVX_TBXCUSTOMSHAPES_HXX
#include "tbxcustomshapes.hxx"
#endif
SFX_IMPL_TOOLBOX_CONTROL(SvxTbxCtlCustomShapes, SfxBoolItem);
/*************************************************************************
|*
|*
|*
\************************************************************************/
SvxTbxCtlCustomShapes::SvxTbxCtlCustomShapes( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :
SfxToolBoxControl( nSlotId, nId, rTbx ),
m_aSubTbxResName( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/" ) )
{
switch( nSlotId )
{
default :
{
DBG_ASSERT( false, "SvxTbxCtlCustomShapes: unknown slot executed. ?" );
}
case SID_DRAWTBX_CS_BASIC :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:BasicShapes.diamond" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "basicshapes" ) );
}
break;
case SID_DRAWTBX_CS_SYMBOL :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:SymbolShapes.smiley" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "symbolshapes" ) );
}
break;
case SID_DRAWTBX_CS_ARROW :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:ArrowShapes.left-right-arrow" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "arrowshapes" ) );
}
break;
case SID_DRAWTBX_CS_FLOWCHART :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:FlowChartShapes.flowchart-internal-storage" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "flowchartshapes" ) );
}
break;
case SID_DRAWTBX_CS_CALLOUT :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:CalloutShapes.round-rectangular-callout" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "calloutshapes" ) );
}
break;
case SID_DRAWTBX_CS_STAR :
{
m_aCommand = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:StarShapes.star5" ) );
m_aSubTbName = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "starshapes" ) );
}
break;
}
m_aSubTbxResName += m_aSubTbName;
rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
rTbx.Invalidate();
}
/*************************************************************************
|*
|* Benachrichtigung, wenn sich der Applikationsstatus geaendert hat
|*
\************************************************************************/
void SvxTbxCtlCustomShapes::StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState )
{
SfxToolBoxControl::StateChanged( nSID, eState, pState );
}
/*************************************************************************
|*
|* Wenn man ein PopupWindow erzeugen will
|*
\************************************************************************/
SfxPopupWindowType SvxTbxCtlCustomShapes::GetPopupWindowType() const
{
return( m_aCommand.getLength() == 0 ? SFX_POPUPWINDOW_ONCLICK : SFX_POPUPWINDOW_ONTIMEOUT);
}
/*************************************************************************
|*
|* Hier wird das Fenster erzeugt
|* Lage der Toolbox mit GetToolBox() abfragbar
|* rItemRect sind die Screen-Koordinaten
|*
\************************************************************************/
SfxPopupWindow* SvxTbxCtlCustomShapes::CreatePopupWindow()
{
createAndPositionSubToolBar( m_aSubTbxResName );
return NULL;
}
// -----------------------------------------------------------------------
void SvxTbxCtlCustomShapes::Select( BOOL /*bMod1*/ )
{
if ( m_aCommand.getLength() > 0 )
{
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > aParamSeq( 0 );
Dispatch( m_aCommand, aParamSeq );
}
}
::sal_Bool SAL_CALL SvxTbxCtlCustomShapes::opensSubToolbar() throw (::com::sun::star::uno::RuntimeException)
{
// We control a sub-toolbar therefor, we have to return true.
return sal_True;
}
::rtl::OUString SAL_CALL SvxTbxCtlCustomShapes::getSubToolbarName() throw (::com::sun::star::uno::RuntimeException)
{
// Provide the controlled sub-toolbar name, so we are notified whenever
// this toolbar executes a function.
return m_aSubTbName;
}
void SAL_CALL SvxTbxCtlCustomShapes::functionSelected( const ::rtl::OUString& rCommand ) throw (::com::sun::star::uno::RuntimeException)
{
// remind the new command
m_aCommand = rCommand;
// Our sub-toolbar wants to execute a function.
// We have to change the image of our toolbar button to reflect the new function.
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( !m_bDisposed )
{
if ( m_aCommand.getLength() > 0 )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame( getFrameInterface());
Image aImage = GetImage( xFrame, m_aCommand, hasBigImages(), isHighContrast() );
if ( !!aImage )
GetToolBox().SetItemImage( GetId(), aImage );
}
}
}
void SAL_CALL SvxTbxCtlCustomShapes::updateImage( ) throw (::com::sun::star::uno::RuntimeException)
{
// We should update the button image of our parent (toolbar).
// Use the stored command to set the correct current image.
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( m_aCommand.getLength() > 0 )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame( getFrameInterface());
Image aImage = GetImage( xFrame, m_aCommand, hasBigImages(), isHighContrast() );
if ( !!aImage )
GetToolBox().SetItemImage( GetId(), aImage );
}
}
<|endoftext|>
|
<commit_before>#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <ctime>
#include <string>
#include <climits>
#include <queue>
#include "myers.h"
#include "SimpleEditDistance.h"
using namespace std;
int readFastaSequences(const char* path, vector< vector<unsigned char> >* seqs,
unsigned char* letterIdx, char* idxToLetter, bool* inAlphabet, int &alphabetLength);
void printAlignment(const unsigned char* query, const int queryLength,
const unsigned char* target, const int targetLength,
const unsigned char* alignment, const int alignmentLength,
const int position, const int modeCode, const char* idxToLetter);
// For debugging
void printSeq(const vector<unsigned char> &seq) {
for (int i = 0; i < seq.size(); i++)
printf("%d ", seq[i]);
printf("\n");
}
int main(int argc, char * const argv[]) {
//----------------------------- PARSE COMMAND LINE ------------------------//
// If true, there will be no output.
bool silent = false;
// Alignment mode.
char mode[16] = "NW";
// How many best sequences (those with smallest score) do we want.
// If 0, then we want them all.
int numBestSeqs = 0;
bool findAlignment = false;
int option;
int kArg = -1;
// If true, simple implementation of edit distance algorithm is used instead of myers.
// This is for testing purposes.
bool useSimple = false;
while ((option = getopt(argc, argv, "a:n:k:sct")) >= 0) { // : is not a delimiter but indicator of parameter
switch (option) {
case 'a': strcpy(mode, optarg); break;
case 'n': numBestSeqs = atoi(optarg); break;
case 'k': kArg = atoi(optarg); break;
case 's': silent = true; break;
case 'c': findAlignment = true; break;
case 't': useSimple = true; break;
}
}
if (optind + 2 != argc) {
fprintf(stderr, "\n");
fprintf(stderr, "Usage: aligner [options...] <queries.fasta> <target.fasta>\n");
fprintf(stderr, "Options:\n");
fprintf(stderr, "\t-s If specified, there will be no score or alignment output (silent mode).\n");
fprintf(stderr, "\t-a HW|NW|SHW Alignment mode that will be used. [default: NW]\n");
fprintf(stderr, "\t-n N Score will be calculated only for N best sequences (best = with smallest score)."
" If N = 0 then all sequences will be calculated."
" Specifying small N can make total calculation much faster. [default: 0]\n");
fprintf(stderr, "\t-c If specified, alignment will be found and printed.\n");
fprintf(stderr, "\t-k K Sequences with score > K will be discarded."
" Smaller k, faster calculation.\n");
fprintf(stderr, "\t-t If specified, simple algorithm is used instead of myers. To be used for testing.\n");
return 1;
}
//-------------------------------------------------------------------------//
int modeCode;
if (!strcmp(mode, "SHW"))
modeCode = MYERS_MODE_SHW;
else if (!strcmp(mode, "HW"))
modeCode = MYERS_MODE_HW;
else if (!strcmp(mode, "NW"))
modeCode = MYERS_MODE_NW;
else {
printf("Invalid mode!\n");
return 1;
}
printf("Using %s alignment mode.\n", mode);
// Alphabet information, will be constructed on fly while reading sequences
unsigned char letterIdx[128]; //!< letterIdx[c] is index of letter c in alphabet
char idxToLetter[128]; //!< numToLetter[i] is letter that has index i in alphabet
bool inAlphabet[128]; // inAlphabet[c] is true if c is in alphabet
for (int i = 0; i < 128; i++) {
inAlphabet[i] = false;
}
int alphabetLength = 0;
int readResult;
// Read queries
char* queriesFilepath = argv[optind];
vector< vector<unsigned char> >* querySequences = new vector< vector<unsigned char> >();
printf("Reading queries...\n");
readResult = readFastaSequences(queriesFilepath, querySequences, letterIdx, idxToLetter,
inAlphabet, alphabetLength);
if (readResult) {
printf("Error: There is no file with name %s\n", queriesFilepath);
delete querySequences;
return 1;
}
int numQueries = querySequences->size();
int queriesTotalLength = 0;
for (int i = 0; i < numQueries; i++) {
queriesTotalLength += (*querySequences)[i].size();
}
printf("Read %d queries, %d residues total.\n", numQueries, queriesTotalLength);
// Read target
char* targetFilepath = argv[optind+1];
vector< vector<unsigned char> >* targetSequences = new vector< vector<unsigned char> >();
printf("Reading target fasta file...\n");
readResult = readFastaSequences(targetFilepath, targetSequences, letterIdx, idxToLetter,
inAlphabet, alphabetLength);
if (readResult) {
printf("Error: There is no file with name %s\n", targetFilepath);
delete querySequences;
delete targetSequences;
return 1;
}
unsigned char* target = (*targetSequences)[0].data();
int targetLength = (*targetSequences)[0].size();
printf("Read target, %d residues.\n", targetLength);
printf("Alphabet: ");
for (int c = 0; c < 128; c++)
if (inAlphabet[c])
printf("%c ", c);
printf("\n");
// ----------------------------- MAIN CALCULATION ----------------------------- //
printf("\nComparing queries to target...\n");
int* scores = new int[numQueries];
int* pos = new int[numQueries];
priority_queue<int> bestScores; // Contains numBestSeqs best scores
int k = kArg;
unsigned char* alignment = NULL; int alignmentLength;
int* positions = NULL; int numPositions;
clock_t start = clock();
if (!findAlignment || silent) {
printf("0/%d", numQueries);
fflush(stdout);
}
for (int i = 0; i < numQueries; i++) {
unsigned char* query = (*querySequences)[i].data();
int queryLength = (*querySequences)[i].size();
// Calculate score
if (useSimple) {
// Just for testing
calcEditDistanceSimple(query, queryLength, target, targetLength,
alphabetLength, modeCode, scores + i,
&positions, &numPositions);
} else {
myersCalcEditDistance(query, queryLength, target, targetLength,
alphabetLength, k, modeCode, scores + i,
&positions, &numPositions,
findAlignment, &alignment, &alignmentLength);
}
// Keep only first position
if (numPositions > 0) {
pos[i] = positions[0];
free(positions);
} else {
pos[i] = -1;
}
// If we want only numBestSeqs best sequences, update best scores and adjust k to largest score.
if (numBestSeqs > 0) {
if (scores[i] >= 0) {
bestScores.push(scores[i]);
if (bestScores.size() > numBestSeqs) {
bestScores.pop();
}
if (bestScores.size() == numBestSeqs) {
k = bestScores.top() - 1;
if (kArg >= 0 && kArg < k)
k = kArg;
}
}
}
if (!findAlignment || silent) {
printf("\r%d/%d", i+1, numQueries);
fflush(stdout);
} else {
// Print alignment if it was found
if (alignment) {
printf("\n");
printf("Query #%d (%d residues): score = %d\n", i, queryLength, scores[i]);
printAlignment(query, queryLength, target, targetLength,
alignment, alignmentLength,
pos[i], modeCode, idxToLetter);
}
}
if (alignment)
free(alignment);
}
printf("\n");
if (!silent && !findAlignment) {
int scoreLimit = -1; // Only scores <= then scoreLimit will be printed (we consider -1 as infinity)
printf("\n");
if (bestScores.size() > 0) {
printf("%d best scores:\n", (int)bestScores.size());
scoreLimit = bestScores.top();
} else {
printf("Scores:\n");
}
printf("<query number>: <score>, <end_position_in_target>\n");
for (int i = 0; i < numQueries; i++)
if (scores[i] > -1 && (scoreLimit == -1 || scores[i] <= scoreLimit))
printf("#%d: %10d, %10d\n", i, scores[i], pos[i]);
}
clock_t finish = clock();
double cpuTime = ((double)(finish-start))/CLOCKS_PER_SEC;
printf("\nCpu time of searching: %lf\n", cpuTime);
// ---------------------------------------------------------------------------- //
// Free allocated space
delete querySequences;
delete targetSequences;
delete[] scores;
delete[] pos;
return 0;
}
/** Reads sequences from fasta file.
* Function is passed current alphabet information and will update it if needed.
* @param [in] path Path to fasta file containing sequences.
* @param [out] seqs Sequences will be stored here, each sequence as vector of indexes from alphabet.
* @param [inout] letterIdx Array of length 128. letterIdx[c] is index of letter c in alphabet.
* @param [inout] inAlphabet Array of length 128. inAlphabet[c] is true if c is in alphabet.
* @param [inout] alphabetLength
* @return 0 if all ok, positive number otherwise.
*/
int readFastaSequences(const char* path, vector< vector<unsigned char> >* seqs,
unsigned char* letterIdx, char* idxToLetter, bool* inAlphabet, int &alphabetLength) {
seqs->clear();
FILE* file = fopen(path, "r");
if (file == 0)
return 1;
bool inHeader = false;
bool inSequence = false;
int buffSize = 4096;
char buffer[buffSize];
while (!feof(file)) {
int read = fread(buffer, sizeof(char), buffSize, file);
for (int i = 0; i < read; ++i) {
char c = buffer[i];
if (inHeader) { // I do nothing if in header
if (c == '\n')
inHeader = false;
} else {
if (c == '>') {
inHeader = true;
inSequence = false;
} else {
if (c == '\r' || c == '\n')
continue;
// If starting new sequence, initialize it.
if (inSequence == false) {
inSequence = true;
seqs->push_back(vector<unsigned char>());
}
if (!inAlphabet[c]) { // I construct alphabet on fly
inAlphabet[c] = true;
letterIdx[c] = alphabetLength;
idxToLetter[alphabetLength] = c;
alphabetLength++;
}
seqs->back().push_back(letterIdx[c]);
}
}
}
}
fclose(file);
return 0;
}
void printAlignment(const unsigned char* query, const int queryLength,
const unsigned char* target, const int targetLength,
const unsigned char* alignment, const int alignmentLength,
const int position, const int modeCode, const char* idxToLetter) {
int tIdx = -1;
int qIdx = -1;
if (modeCode == MYERS_MODE_HW) {
tIdx = position;
for (int i = 0; i < alignmentLength; i++) {
if (alignment[i] != 1)
tIdx--;
}
}
for (int start = 0; start < alignmentLength; start += 50) {
// target
printf("T: ");
int startTIdx;
for (int j = start; j < start + 50 && j < alignmentLength; j++) {
if (alignment[j] == 1)
printf("_");
else
printf("%c", idxToLetter[target[++tIdx]]);
if (j == start)
startTIdx = tIdx;
}
printf(" (%d - %d)\n", max(startTIdx, 0), tIdx);
// query
printf("Q: ");
int startQIdx = qIdx;
for (int j = start; j < start + 50 && j < alignmentLength; j++) {
if (alignment[j] == 2)
printf("_");
else
printf("%c", idxToLetter[query[++qIdx]]);
if (j == start)
startQIdx = qIdx;
}
printf(" (%d - %d)\n\n", max(startQIdx, 0), qIdx);
}
}
<commit_msg>Aligner now prints all positions<commit_after>#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <ctime>
#include <string>
#include <climits>
#include <queue>
#include "myers.h"
#include "SimpleEditDistance.h"
using namespace std;
int readFastaSequences(const char* path, vector< vector<unsigned char> >* seqs,
unsigned char* letterIdx, char* idxToLetter, bool* inAlphabet, int &alphabetLength);
void printAlignment(const unsigned char* query, const int queryLength,
const unsigned char* target, const int targetLength,
const unsigned char* alignment, const int alignmentLength,
const int position, const int modeCode, const char* idxToLetter);
// For debugging
void printSeq(const vector<unsigned char> &seq) {
for (int i = 0; i < seq.size(); i++)
printf("%d ", seq[i]);
printf("\n");
}
int main(int argc, char * const argv[]) {
//----------------------------- PARSE COMMAND LINE ------------------------//
// If true, there will be no output.
bool silent = false;
// Alignment mode.
char mode[16] = "NW";
// How many best sequences (those with smallest score) do we want.
// If 0, then we want them all.
int numBestSeqs = 0;
bool findAlignment = false;
int option;
int kArg = -1;
// If true, simple implementation of edit distance algorithm is used instead of myers.
// This is for testing purposes.
bool useSimple = false;
while ((option = getopt(argc, argv, "a:n:k:sct")) >= 0) { // : is not a delimiter but indicator of parameter
switch (option) {
case 'a': strcpy(mode, optarg); break;
case 'n': numBestSeqs = atoi(optarg); break;
case 'k': kArg = atoi(optarg); break;
case 's': silent = true; break;
case 'c': findAlignment = true; break;
case 't': useSimple = true; break;
}
}
if (optind + 2 != argc) {
fprintf(stderr, "\n");
fprintf(stderr, "Usage: aligner [options...] <queries.fasta> <target.fasta>\n");
fprintf(stderr, "Options:\n");
fprintf(stderr, "\t-s If specified, there will be no score or alignment output (silent mode).\n");
fprintf(stderr, "\t-a HW|NW|SHW Alignment mode that will be used. [default: NW]\n");
fprintf(stderr, "\t-n N Score will be calculated only for N best sequences (best = with smallest score)."
" If N = 0 then all sequences will be calculated."
" Specifying small N can make total calculation much faster. [default: 0]\n");
fprintf(stderr, "\t-c If specified, alignment will be found and printed.\n");
fprintf(stderr, "\t-k K Sequences with score > K will be discarded."
" Smaller k, faster calculation.\n");
fprintf(stderr, "\t-t If specified, simple algorithm is used instead of myers. To be used for testing.\n");
return 1;
}
//-------------------------------------------------------------------------//
int modeCode;
if (!strcmp(mode, "SHW"))
modeCode = MYERS_MODE_SHW;
else if (!strcmp(mode, "HW"))
modeCode = MYERS_MODE_HW;
else if (!strcmp(mode, "NW"))
modeCode = MYERS_MODE_NW;
else {
printf("Invalid mode!\n");
return 1;
}
printf("Using %s alignment mode.\n", mode);
// Alphabet information, will be constructed on fly while reading sequences
unsigned char letterIdx[128]; //!< letterIdx[c] is index of letter c in alphabet
char idxToLetter[128]; //!< numToLetter[i] is letter that has index i in alphabet
bool inAlphabet[128]; // inAlphabet[c] is true if c is in alphabet
for (int i = 0; i < 128; i++) {
inAlphabet[i] = false;
}
int alphabetLength = 0;
int readResult;
// Read queries
char* queriesFilepath = argv[optind];
vector< vector<unsigned char> >* querySequences = new vector< vector<unsigned char> >();
printf("Reading queries...\n");
readResult = readFastaSequences(queriesFilepath, querySequences, letterIdx, idxToLetter,
inAlphabet, alphabetLength);
if (readResult) {
printf("Error: There is no file with name %s\n", queriesFilepath);
delete querySequences;
return 1;
}
int numQueries = querySequences->size();
int queriesTotalLength = 0;
for (int i = 0; i < numQueries; i++) {
queriesTotalLength += (*querySequences)[i].size();
}
printf("Read %d queries, %d residues total.\n", numQueries, queriesTotalLength);
// Read target
char* targetFilepath = argv[optind+1];
vector< vector<unsigned char> >* targetSequences = new vector< vector<unsigned char> >();
printf("Reading target fasta file...\n");
readResult = readFastaSequences(targetFilepath, targetSequences, letterIdx, idxToLetter,
inAlphabet, alphabetLength);
if (readResult) {
printf("Error: There is no file with name %s\n", targetFilepath);
delete querySequences;
delete targetSequences;
return 1;
}
unsigned char* target = (*targetSequences)[0].data();
int targetLength = (*targetSequences)[0].size();
printf("Read target, %d residues.\n", targetLength);
printf("Alphabet: ");
for (int c = 0; c < 128; c++)
if (inAlphabet[c])
printf("%c ", c);
printf("\n");
// ----------------------------- MAIN CALCULATION ----------------------------- //
printf("\nComparing queries to target...\n");
int* scores = new int[numQueries];
int** positions = new int*[numQueries];
int* numPositions = new int[numQueries];
priority_queue<int> bestScores; // Contains numBestSeqs best scores
int k = kArg;
unsigned char* alignment = NULL; int alignmentLength;
clock_t start = clock();
if (!findAlignment || silent) {
printf("0/%d", numQueries);
fflush(stdout);
}
for (int i = 0; i < numQueries; i++) {
unsigned char* query = (*querySequences)[i].data();
int queryLength = (*querySequences)[i].size();
// Calculate score
if (useSimple) {
// Just for testing
calcEditDistanceSimple(query, queryLength, target, targetLength,
alphabetLength, modeCode, scores + i,
positions + i, numPositions + i);
} else {
myersCalcEditDistance(query, queryLength, target, targetLength,
alphabetLength, k, modeCode, scores + i,
positions + i, numPositions + i,
findAlignment, &alignment, &alignmentLength);
}
// If we want only numBestSeqs best sequences, update best scores and adjust k to largest score.
if (numBestSeqs > 0) {
if (scores[i] >= 0) {
bestScores.push(scores[i]);
if (bestScores.size() > numBestSeqs) {
bestScores.pop();
}
if (bestScores.size() == numBestSeqs) {
k = bestScores.top() - 1;
if (kArg >= 0 && kArg < k)
k = kArg;
}
}
}
if (!findAlignment || silent) {
printf("\r%d/%d", i+1, numQueries);
fflush(stdout);
} else {
// Print alignment if it was found, use first position
if (alignment) {
printf("\n");
printf("Query #%d (%d residues): score = %d\n", i, queryLength, scores[i]);
printAlignment(query, queryLength, target, targetLength,
alignment, alignmentLength,
*(positions[i]), modeCode, idxToLetter);
}
}
if (alignment)
free(alignment);
}
printf("\n");
if (!silent && !findAlignment) {
int scoreLimit = -1; // Only scores <= then scoreLimit will be printed (we consider -1 as infinity)
printf("\n");
if (bestScores.size() > 0) {
printf("%d best scores:\n", (int)bestScores.size());
scoreLimit = bestScores.top();
} else {
printf("Scores:\n");
}
printf("<query number>: <score>, <num_positions>, [<end_position_in_target>]\n");
for (int i = 0; i < numQueries; i++) {
if (scores[i] > -1 && (scoreLimit == -1 || scores[i] <= scoreLimit)) {
printf("#%d: %d %d", i, scores[i], numPositions[i]);
if (numPositions[i] > 0) {
printf(" [");
for (int j = 0; j < numPositions[i]; j++) {
printf(" %d", *(positions[i] + j));
}
printf(" ]");
}
printf("\n");
}
}
}
clock_t finish = clock();
double cpuTime = ((double)(finish-start))/CLOCKS_PER_SEC;
printf("\nCpu time of searching: %lf\n", cpuTime);
// ---------------------------------------------------------------------------- //
// Free allocated space
for (int i = 0; i < numQueries; i++) {
free(positions[i]);
}
delete[] positions;
delete[] numPositions;
delete querySequences;
delete targetSequences;
delete[] scores;
return 0;
}
/** Reads sequences from fasta file.
* Function is passed current alphabet information and will update it if needed.
* @param [in] path Path to fasta file containing sequences.
* @param [out] seqs Sequences will be stored here, each sequence as vector of indexes from alphabet.
* @param [inout] letterIdx Array of length 128. letterIdx[c] is index of letter c in alphabet.
* @param [inout] inAlphabet Array of length 128. inAlphabet[c] is true if c is in alphabet.
* @param [inout] alphabetLength
* @return 0 if all ok, positive number otherwise.
*/
int readFastaSequences(const char* path, vector< vector<unsigned char> >* seqs,
unsigned char* letterIdx, char* idxToLetter, bool* inAlphabet, int &alphabetLength) {
seqs->clear();
FILE* file = fopen(path, "r");
if (file == 0)
return 1;
bool inHeader = false;
bool inSequence = false;
int buffSize = 4096;
char buffer[buffSize];
while (!feof(file)) {
int read = fread(buffer, sizeof(char), buffSize, file);
for (int i = 0; i < read; ++i) {
char c = buffer[i];
if (inHeader) { // I do nothing if in header
if (c == '\n')
inHeader = false;
} else {
if (c == '>') {
inHeader = true;
inSequence = false;
} else {
if (c == '\r' || c == '\n')
continue;
// If starting new sequence, initialize it.
if (inSequence == false) {
inSequence = true;
seqs->push_back(vector<unsigned char>());
}
if (!inAlphabet[c]) { // I construct alphabet on fly
inAlphabet[c] = true;
letterIdx[c] = alphabetLength;
idxToLetter[alphabetLength] = c;
alphabetLength++;
}
seqs->back().push_back(letterIdx[c]);
}
}
}
}
fclose(file);
return 0;
}
void printAlignment(const unsigned char* query, const int queryLength,
const unsigned char* target, const int targetLength,
const unsigned char* alignment, const int alignmentLength,
const int position, const int modeCode, const char* idxToLetter) {
int tIdx = -1;
int qIdx = -1;
if (modeCode == MYERS_MODE_HW) {
tIdx = position;
for (int i = 0; i < alignmentLength; i++) {
if (alignment[i] != 1)
tIdx--;
}
}
for (int start = 0; start < alignmentLength; start += 50) {
// target
printf("T: ");
int startTIdx;
for (int j = start; j < start + 50 && j < alignmentLength; j++) {
if (alignment[j] == 1)
printf("_");
else
printf("%c", idxToLetter[target[++tIdx]]);
if (j == start)
startTIdx = tIdx;
}
printf(" (%d - %d)\n", max(startTIdx, 0), tIdx);
// query
printf("Q: ");
int startQIdx = qIdx;
for (int j = start; j < start + 50 && j < alignmentLength; j++) {
if (alignment[j] == 2)
printf("_");
else
printf("%c", idxToLetter[query[++qIdx]]);
if (j == start)
startQIdx = qIdx;
}
printf(" (%d - %d)\n\n", max(startQIdx, 0), qIdx);
}
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// varlen.cpp
//
// Identification: src/backend/common/varlen.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "backend/common/varlen.h"
#include "backend/common/pool.h"
namespace peloton {
Varlen *Varlen::Create(size_t size, VarlenPool *data_pool) {
assert(false);
Varlen *retval;
if (data_pool != NULL) {
retval = new (data_pool->Allocate(sizeof(Varlen))) Varlen(size, data_pool);
} else {
retval = new Varlen(size);
}
return retval;
}
Varlen *Varlen::Clone(const Varlen &src, VarlenPool *data_pool) {
// Create a new instance, back pointer is set inside
Varlen *rv = Create(src.varlen_size - sizeof(Varlen *), data_pool);
// copy the meat (excluding back pointer)
::memcpy(rv->Get(), src.Get(), (rv->varlen_size - sizeof(Varlen *)));
return rv;
}
// Construct varlen in heap
Varlen::Varlen(size_t size) {
varlen_size = size + sizeof(Varlen *);
varlen_temp_pool = true;
varlen_string_ptr = new char[varlen_size];
SetBackPtr();
}
// Construct varlen in given data pool
Varlen::Varlen(std::size_t size, VarlenPool *data_pool) {
varlen_size = size + sizeof(Varlen *);
varlen_temp_pool = false;
varlen_string_ptr =
reinterpret_cast<char *>(data_pool->Allocate(varlen_size));
SetBackPtr();
}
Varlen::~Varlen() {
if (varlen_temp_pool == true) {
delete[] varlen_string_ptr;
}
}
char *Varlen::Get() { return varlen_string_ptr + sizeof(Varlen *); }
const char *Varlen::Get() const { return varlen_string_ptr + sizeof(Varlen *); }
void Varlen::UpdateStringLocation(void *location) {
varlen_string_ptr = reinterpret_cast<char *>(location);
}
void Varlen::SetBackPtr() {
Varlen **backptr = reinterpret_cast<Varlen **>(varlen_string_ptr);
*backptr = this;
}
} // End peloton namespace
<commit_msg>removed assert false in varlen creation (why was this here?)<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// varlen.cpp
//
// Identification: src/backend/common/varlen.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "backend/common/varlen.h"
#include "backend/common/pool.h"
namespace peloton {
Varlen *Varlen::Create(size_t size, VarlenPool *data_pool) {
Varlen *retval;
if (data_pool != NULL) {
retval = new (data_pool->Allocate(sizeof(Varlen))) Varlen(size, data_pool);
} else {
retval = new Varlen(size);
}
return retval;
}
Varlen *Varlen::Clone(const Varlen &src, VarlenPool *data_pool) {
// Create a new instance, back pointer is set inside
Varlen *rv = Create(src.varlen_size - sizeof(Varlen *), data_pool);
// copy the meat (excluding back pointer)
::memcpy(rv->Get(), src.Get(), (rv->varlen_size - sizeof(Varlen *)));
return rv;
}
// Construct varlen in heap
Varlen::Varlen(size_t size) {
varlen_size = size + sizeof(Varlen *);
varlen_temp_pool = true;
varlen_string_ptr = new char[varlen_size];
SetBackPtr();
}
// Construct varlen in given data pool
Varlen::Varlen(std::size_t size, VarlenPool *data_pool) {
varlen_size = size + sizeof(Varlen *);
varlen_temp_pool = false;
varlen_string_ptr =
reinterpret_cast<char *>(data_pool->Allocate(varlen_size));
SetBackPtr();
}
Varlen::~Varlen() {
if (varlen_temp_pool == true) {
delete[] varlen_string_ptr;
}
}
char *Varlen::Get() { return varlen_string_ptr + sizeof(Varlen *); }
const char *Varlen::Get() const { return varlen_string_ptr + sizeof(Varlen *); }
void Varlen::UpdateStringLocation(void *location) {
varlen_string_ptr = reinterpret_cast<char *>(location);
}
void Varlen::SetBackPtr() {
Varlen **backptr = reinterpret_cast<Varlen **>(varlen_string_ptr);
*backptr = this;
}
} // End peloton namespace
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <vector>
#include <seastar/core/shared_ptr.hh>
#include "schema.hh"
#include "sstables/types.hh"
#include "utils/UUID.hh"
namespace sstables {
/*
* This class caches a mapping from columns present in sstable to their column_id.
* This way we don't need to looku them up by column name every time.
*/
class column_translation {
struct state {
static std::pair<std::vector<stdx::optional<column_id>>, std::vector<std::optional<uint32_t>>> build(
const schema& s,
const utils::chunked_vector<serialization_header::column_desc>& src,
bool is_static) {
std::vector<stdx::optional<column_id>> ids;
std::vector<std::optional<column_id>> lens;
if (s.is_dense()) {
if (is_static) {
ids.push_back(s.static_begin()->id);
lens.push_back(s.static_begin()->type->value_length_if_fixed());
} else {
ids.push_back(s.regular_begin()->id);
lens.push_back(s.regular_begin()->type->value_length_if_fixed());
}
} else {
ids.reserve(src.size());
lens.reserve(src.size());
for (auto&& desc : src) {
const column_definition* def = s.get_column_definition(desc.name.value);
if (def) {
ids.push_back(def->id);
lens.push_back(def->type->value_length_if_fixed());
} else {
ids.push_back(stdx::nullopt);
lens.push_back(std::nullopt);
}
}
}
return std::make_pair(std::move(ids), std::move(lens));
}
utils::UUID schema_uuid;
std::vector<stdx::optional<column_id>> regular_schema_column_id_from_sstable;
std::vector<stdx::optional<column_id>> static_schema_column_id_from_sstable;
std::vector<std::optional<uint32_t>> regular_column_value_fix_lengths;
std::vector<std::optional<uint32_t>> static_column_value_fix_lengths;
std::vector<std::optional<uint32_t>> clustering_column_value_fix_lengths;
state() = default;
state(const state&) = delete;
state& operator=(const state&) = delete;
state(state&&) = default;
state& operator=(state&&) = default;
state(const schema& s, const serialization_header& header)
: schema_uuid(s.version())
{
std::tie(regular_schema_column_id_from_sstable, regular_column_value_fix_lengths) =
build(s, header.regular_columns.elements, false);
std::tie(static_schema_column_id_from_sstable, static_column_value_fix_lengths) =
build(s, header.static_columns.elements, true);
clustering_column_value_fix_lengths.reserve(header.clustering_key_types_names.elements.size());
for (auto&& t : header.clustering_key_types_names.elements) {
auto type = abstract_type::parse_type(sstring(std::cbegin(t.value), std::cend(t.value)));
clustering_column_value_fix_lengths.push_back(type->value_length_if_fixed());
}
}
};
lw_shared_ptr<const state> _state = make_lw_shared<const state>();
public:
column_translation get_for_schema(const schema& s, const serialization_header& header) {
if (s.version() != _state->schema_uuid) {
_state = make_lw_shared(state(s, header));
}
return *this;
}
const std::vector<stdx::optional<column_id>>& regular_columns() const {
return _state->regular_schema_column_id_from_sstable;
}
const std::vector<stdx::optional<column_id>>& static_columns() const {
return _state->static_schema_column_id_from_sstable;
}
const std::vector<std::optional<uint32_t>>& regular_column_value_fix_legths() const {
return _state->regular_column_value_fix_lengths;
}
const std::vector<std::optional<uint32_t>>& static_column_value_fix_legths() const {
return _state->static_column_value_fix_lengths;
}
const std::vector<std::optional<uint32_t>>& clustering_column_value_fix_legths() const {
return _state->clustering_column_value_fix_lengths;
}
};
}; // namespace sstables
<commit_msg>column_translation: add *_column_is_collection()<commit_after>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <vector>
#include <seastar/core/shared_ptr.hh>
#include "schema.hh"
#include "sstables/types.hh"
#include "utils/UUID.hh"
namespace sstables {
/*
* This class caches a mapping from columns present in sstable to their column_id.
* This way we don't need to looku them up by column name every time.
*/
class column_translation {
struct state {
static std::tuple<std::vector<stdx::optional<column_id>>,
std::vector<std::optional<uint32_t>>,
std::vector<bool>> build(
const schema& s,
const utils::chunked_vector<serialization_header::column_desc>& src,
bool is_static) {
std::vector<stdx::optional<column_id>> ids;
std::vector<std::optional<column_id>> lens;
std::vector<bool> is_collection;
if (s.is_dense()) {
if (is_static) {
ids.push_back(s.static_begin()->id);
lens.push_back(s.static_begin()->type->value_length_if_fixed());
is_collection.push_back(s.static_begin()->is_multi_cell());
} else {
ids.push_back(s.regular_begin()->id);
lens.push_back(s.regular_begin()->type->value_length_if_fixed());
is_collection.push_back(s.regular_begin()->is_multi_cell());
}
} else {
ids.reserve(src.size());
lens.reserve(src.size());
for (auto&& desc : src) {
const column_definition* def = s.get_column_definition(desc.name.value);
if (def) {
ids.push_back(def->id);
lens.push_back(def->type->value_length_if_fixed());
is_collection.push_back(def->is_multi_cell());
} else {
ids.push_back(stdx::nullopt);
lens.push_back(std::nullopt);
is_collection.push_back(false);
}
}
}
return std::make_tuple(std::move(ids), std::move(lens), std::move(is_collection));
}
utils::UUID schema_uuid;
std::vector<stdx::optional<column_id>> regular_schema_column_id_from_sstable;
std::vector<stdx::optional<column_id>> static_schema_column_id_from_sstable;
std::vector<std::optional<uint32_t>> regular_column_value_fix_lengths;
std::vector<std::optional<uint32_t>> static_column_value_fix_lengths;
std::vector<std::optional<uint32_t>> clustering_column_value_fix_lengths;
std::vector<bool> static_column_is_collection;
std::vector<bool> regular_column_is_collection;
state() = default;
state(const state&) = delete;
state& operator=(const state&) = delete;
state(state&&) = default;
state& operator=(state&&) = default;
state(const schema& s, const serialization_header& header)
: schema_uuid(s.version())
{
std::tie(regular_schema_column_id_from_sstable,
regular_column_value_fix_lengths,
regular_column_is_collection) =
build(s, header.regular_columns.elements, false);
std::tie(static_schema_column_id_from_sstable,
static_column_value_fix_lengths,
static_column_is_collection) =
build(s, header.static_columns.elements, true);
clustering_column_value_fix_lengths.reserve(header.clustering_key_types_names.elements.size());
for (auto&& t : header.clustering_key_types_names.elements) {
auto type = abstract_type::parse_type(sstring(std::cbegin(t.value), std::cend(t.value)));
clustering_column_value_fix_lengths.push_back(type->value_length_if_fixed());
}
}
};
lw_shared_ptr<const state> _state = make_lw_shared<const state>();
public:
column_translation get_for_schema(const schema& s, const serialization_header& header) {
if (s.version() != _state->schema_uuid) {
_state = make_lw_shared(state(s, header));
}
return *this;
}
const std::vector<stdx::optional<column_id>>& regular_columns() const {
return _state->regular_schema_column_id_from_sstable;
}
const std::vector<stdx::optional<column_id>>& static_columns() const {
return _state->static_schema_column_id_from_sstable;
}
const std::vector<std::optional<uint32_t>>& regular_column_value_fix_legths() const {
return _state->regular_column_value_fix_lengths;
}
const std::vector<std::optional<uint32_t>>& static_column_value_fix_legths() const {
return _state->static_column_value_fix_lengths;
}
const std::vector<std::optional<uint32_t>>& clustering_column_value_fix_legths() const {
return _state->clustering_column_value_fix_lengths;
}
const std::vector<bool>& static_column_is_collection() const {
return _state->static_column_is_collection;
}
const std::vector<bool>& regular_column_is_collection() const {
return _state->regular_column_is_collection;
}
};
}; // namespace sstables
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <seastar/core/semaphore.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/gate.hh>
#include <seastar/core/shared_future.hh>
#include <seastar/core/rwlock.hh>
#include <seastar/core/metrics_registration.hh>
#include <seastar/core/scheduling.hh>
#include "log.hh"
#include "utils/exponential_backoff_retry.hh"
#include <vector>
#include <list>
#include <functional>
#include "sstables/compaction.hh"
#include "compaction_weight_registration.hh"
#include "compaction_backlog_manager.hh"
#include "backlog_controller.hh"
class table;
using column_family = table;
class compacting_sstable_registration;
// Compaction manager is a feature used to manage compaction jobs from multiple
// column families pertaining to the same database.
class compaction_manager {
public:
struct stats {
int64_t pending_tasks = 0;
int64_t completed_tasks = 0;
uint64_t active_tasks = 0; // Number of compaction going on.
int64_t errors = 0;
};
private:
struct task {
column_family* compacting_cf = nullptr;
shared_future<> compaction_done = make_ready_future<>();
exponential_backoff_retry compaction_retry = exponential_backoff_retry(std::chrono::seconds(5), std::chrono::seconds(300));
bool stopping = false;
bool cleanup = false;
bool compaction_running = false;
};
// compaction manager may have N fibers to allow parallel compaction per shard.
std::list<lw_shared_ptr<task>> _tasks;
// Used to assert that compaction_manager was explicitly stopped, if started.
bool _stopped = true;
stats _stats;
seastar::metrics::metric_groups _metrics;
std::list<lw_shared_ptr<sstables::compaction_info>> _compactions;
// Store sstables that are being compacted at the moment. That's needed to prevent
// a sstable from being compacted twice.
std::unordered_set<sstables::shared_sstable> _compacting_sstables;
future<> _waiting_reevalution = make_ready_future<>();
condition_variable _postponed_reevaluation;
// column families that wait for compaction but had its submission postponed due to ongoing compaction.
std::vector<column_family*> _postponed;
// tracks taken weights of ongoing compactions, only one compaction per weight is allowed.
// weight is value assigned to a compaction job that is log base N of total size of all input sstables.
std::unordered_set<int> _weight_tracker;
// Purpose is to serialize major compaction across all column families, so as to
// reduce disk space requirement.
semaphore _major_compaction_sem{1};
// Prevents column family from running major and minor compaction at same time.
std::unordered_map<column_family*, rwlock> _compaction_locks;
semaphore _resharding_sem{1};
std::function<void()> compaction_submission_callback();
// all registered column families are submitted for compaction at a constant interval.
// Submission is a NO-OP when there's nothing to do, so it's fine to call it regularly.
timer<lowres_clock> _compaction_submission_timer = timer<lowres_clock>(compaction_submission_callback());
static constexpr std::chrono::seconds periodic_compaction_submission_interval() { return std::chrono::seconds(3600); }
private:
future<> task_stop(lw_shared_ptr<task> task);
// Return true if weight is not registered.
bool can_register_weight(column_family* cf, int weight);
// Register weight for a column family. Do that only if can_register_weight()
// returned true.
void register_weight(int weight);
// Deregister weight for a column family.
void deregister_weight(int weight);
// If weight of compaction job is taken, it will be trimmed until its new
// weight is not taken or its size is equal to minimum threshold.
// Return weight of compaction job.
int trim_to_compact(column_family* cf, sstables::compaction_descriptor& descriptor);
// Get candidates for compaction strategy, which are all sstables but the ones being compacted.
std::vector<sstables::shared_sstable> get_candidates(const column_family& cf);
void register_compacting_sstables(const std::vector<sstables::shared_sstable>& sstables);
void deregister_compacting_sstables(const std::vector<sstables::shared_sstable>& sstables);
// Return true if compaction manager and task weren't asked to stop.
inline bool can_proceed(const lw_shared_ptr<task>& task);
// Check if column family is being cleaned up.
inline bool check_for_cleanup(column_family *cf);
inline future<> put_task_to_sleep(lw_shared_ptr<task>& task);
// Compaction manager stop itself if it finds an storage I/O error which results in
// stop of transportation services. It cannot make progress anyway.
// Returns true if error is judged not fatal, and compaction can be retried.
inline bool maybe_stop_on_error(future<> f, stop_iteration will_stop = stop_iteration::no);
void postponed_compactions_reevaluation();
void reevaluate_postponed_compactions();
// Postpone compaction for a column family that couldn't be executed due to ongoing
// similar-sized compaction.
void postpone_compaction_for_column_family(column_family* cf);
compaction_controller _compaction_controller;
compaction_backlog_manager _backlog_manager;
seastar::scheduling_group _scheduling_group;
size_t _available_memory;
using get_candidates_func = std::function<std::vector<sstables::shared_sstable>(const column_family&)>;
future<> rewrite_sstables(column_family* cf, bool is_cleanup, get_candidates_func);
public:
compaction_manager(seastar::scheduling_group sg, const ::io_priority_class& iop, size_t available_memory);
compaction_manager(seastar::scheduling_group sg, const ::io_priority_class& iop, size_t available_memory, uint64_t shares);
compaction_manager();
~compaction_manager();
void register_metrics();
// Start compaction manager.
void start();
// Stop all fibers. Ongoing compactions will be waited.
future<> stop();
bool stopped() const { return _stopped; }
// Submit a column family to be compacted.
void submit(column_family* cf);
// Submit a column family to be cleaned up and wait for its termination.
future<> perform_cleanup(column_family* cf);
// Submit a column family to be upgraded and wait for its termination.
future<> perform_sstable_upgrade(column_family* cf, bool exclude_current_version);
// Submit a column family to be scrubbed and wait for its termination.
future<> perform_sstable_scrub(column_family* cf);
// Submit a column family for major compaction.
future<> submit_major_compaction(column_family* cf);
// Run a resharding job for a given column family.
// it completes when future returned by job is ready or returns immediately
// if manager was asked to stop.
//
// parameter job is a function that will carry the reshard operation on a set
// of sstables that belong to different shards for this column family using
// sstables::reshard_sstables(), and in the end, it will forward unshared
// sstables created by the process to their owner shards.
future<> run_resharding_job(column_family* cf, std::function<future<>()> job);
// Remove a column family from the compaction manager.
// Cancel requests on cf and wait for a possible ongoing compaction on cf.
future<> remove(column_family* cf);
// No longer interested in tracking backlog for compactions in this column
// family. For instance, we could be ALTERing TABLE to a different strategy.
void stop_tracking_ongoing_compactions(column_family* cf);
const stats& get_stats() const {
return _stats;
}
void register_compaction(lw_shared_ptr<sstables::compaction_info> c) {
_compactions.push_back(c);
}
void deregister_compaction(lw_shared_ptr<sstables::compaction_info> c) {
_compactions.remove(c);
}
const std::list<lw_shared_ptr<sstables::compaction_info>>& get_compactions() const {
return _compactions;
}
// Stops ongoing compaction of a given type.
void stop_compaction(sstring type);
// Called by compaction procedure to release the weight lock assigned to it, such that
// another compaction waiting on same weight can start as soon as possible. That's usually
// called before compaction seals sstable and such and after all compaction work is done.
void on_compaction_complete(compaction_weight_registration& weight_registration);
float backlog() {
return _backlog_manager.backlog();
}
void register_backlog_tracker(compaction_backlog_tracker& backlog_tracker) {
_backlog_manager.register_backlog_tracker(backlog_tracker);
}
// Propagate replacement of sstables to all ongoing compaction of a given column family
void propagate_replacement(column_family*cf, const std::vector<sstables::shared_sstable>& removed, const std::vector<sstables::shared_sstable>& added);
friend class compacting_sstable_registration;
friend class compaction_weight_registration;
};
<commit_msg>sstables: compaction_manager: #include seastarx.hh<commit_after>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <seastar/core/semaphore.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/gate.hh>
#include <seastar/core/shared_future.hh>
#include <seastar/core/rwlock.hh>
#include <seastar/core/metrics_registration.hh>
#include <seastar/core/scheduling.hh>
#include "log.hh"
#include "utils/exponential_backoff_retry.hh"
#include <vector>
#include <list>
#include <functional>
#include "sstables/compaction.hh"
#include "compaction_weight_registration.hh"
#include "compaction_backlog_manager.hh"
#include "backlog_controller.hh"
#include "seastarx.hh"
class table;
using column_family = table;
class compacting_sstable_registration;
// Compaction manager is a feature used to manage compaction jobs from multiple
// column families pertaining to the same database.
class compaction_manager {
public:
struct stats {
int64_t pending_tasks = 0;
int64_t completed_tasks = 0;
uint64_t active_tasks = 0; // Number of compaction going on.
int64_t errors = 0;
};
private:
struct task {
column_family* compacting_cf = nullptr;
shared_future<> compaction_done = make_ready_future<>();
exponential_backoff_retry compaction_retry = exponential_backoff_retry(std::chrono::seconds(5), std::chrono::seconds(300));
bool stopping = false;
bool cleanup = false;
bool compaction_running = false;
};
// compaction manager may have N fibers to allow parallel compaction per shard.
std::list<lw_shared_ptr<task>> _tasks;
// Used to assert that compaction_manager was explicitly stopped, if started.
bool _stopped = true;
stats _stats;
seastar::metrics::metric_groups _metrics;
std::list<lw_shared_ptr<sstables::compaction_info>> _compactions;
// Store sstables that are being compacted at the moment. That's needed to prevent
// a sstable from being compacted twice.
std::unordered_set<sstables::shared_sstable> _compacting_sstables;
future<> _waiting_reevalution = make_ready_future<>();
condition_variable _postponed_reevaluation;
// column families that wait for compaction but had its submission postponed due to ongoing compaction.
std::vector<column_family*> _postponed;
// tracks taken weights of ongoing compactions, only one compaction per weight is allowed.
// weight is value assigned to a compaction job that is log base N of total size of all input sstables.
std::unordered_set<int> _weight_tracker;
// Purpose is to serialize major compaction across all column families, so as to
// reduce disk space requirement.
semaphore _major_compaction_sem{1};
// Prevents column family from running major and minor compaction at same time.
std::unordered_map<column_family*, rwlock> _compaction_locks;
semaphore _resharding_sem{1};
std::function<void()> compaction_submission_callback();
// all registered column families are submitted for compaction at a constant interval.
// Submission is a NO-OP when there's nothing to do, so it's fine to call it regularly.
timer<lowres_clock> _compaction_submission_timer = timer<lowres_clock>(compaction_submission_callback());
static constexpr std::chrono::seconds periodic_compaction_submission_interval() { return std::chrono::seconds(3600); }
private:
future<> task_stop(lw_shared_ptr<task> task);
// Return true if weight is not registered.
bool can_register_weight(column_family* cf, int weight);
// Register weight for a column family. Do that only if can_register_weight()
// returned true.
void register_weight(int weight);
// Deregister weight for a column family.
void deregister_weight(int weight);
// If weight of compaction job is taken, it will be trimmed until its new
// weight is not taken or its size is equal to minimum threshold.
// Return weight of compaction job.
int trim_to_compact(column_family* cf, sstables::compaction_descriptor& descriptor);
// Get candidates for compaction strategy, which are all sstables but the ones being compacted.
std::vector<sstables::shared_sstable> get_candidates(const column_family& cf);
void register_compacting_sstables(const std::vector<sstables::shared_sstable>& sstables);
void deregister_compacting_sstables(const std::vector<sstables::shared_sstable>& sstables);
// Return true if compaction manager and task weren't asked to stop.
inline bool can_proceed(const lw_shared_ptr<task>& task);
// Check if column family is being cleaned up.
inline bool check_for_cleanup(column_family *cf);
inline future<> put_task_to_sleep(lw_shared_ptr<task>& task);
// Compaction manager stop itself if it finds an storage I/O error which results in
// stop of transportation services. It cannot make progress anyway.
// Returns true if error is judged not fatal, and compaction can be retried.
inline bool maybe_stop_on_error(future<> f, stop_iteration will_stop = stop_iteration::no);
void postponed_compactions_reevaluation();
void reevaluate_postponed_compactions();
// Postpone compaction for a column family that couldn't be executed due to ongoing
// similar-sized compaction.
void postpone_compaction_for_column_family(column_family* cf);
compaction_controller _compaction_controller;
compaction_backlog_manager _backlog_manager;
seastar::scheduling_group _scheduling_group;
size_t _available_memory;
using get_candidates_func = std::function<std::vector<sstables::shared_sstable>(const column_family&)>;
future<> rewrite_sstables(column_family* cf, bool is_cleanup, get_candidates_func);
public:
compaction_manager(seastar::scheduling_group sg, const ::io_priority_class& iop, size_t available_memory);
compaction_manager(seastar::scheduling_group sg, const ::io_priority_class& iop, size_t available_memory, uint64_t shares);
compaction_manager();
~compaction_manager();
void register_metrics();
// Start compaction manager.
void start();
// Stop all fibers. Ongoing compactions will be waited.
future<> stop();
bool stopped() const { return _stopped; }
// Submit a column family to be compacted.
void submit(column_family* cf);
// Submit a column family to be cleaned up and wait for its termination.
future<> perform_cleanup(column_family* cf);
// Submit a column family to be upgraded and wait for its termination.
future<> perform_sstable_upgrade(column_family* cf, bool exclude_current_version);
// Submit a column family to be scrubbed and wait for its termination.
future<> perform_sstable_scrub(column_family* cf);
// Submit a column family for major compaction.
future<> submit_major_compaction(column_family* cf);
// Run a resharding job for a given column family.
// it completes when future returned by job is ready or returns immediately
// if manager was asked to stop.
//
// parameter job is a function that will carry the reshard operation on a set
// of sstables that belong to different shards for this column family using
// sstables::reshard_sstables(), and in the end, it will forward unshared
// sstables created by the process to their owner shards.
future<> run_resharding_job(column_family* cf, std::function<future<>()> job);
// Remove a column family from the compaction manager.
// Cancel requests on cf and wait for a possible ongoing compaction on cf.
future<> remove(column_family* cf);
// No longer interested in tracking backlog for compactions in this column
// family. For instance, we could be ALTERing TABLE to a different strategy.
void stop_tracking_ongoing_compactions(column_family* cf);
const stats& get_stats() const {
return _stats;
}
void register_compaction(lw_shared_ptr<sstables::compaction_info> c) {
_compactions.push_back(c);
}
void deregister_compaction(lw_shared_ptr<sstables::compaction_info> c) {
_compactions.remove(c);
}
const std::list<lw_shared_ptr<sstables::compaction_info>>& get_compactions() const {
return _compactions;
}
// Stops ongoing compaction of a given type.
void stop_compaction(sstring type);
// Called by compaction procedure to release the weight lock assigned to it, such that
// another compaction waiting on same weight can start as soon as possible. That's usually
// called before compaction seals sstable and such and after all compaction work is done.
void on_compaction_complete(compaction_weight_registration& weight_registration);
float backlog() {
return _backlog_manager.backlog();
}
void register_backlog_tracker(compaction_backlog_tracker& backlog_tracker) {
_backlog_manager.register_backlog_tracker(backlog_tracker);
}
// Propagate replacement of sstables to all ongoing compaction of a given column family
void propagate_replacement(column_family*cf, const std::vector<sstables::shared_sstable>& removed, const std::vector<sstables::shared_sstable>& added);
friend class compacting_sstable_registration;
friend class compaction_weight_registration;
};
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <config.h>
#include <iostream>
#include <string>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <libport/cstdlib>
#include <libport/containers.hh>
#include <libport/sysexits.hh>
#include <libport/unistd.h>
#include "../sdk-remote/src/bin/urbi-root.hh"
int
main(int argc, char* argv[])
{
const std::string urbi_root = get_urbi_root(argv[0]);
const std::string urbi_launch = urbi_root + "/bin/urbi-launch";
std::vector<std::string> args_urbi_launch;
std::vector<std::string> args_libuobject;
args_urbi_launch << "--start";
for (int i = 1; i < argc; ++i)
{
if (!strcmp(argv[i], "--debug") || !strcmp(argv[i], "-d"))
{
args_urbi_launch << "--debug";
args_urbi_launch << argv[++i];
}
else if (!strncmp(argv[i], "--debug=", 8))
{
args_urbi_launch << "--debug";
args_urbi_launch << argv[i] + 8;
}
else
args_libuobject << argv[i];
}
const size_t args_n = args_urbi_launch.size() + args_libuobject.size() + 3;
const char** args_exec = new const char*[args_n];
memset(args_exec, sizeof(char*), args_n);
unsigned i = 0;
args_exec[i++] = urbi_launch.c_str();
for (unsigned j = 0; j < args_urbi_launch.size(); ++j)
args_exec[i++] = args_urbi_launch[j].c_str();
args_exec[i++] = "--";
for (unsigned j = 0; j < args_libuobject.size(); ++j)
args_exec[i++] = args_libuobject[j].c_str();
execv(urbi_launch.c_str(), const_cast<char *const*>(args_exec));
std::cerr << "unable to exec urbi-launch" << std::endl;
exit(EX_OSFILE);
}
<commit_msg>urbi: fix tests/bin/urbi.<commit_after>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <config.h>
#include <cerrno>
#include <iostream>
#include <string>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <libport/containers.hh>
#include <libport/cstdlib>
#include <libport/cstring>
#include <libport/sysexits.hh>
#include <libport/unistd.h>
#include "../sdk-remote/src/bin/urbi-root.hh"
using libport::streq;
using libport::strneq;
std::string
xgetenv(const char* var, const std::string& def)
{
if (const char* res = getenv(var))
return res;
else
return def;
}
int
main(int argc, char* argv[])
{
const std::string urbi_launch =
xgetenv("URBI_LAUNCH",
get_urbi_root(argv[0]) + "/bin/urbi-launch");
std::vector<std::string> args_urbi_launch;
std::vector<std::string> args_libuobject;
args_urbi_launch << "--start";
for (int i = 1; i < argc; ++i)
{
if (streq(argv[i], "--debug") || streq(argv[i], "-d"))
args_urbi_launch << "--debug" << argv[++i];
else if (strneq(argv[i], "--debug=", 8))
args_urbi_launch << "--debug" << argv[i] + 8;
else
args_libuobject << argv[i];
}
// Prepare a C version of vector<string> to please exec.
const size_t args_n = args_urbi_launch.size() + args_libuobject.size() + 3;
const char** args_exec = new const char*[args_n];
{
unsigned i = 0;
args_exec[i++] = urbi_launch.c_str();
for (unsigned j = 0; j < args_urbi_launch.size(); ++j)
args_exec[i++] = args_urbi_launch[j].c_str();
args_exec[i++] = "--";
for (unsigned j = 0; j < args_libuobject.size(); ++j)
args_exec[i++] = args_libuobject[j].c_str();
args_exec[i++] = 0;
assert(i <= args_n);
}
execv(urbi_launch.c_str(), const_cast<char *const*>(args_exec));
std::cerr
<< argv[0] << ": cannot exec " << urbi_launch
<< ": " << strerror(errno) << std::endl;
exit(EX_OSFILE);
}
<|endoftext|>
|
<commit_before>#include <config.h>
#include <assert.h>
#include <boost/concept/usage.hpp>
#include <boost/format.hpp>
#include <dune/common/exceptions.hh>
#include <dune/fem/io/file/dataoutput.hh>
#include <dune/fem/io/parameter.hh>
#include <dune/istl/scalarproducts.hh>
#include <dune/istl/solvers.hh>
#include <dune/multiscale/msfem/localproblems/localoperator.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/tools/discretefunctionwriter.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/fem/localmatrix_proxy.hh>
#include <dune/stuff/functions/norm.hh>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "dune/multiscale/msfem/localproblems/subgrid-list.hh"
#include "dune/multiscale/tools/misc/outputparameter.hh"
#include "localproblemsolver.hh"
namespace Dune {
namespace Multiscale {
namespace MsFEM {
/** \brief define output parameters for local problems
* appends "local_problems" for path
**/
struct LocalProblemDataOutputParameters : public OutputParameters {
public:
explicit LocalProblemDataOutputParameters();
};
LocalProblemDataOutputParameters::LocalProblemDataOutputParameters()
: OutputParameters(DSC_CONFIG_GET("global.datadir", "data") + "/local_problems/") {}
LocalProblemSolver::LocalProblemSolver(const CommonTraits::DiscreteFunctionSpaceType& coarse_space,
LocalGridList& subgrid_list,
const CommonTraits::DiffusionType& diffusion_operator)
: diffusion_(diffusion_operator)
, subgrid_list_(subgrid_list)
, coarse_space_(coarse_space) {}
void LocalProblemSolver::solve_all_on_single_cell(const MsFEMTraits::CoarseEntityType& coarseCell,
MsFEMTraits::LocalSolutionVectorType& allLocalSolutions) const {
assert(allLocalSolutions.size() > 0);
const bool hasBoundary = coarseCell.hasBoundaryIntersections();
const auto numBoundaryCorrectors = DSG::is_simplex_grid(coarse_space_) ? 1u : 2u;
const auto numInnerCorrectors = allLocalSolutions.size() - numBoundaryCorrectors;
// clear return argument
for (auto& localSol : allLocalSolutions)
localSol->clear();
const auto& subDiscreteFunctionSpace = allLocalSolutions[0]->space();
//! define the discrete (elliptic) local MsFEM problem operator
// ( effect of the discretized differential operator on a certain discrete function )
LocalProblemOperator localProblemOperator(coarse_space_, subDiscreteFunctionSpace, diffusion_);
// right hand side vector of the algebraic local MsFEM problem
MsFEMTraits::LocalSolutionVectorType allLocalRHS(allLocalSolutions.size());
for (auto& it : allLocalRHS)
it = DSC::make_unique<MsFEMTraits::LocalGridDiscreteFunctionType>("rhs of local MsFEM problem",
subDiscreteFunctionSpace);
localProblemOperator.assemble_all_local_rhs(coarseCell, allLocalRHS);
for (auto i : DSC::valueRange(allLocalSolutions.size())) {
auto& current_rhs = *allLocalRHS[i];
auto& current_solution = *allLocalSolutions[i];
// is the right hand side of the local MsFEM problem equal to zero or almost identical to zero?
// if yes, the solution of the local MsFEM problem is also identical to zero. The solver is getting a problem with
// this situation, which is why we do not solve local msfem problems for zero-right-hand-side, since we already know
// the result.
if (DS::l2norm(current_rhs) < 1e-30) {
current_solution.clear();
DSC_LOG_DEBUG << "Local MsFEM problem with solution zero." << std::endl;
continue;
}
// don't solve local problems for boundary correctors if coarse cell has no boundary intersections
if (i >= numInnerCorrectors && !hasBoundary) {
current_solution.clear();
DSC_LOG_DEBUG << "Zero-Boundary corrector." << std::endl;
continue;
}
localProblemOperator.apply_inverse(current_rhs, current_solution);
}
}
void LocalProblemSolver::solve_for_all_cells() {
static const int dimension = CommonTraits::GridType::dimension;
JacobianRangeType unitVectors[dimension];
for (int i = 0; i < dimension; ++i)
for (int j = 0; j < dimension; ++j) {
if (i == j) {
unitVectors[i][0][j] = 1.0;
} else {
unitVectors[i][0][j] = 0.0;
}
}
// number of coarse grid entities (of codim 0).
const auto coarseGridSize = coarse_space_.grid().size(0);
if (Dune::Fem::MPIManager::size() > 0)
DSC_LOG_DEBUG << "Rank " << Dune::Fem::MPIManager::rank() << " will solve local problems for " << coarseGridSize
<< " coarse entities!" << std::endl;
else {
DSC_LOG_DEBUG << "Will solve local problems for " << coarseGridSize << " coarse entities!" << std::endl;
}
DSC_PROFILER.startTiming("msfem.localproblemsolver.assemble_all");
// we want to determine minimum, average and maxiumum time for solving a local msfem problem in the current method
DSC::MinMaxAvg<double> cell_time;
DSC::MinMaxAvg<double> saveTime;
const auto& coarseGridLeafIndexSet = coarse_space_.gridPart().grid().leafIndexSet();
for (const auto& coarseEntity : coarse_space_) {
const int coarse_index = coarseGridLeafIndexSet.index(coarseEntity);
DSC_PROFILER.startTiming("none.saveLocalProblemsOnCell");
DSC_LOG_DEBUG << "-------------------------" << std::endl << "Coarse index " << coarse_index << std::endl;
// take time
DSC_PROFILER.startTiming("none.local_problem_solution");
LocalSolutionManager localSolutionManager(coarse_space_, coarseEntity, subgrid_list_);
// solve the problems
solve_all_on_single_cell(coarseEntity, localSolutionManager.getLocalSolutions());
// min/max time
cell_time(DSC_PROFILER.stopTiming("none.local_problem_solution") / 1000.f);
DSC_PROFILER.resetTiming("none.local_problem_solution");
// save the local solutions to disk
DSC_PROFILER.startTiming("none.saveLocalProblemSolution");
localSolutionManager.save();
saveTime(DSC_PROFILER.stopTiming("none.saveLocalProblemSolution") / 1000.f);
DSC_PROFILER.resetTiming("none.saveLocalProblemSolution");
DSC_LOG_INFO << "Total time for solving and saving all local problems for the current subgrid: "
<< DSC_PROFILER.stopTiming("none.saveLocalProblemsOnCell") / 1000.f << "s" << std::endl << std::endl;
DSC_PROFILER.resetTiming("none.saveLocalProblemsOnCell");
} // for
//! @todo The following debug-output is wrong (number of local problems may be different)
const auto total_time = DSC_PROFILER.stopTiming("msfem.localproblemsolver.assemble_all") / 1000.f;
DSC_LOG_DEBUG << "Local problems solved for " << coarseGridSize << " coarse grid entities.\n";
DSC_LOG_DEBUG << "Minimum time for solving a local problem = " << cell_time.min() << "s.\n";
DSC_LOG_DEBUG << "Maximum time for solving a localproblem = " << cell_time.max() << "s.\n";
DSC_LOG_DEBUG << "Average time for solving a localproblem = " << cell_time.average() << "s.\n";
DSC_LOG_DEBUG << "Minimum time for saving a local problem = " << saveTime.min() << "s.\n";
DSC_LOG_DEBUG << "Maximum time for saving a localproblem = " << saveTime.max() << "s.\n";
DSC_LOG_DEBUG << "Average time for saving a localproblem = " << saveTime.average() << "s.\n";
DSC_LOG_DEBUG << "Total time for computing and saving the localproblems = " << total_time << "s," << std::endl
<< std::endl;
} // assemble_all
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<commit_msg>Renamed some variables, changed some timings<commit_after>#include <config.h>
#include <assert.h>
#include <boost/concept/usage.hpp>
#include <boost/format.hpp>
#include <dune/common/exceptions.hh>
#include <dune/fem/io/file/dataoutput.hh>
#include <dune/fem/io/parameter.hh>
#include <dune/istl/scalarproducts.hh>
#include <dune/istl/solvers.hh>
#include <dune/multiscale/msfem/localproblems/localoperator.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/tools/discretefunctionwriter.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/fem/localmatrix_proxy.hh>
#include <dune/stuff/functions/norm.hh>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "dune/multiscale/msfem/localproblems/subgrid-list.hh"
#include "dune/multiscale/tools/misc/outputparameter.hh"
#include "localproblemsolver.hh"
namespace Dune {
namespace Multiscale {
namespace MsFEM {
/** \brief define output parameters for local problems
* appends "local_problems" for path
**/
struct LocalProblemDataOutputParameters : public OutputParameters {
public:
explicit LocalProblemDataOutputParameters();
};
LocalProblemDataOutputParameters::LocalProblemDataOutputParameters()
: OutputParameters(DSC_CONFIG_GET("global.datadir", "data") + "/local_problems/") {}
LocalProblemSolver::LocalProblemSolver(const CommonTraits::DiscreteFunctionSpaceType& coarse_space,
LocalGridList& subgrid_list,
const CommonTraits::DiffusionType& diffusion_operator)
: diffusion_(diffusion_operator)
, subgrid_list_(subgrid_list)
, coarse_space_(coarse_space) {}
void LocalProblemSolver::solve_all_on_single_cell(const MsFEMTraits::CoarseEntityType& coarseCell,
MsFEMTraits::LocalSolutionVectorType& allLocalSolutions) const {
assert(allLocalSolutions.size() > 0);
const bool hasBoundary = coarseCell.hasBoundaryIntersections();
const auto numBoundaryCorrectors = DSG::is_simplex_grid(coarse_space_) ? 1u : 2u;
const auto numInnerCorrectors = allLocalSolutions.size() - numBoundaryCorrectors;
// clear return argument
for (auto& localSol : allLocalSolutions)
localSol->clear();
const auto& subDiscreteFunctionSpace = allLocalSolutions[0]->space();
//! define the discrete (elliptic) local MsFEM problem operator
// ( effect of the discretized differential operator on a certain discrete function )
LocalProblemOperator localProblemOperator(coarse_space_, subDiscreteFunctionSpace, diffusion_);
// right hand side vector of the algebraic local MsFEM problem
MsFEMTraits::LocalSolutionVectorType allLocalRHS(allLocalSolutions.size());
for (auto& it : allLocalRHS)
it = DSC::make_unique<MsFEMTraits::LocalGridDiscreteFunctionType>("rhs of local MsFEM problem",
subDiscreteFunctionSpace);
localProblemOperator.assemble_all_local_rhs(coarseCell, allLocalRHS);
for (auto i : DSC::valueRange(allLocalSolutions.size())) {
auto& current_rhs = *allLocalRHS[i];
auto& current_solution = *allLocalSolutions[i];
// is the right hand side of the local MsFEM problem equal to zero or almost identical to zero?
// if yes, the solution of the local MsFEM problem is also identical to zero. The solver is getting a problem with
// this situation, which is why we do not solve local msfem problems for zero-right-hand-side, since we already know
// the result.
if (DS::l2norm(current_rhs) < 1e-30) {
current_solution.clear();
DSC_LOG_DEBUG << "Local MsFEM problem with solution zero." << std::endl;
continue;
}
// don't solve local problems for boundary correctors if coarse cell has no boundary intersections
if (i >= numInnerCorrectors && !hasBoundary) {
current_solution.clear();
DSC_LOG_DEBUG << "Zero-Boundary corrector." << std::endl;
continue;
}
localProblemOperator.apply_inverse(current_rhs, current_solution);
}
}
void LocalProblemSolver::solve_for_all_cells() {
static const int dimension = CommonTraits::GridType::dimension;
JacobianRangeType unitVectors[dimension];
for (int i = 0; i < dimension; ++i)
for (int j = 0; j < dimension; ++j) {
if (i == j) {
unitVectors[i][0][j] = 1.0;
} else {
unitVectors[i][0][j] = 0.0;
}
}
// number of coarse grid entities (of codim 0).
const auto coarseGridSize = coarse_space_.grid().size(0);
if (Dune::Fem::MPIManager::size() > 0)
DSC_LOG_DEBUG << "Rank " << Dune::Fem::MPIManager::rank() << " will solve local problems for " << coarseGridSize
<< " coarse entities!" << std::endl;
else {
DSC_LOG_DEBUG << "Will solve local problems for " << coarseGridSize << " coarse entities!" << std::endl;
}
DSC_PROFILER.startTiming("msfem.localProblemSolver.solveAndSaveAll");
// we want to determine minimum, average and maxiumum time for solving a local msfem problem in the current method
DSC::MinMaxAvg<double> solveTime;
DSC::MinMaxAvg<double> saveTime;
const auto& coarseGridLeafIndexSet = coarse_space_.gridPart().grid().leafIndexSet();
for (const auto& coarseEntity : coarse_space_) {
const int coarse_index = coarseGridLeafIndexSet.index(coarseEntity);
DSC_LOG_DEBUG << "-------------------------" << std::endl << "Coarse index " << coarse_index << std::endl;
// take time
DSC_PROFILER.startTiming("msfem.localProblemSolver.solve");
LocalSolutionManager localSolutionManager(coarse_space_, coarseEntity, subgrid_list_);
// solve the problems
solve_all_on_single_cell(coarseEntity, localSolutionManager.getLocalSolutions());
solveTime(DSC_PROFILER.stopTiming("msfem.localProblemSolver.solve") / 1000.f);
// save the local solutions to disk
DSC_PROFILER.startTiming("msfem.localProblemSolver.save");
localSolutionManager.save();
saveTime(DSC_PROFILER.stopTiming("msfem.localProblemSolver.save") / 1000.f);
DSC_PROFILER.resetTiming("msfem.localProblemSolver.solve");
DSC_PROFILER.resetTiming("msfem.localProblemSolver.save");
} // for
//! @todo The following debug-output is wrong (number of local problems may be different)
const auto totalTime = DSC_PROFILER.stopTiming("msfem.localProblemSolver.solveAndSaveAll") / 1000.f;
DSC_LOG_DEBUG << "Local problems solved for " << coarseGridSize << " coarse grid entities.\n";
DSC_LOG_DEBUG << "Minimum time for solving a local problem = " << solveTime.min() << "s.\n";
DSC_LOG_DEBUG << "Maximum time for solving a localproblem = " << solveTime.max() << "s.\n";
DSC_LOG_DEBUG << "Average time for solving a localproblem = " << solveTime.average() << "s.\n";
DSC_LOG_DEBUG << "Minimum time for saving a local problem = " << saveTime.min() << "s.\n";
DSC_LOG_DEBUG << "Maximum time for saving a localproblem = " << saveTime.max() << "s.\n";
DSC_LOG_DEBUG << "Average time for saving a localproblem = " << saveTime.average() << "s.\n";
DSC_LOG_DEBUG << "Total time for computing and saving the localproblems = " << totalTime << "s on rank" << Dune::Fem::MPIManager::rank() << std::endl
<< std::endl;
} // assemble_all
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<|endoftext|>
|
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/core/data/service/worker_impl.h"
#include "grpcpp/create_channel.h"
#include "absl/memory/memory.h"
#include "tensorflow/c/c_api_internal.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/core/data/dataset.pb.h"
#include "tensorflow/core/data/service/common.pb.h"
#include "tensorflow/core/data/service/credentials_factory.h"
#include "tensorflow/core/data/service/data_service.h"
#include "tensorflow/core/data/service/data_transfer.h"
#include "tensorflow/core/data/service/dispatcher.grpc.pb.h"
#include "tensorflow/core/data/service/dispatcher.pb.h"
#include "tensorflow/core/data/service/grpc_util.h"
#include "tensorflow/core/data/service/split_provider.h"
#include "tensorflow/core/data/service/task_runner.h"
#include "tensorflow/core/data/service/utils.h"
#include "tensorflow/core/data/standalone.h"
#include "tensorflow/core/framework/metrics.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/io/zlib_outputbuffer.h"
#include "tensorflow/core/lib/monitoring/gauge.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/refcount.h"
#include "tensorflow/core/platform/snappy.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
namespace data {
const constexpr uint64 kRetryIntervalMicros = 5ull * 1000 * 1000;
namespace {
// Moves the element into the response. If the tensor contains a single
// CompressedElement variant, the move will be zero-copy. Otherwise, the tensor
// data will be serialized as TensorProtos.
Status MoveElementToResponse(std::vector<Tensor>&& element,
GetElementResponse& resp) {
if (element.size() != 1 || element[0].dtype() != DT_VARIANT ||
!TensorShapeUtils::IsScalar(element[0].shape())) {
for (const auto& component : element) {
UncompressedElement* uncompressed = resp.mutable_uncompressed();
component.AsProtoTensorContent(uncompressed->add_components());
}
return Status::OK();
}
Variant& variant = element[0].scalar<Variant>()();
CompressedElement* compressed = variant.get<CompressedElement>();
if (compressed == nullptr) {
return errors::FailedPrecondition(
"Expected dataset to produce a CompressedElement variant tensor, but "
"it produced ",
variant.TypeName());
}
*resp.mutable_compressed() = *compressed;
return Status::OK();
}
} // namespace
DataServiceWorkerImpl::DataServiceWorkerImpl(
const experimental::WorkerConfig& config)
: config_(config) {
metrics::RecordTFDataServiceWorkerCreated();
}
DataServiceWorkerImpl::~DataServiceWorkerImpl() {
mutex_lock l(mu_);
cancelled_ = true;
task_completion_cv_.notify_one();
heartbeat_cv_.notify_one();
}
Status DataServiceWorkerImpl::Start(const std::string& worker_address,
const std::string& transfer_address) {
VLOG(3) << "Starting tf.data service worker at address " << worker_address;
worker_address_ = worker_address;
transfer_address_ = transfer_address;
dispatcher_ = absl::make_unique<DataServiceDispatcherClient>(
config_.dispatcher_address(), config_.protocol());
TF_RETURN_IF_ERROR(dispatcher_->Initialize());
Status s = Heartbeat();
while (!s.ok()) {
if (!errors::IsUnavailable(s) && !errors::IsAborted(s) &&
!errors::IsCancelled(s)) {
return s;
}
LOG(WARNING) << "Failed to register with dispatcher at "
<< config_.dispatcher_address() << ": " << s;
Env::Default()->SleepForMicroseconds(kRetryIntervalMicros);
s = Heartbeat();
}
LOG(INFO) << "Worker registered with dispatcher running at "
<< config_.dispatcher_address();
task_completion_thread_ = absl::WrapUnique(
Env::Default()->StartThread({}, "data-service-worker-task-completion",
[this]() { TaskCompletionThread(); }));
heartbeat_thread_ = absl::WrapUnique(Env::Default()->StartThread(
{}, "data-service-worker-heartbeat", [this]() { HeartbeatThread(); }));
mutex_lock l(mu_);
registered_ = true;
return Status::OK();
}
void DataServiceWorkerImpl::Stop() {
{
mutex_lock l(mu_);
cancellation_manager_.StartCancel();
cancelled_ = true;
while (outstanding_requests_ > 0) {
cv_.wait(l);
}
}
// At this point there are no outstanding requests in this RPC handler.
// However, requests successfully returned from this RPC handler may still be
// in progress within the gRPC server. If we shut down the gRPC server
// immediately, it could cause these requests to fail, e.g. with broken pipe.
// To mitigate this, we sleep for some time to give the gRPC server time to
// complete requests.
Env::Default()->SleepForMicroseconds(config_.shutdown_quiet_period_ms() *
1000);
}
Status DataServiceWorkerImpl::GetElementResult(
const GetElementRequest* request, struct GetElementResult* result) {
auto cleanup = gtl::MakeCleanup([&] {
mutex_lock l(mu_);
outstanding_requests_--;
cv_.notify_all();
});
Task* task;
{
mutex_lock l(mu_);
outstanding_requests_++;
if (cancelled_) {
return errors::Cancelled("Worker is shutting down");
}
if (!registered_) {
// We need to reject requests until the worker has registered with the
// dispatcher, so that we don't return NOT_FOUND for tasks that the worker
// had before preemption.
return errors::Unavailable(
"Worker has not yet registered with dispatcher.");
}
auto it = tasks_.find(request->task_id());
if (it == tasks_.end()) {
if (finished_tasks_.contains(request->task_id())) {
VLOG(3) << "Task is already finished";
result->end_of_sequence = true;
return Status::OK();
} else {
// Perhaps the workers hasn't gotten the task from the dispatcher yet.
// Return Unavailable so that the client knows to continue retrying.
return errors::Unavailable("Task ", request->task_id(), " not found");
}
}
task = it->second.get();
TF_RETURN_IF_ERROR(EnsureTaskInitialized(*task));
}
TF_RETURN_IF_ERROR(task->task_runner->GetNext(*request, *result));
return Status::OK();
}
Status DataServiceWorkerImpl::ProcessTask(const ProcessTaskRequest* request,
ProcessTaskResponse* response) {
mutex_lock l(mu_);
const TaskDef& task = request->task();
VLOG(3) << "Received request to process task " << task.task_id();
return ProcessTaskInternal(task);
}
Status DataServiceWorkerImpl::ProcessTaskInternal(const TaskDef& task_def)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
std::shared_ptr<Task>& task = tasks_[task_def.task_id()];
if (task) {
VLOG(1) << "Received request to process already-processed task "
<< task->task_def.task_id();
return Status::OK();
}
task = absl::make_unique<Task>(task_def);
VLOG(3) << "Began processing for task " << task_def.task_id()
<< " with processing mode " << task_def.processing_mode();
return Status::OK();
}
Status DataServiceWorkerImpl::EnsureTaskInitialized(
DataServiceWorkerImpl::Task& task) {
mutex_lock l(task.mu);
if (task.initialized) {
return Status::OK();
}
standalone::Dataset::Params params;
std::unique_ptr<standalone::Dataset> dataset;
std::unique_ptr<standalone::Iterator> iterator;
switch (task.task_def.dataset_case()) {
case TaskDef::kDatasetDef:
TF_RETURN_IF_ERROR(standalone::Dataset::FromGraph(
params, task.task_def.dataset_def().graph(), &dataset));
break;
case TaskDef::kPath: {
DatasetDef def;
Status s = ReadDatasetDef(task.task_def.path(), def);
if (!s.ok()) {
LOG(INFO) << "Failed to read dataset from " << task.task_def.path()
<< ": " << s << ". Falling back to reading from dispatcher.";
TF_RETURN_IF_ERROR(
dispatcher_->GetDatasetDef(task.task_def.dataset_id(), def));
}
TF_RETURN_IF_ERROR(
standalone::Dataset::FromGraph(params, def.graph(), &dataset));
break;
}
case TaskDef::DATASET_NOT_SET:
return errors::Internal("Unrecognized dataset case: ",
task.task_def.dataset_case());
}
switch (task.task_def.processing_mode()) {
case DISTRIBUTED_EPOCH: {
auto split_provider = absl::make_unique<DataServiceSplitProvider>(
config_.dispatcher_address(), config_.protocol(),
task.task_def.job_id(), config_.dispatcher_timeout_ms());
TF_RETURN_IF_ERROR(
dataset->MakeIterator(std::move(split_provider), &iterator));
break;
}
case PARALLEL_EPOCHS:
TF_RETURN_IF_ERROR(dataset->MakeIterator(&iterator));
break;
default:
return errors::InvalidArgument("Unrecognized processing mode: ",
task.task_def.processing_mode());
}
auto task_iterator = absl::make_unique<StandaloneTaskIterator>(
std::move(dataset), std::move(iterator));
TF_RETURN_IF_ERROR(
TaskRunner::Create(config_, task.task_def, cancellation_manager_,
std::move(task_iterator), task.task_runner));
task.initialized = true;
VLOG(3) << "Created iterator for task " << task.task_def.task_id();
return Status::OK();
}
Status DataServiceWorkerImpl::GetElement(const GetElementRequest* request,
GetElementResponse* response) {
VLOG(3) << "Received GetElement request for task " << request->task_id();
struct GetElementResult result;
TF_RETURN_IF_ERROR(GetElementResult(request, &result));
response->set_end_of_sequence(result.end_of_sequence);
response->set_skip_task(result.skip);
if (response->end_of_sequence()) {
mutex_lock l(mu_);
VLOG(3) << "Reached end_of_sequence for task " << request->task_id();
pending_completed_tasks_.insert(request->task_id());
task_completion_cv_.notify_one();
} else if (!response->skip_task()) {
TF_RETURN_IF_ERROR(
MoveElementToResponse(std::move(result.components), *response));
VLOG(3) << "Producing an element for task " << request->task_id();
}
return Status::OK();
}
Status DataServiceWorkerImpl::GetWorkerTasks(
const GetWorkerTasksRequest* request, GetWorkerTasksResponse* response) {
mutex_lock l(mu_);
for (const auto& it : tasks_) {
Task* task = it.second.get();
TaskInfo* task_info = response->add_tasks();
task_info->set_worker_address(worker_address_);
task_info->set_task_id(task->task_def.task_id());
task_info->set_job_id(task->task_def.job_id());
}
return Status::OK();
}
void DataServiceWorkerImpl::TaskCompletionThread() TF_LOCKS_EXCLUDED(mu_) {
while (true) {
{
mutex_lock l(mu_);
while (!cancelled_ && pending_completed_tasks_.empty()) {
task_completion_cv_.wait(l);
}
if (cancelled_) {
VLOG(3) << "Task completion thread shutting down";
return;
}
}
Status s = SendTaskUpdates();
if (!s.ok()) {
LOG(WARNING) << "Failed to send task updates to dispatcher: " << s;
mutex_lock l(mu_);
if (!cancelled_) {
task_completion_cv_.wait_for(
l, std::chrono::microseconds(kRetryIntervalMicros));
}
}
}
}
Status DataServiceWorkerImpl::SendTaskUpdates() TF_LOCKS_EXCLUDED(mu_) {
std::vector<TaskProgress> task_progress;
{
mutex_lock l(mu_);
VLOG(3) << "Sending " << pending_completed_tasks_.size()
<< " task updates to dispatcher";
task_progress.reserve(pending_completed_tasks_.size());
for (int task_id : pending_completed_tasks_) {
task_progress.emplace_back();
task_progress.back().set_task_id(task_id);
task_progress.back().set_completed(true);
}
}
TF_RETURN_IF_ERROR(dispatcher_->WorkerUpdate(worker_address_, task_progress));
mutex_lock l(mu_);
for (const auto& update : task_progress) {
pending_completed_tasks_.erase(update.task_id());
}
VLOG(3) << "Sent " << task_progress.size() << " task updates ";
return Status::OK();
}
void DataServiceWorkerImpl::HeartbeatThread() TF_LOCKS_EXCLUDED(mu_) {
while (true) {
int64 next_heartbeat_micros =
Env::Default()->NowMicros() + (config_.heartbeat_interval_ms() * 1000);
{
mutex_lock l(mu_);
while (!cancelled_ &&
Env::Default()->NowMicros() < next_heartbeat_micros) {
int64 time_to_wait_micros =
next_heartbeat_micros - Env::Default()->NowMicros();
heartbeat_cv_.wait_for(l,
std::chrono::microseconds(time_to_wait_micros));
}
if (cancelled_) {
VLOG(3) << "Heartbeat thread shutting down";
return;
}
if (!registered_) {
VLOG(1) << "Not performing heartbeat; worker is not yet registered";
continue;
}
}
Status s = Heartbeat();
if (!s.ok()) {
LOG(WARNING) << "Failed to send heartbeat to dispatcher: " << s;
}
}
}
Status DataServiceWorkerImpl::Heartbeat() TF_LOCKS_EXCLUDED(mu_) {
std::vector<int64> current_tasks;
{
mutex_lock l(mu_);
for (const auto& task : tasks_) {
current_tasks.push_back(task.first);
}
}
std::vector<TaskDef> new_tasks;
std::vector<int64> tasks_to_delete;
TF_RETURN_IF_ERROR(
dispatcher_->WorkerHeartbeat(worker_address_, transfer_address_,
current_tasks, new_tasks, tasks_to_delete));
mutex_lock l(mu_);
for (const auto& task : new_tasks) {
VLOG(1) << "Received new task from dispatcher with id " << task.task_id();
Status s = ProcessTaskInternal(task);
if (!s.ok() && !errors::IsAlreadyExists(s)) {
LOG(WARNING) << "Failed to start processing task " << task.task_id()
<< ": " << s;
}
}
for (int64 task_id : tasks_to_delete) {
VLOG(3) << "Deleting task " << task_id
<< " at the request of the dispatcher";
tasks_.erase(task_id);
finished_tasks_.insert(task_id);
}
return Status::OK();
}
} // namespace data
} // namespace tensorflow
<commit_msg>[tf.data service] Fix uninitialized field asan error.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/core/data/service/worker_impl.h"
#include "grpcpp/create_channel.h"
#include "absl/memory/memory.h"
#include "tensorflow/c/c_api_internal.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/core/data/dataset.pb.h"
#include "tensorflow/core/data/service/common.pb.h"
#include "tensorflow/core/data/service/credentials_factory.h"
#include "tensorflow/core/data/service/data_service.h"
#include "tensorflow/core/data/service/data_transfer.h"
#include "tensorflow/core/data/service/dispatcher.grpc.pb.h"
#include "tensorflow/core/data/service/dispatcher.pb.h"
#include "tensorflow/core/data/service/grpc_util.h"
#include "tensorflow/core/data/service/split_provider.h"
#include "tensorflow/core/data/service/task_runner.h"
#include "tensorflow/core/data/service/utils.h"
#include "tensorflow/core/data/standalone.h"
#include "tensorflow/core/framework/metrics.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/io/zlib_outputbuffer.h"
#include "tensorflow/core/lib/monitoring/gauge.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/refcount.h"
#include "tensorflow/core/platform/snappy.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
namespace data {
const constexpr uint64 kRetryIntervalMicros = 5ull * 1000 * 1000;
namespace {
// Moves the element into the response. If the tensor contains a single
// CompressedElement variant, the move will be zero-copy. Otherwise, the tensor
// data will be serialized as TensorProtos.
Status MoveElementToResponse(std::vector<Tensor>&& element,
GetElementResponse& resp) {
if (element.size() != 1 || element[0].dtype() != DT_VARIANT ||
!TensorShapeUtils::IsScalar(element[0].shape())) {
for (const auto& component : element) {
UncompressedElement* uncompressed = resp.mutable_uncompressed();
component.AsProtoTensorContent(uncompressed->add_components());
}
return Status::OK();
}
Variant& variant = element[0].scalar<Variant>()();
CompressedElement* compressed = variant.get<CompressedElement>();
if (compressed == nullptr) {
return errors::FailedPrecondition(
"Expected dataset to produce a CompressedElement variant tensor, but "
"it produced ",
variant.TypeName());
}
*resp.mutable_compressed() = *compressed;
return Status::OK();
}
} // namespace
DataServiceWorkerImpl::DataServiceWorkerImpl(
const experimental::WorkerConfig& config)
: config_(config) {
metrics::RecordTFDataServiceWorkerCreated();
}
DataServiceWorkerImpl::~DataServiceWorkerImpl() {
mutex_lock l(mu_);
cancelled_ = true;
task_completion_cv_.notify_one();
heartbeat_cv_.notify_one();
}
Status DataServiceWorkerImpl::Start(const std::string& worker_address,
const std::string& transfer_address) {
VLOG(3) << "Starting tf.data service worker at address " << worker_address;
worker_address_ = worker_address;
transfer_address_ = transfer_address;
dispatcher_ = absl::make_unique<DataServiceDispatcherClient>(
config_.dispatcher_address(), config_.protocol());
TF_RETURN_IF_ERROR(dispatcher_->Initialize());
Status s = Heartbeat();
while (!s.ok()) {
if (!errors::IsUnavailable(s) && !errors::IsAborted(s) &&
!errors::IsCancelled(s)) {
return s;
}
LOG(WARNING) << "Failed to register with dispatcher at "
<< config_.dispatcher_address() << ": " << s;
Env::Default()->SleepForMicroseconds(kRetryIntervalMicros);
s = Heartbeat();
}
LOG(INFO) << "Worker registered with dispatcher running at "
<< config_.dispatcher_address();
task_completion_thread_ = absl::WrapUnique(
Env::Default()->StartThread({}, "data-service-worker-task-completion",
[this]() { TaskCompletionThread(); }));
heartbeat_thread_ = absl::WrapUnique(Env::Default()->StartThread(
{}, "data-service-worker-heartbeat", [this]() { HeartbeatThread(); }));
mutex_lock l(mu_);
registered_ = true;
return Status::OK();
}
void DataServiceWorkerImpl::Stop() {
{
mutex_lock l(mu_);
cancellation_manager_.StartCancel();
cancelled_ = true;
while (outstanding_requests_ > 0) {
cv_.wait(l);
}
}
// At this point there are no outstanding requests in this RPC handler.
// However, requests successfully returned from this RPC handler may still be
// in progress within the gRPC server. If we shut down the gRPC server
// immediately, it could cause these requests to fail, e.g. with broken pipe.
// To mitigate this, we sleep for some time to give the gRPC server time to
// complete requests.
Env::Default()->SleepForMicroseconds(config_.shutdown_quiet_period_ms() *
1000);
}
Status DataServiceWorkerImpl::GetElementResult(
const GetElementRequest* request, struct GetElementResult* result) {
auto cleanup = gtl::MakeCleanup([&] {
mutex_lock l(mu_);
outstanding_requests_--;
cv_.notify_all();
});
Task* task;
{
mutex_lock l(mu_);
outstanding_requests_++;
if (cancelled_) {
return errors::Cancelled("Worker is shutting down");
}
if (!registered_) {
// We need to reject requests until the worker has registered with the
// dispatcher, so that we don't return NOT_FOUND for tasks that the worker
// had before preemption.
return errors::Unavailable(
"Worker has not yet registered with dispatcher.");
}
auto it = tasks_.find(request->task_id());
if (it == tasks_.end()) {
if (finished_tasks_.contains(request->task_id())) {
VLOG(3) << "Task is already finished";
result->end_of_sequence = true;
result->skip = false;
return Status::OK();
} else {
// Perhaps the workers hasn't gotten the task from the dispatcher yet.
// Return Unavailable so that the client knows to continue retrying.
return errors::Unavailable("Task ", request->task_id(), " not found");
}
}
task = it->second.get();
TF_RETURN_IF_ERROR(EnsureTaskInitialized(*task));
}
TF_RETURN_IF_ERROR(task->task_runner->GetNext(*request, *result));
return Status::OK();
}
Status DataServiceWorkerImpl::ProcessTask(const ProcessTaskRequest* request,
ProcessTaskResponse* response) {
mutex_lock l(mu_);
const TaskDef& task = request->task();
VLOG(3) << "Received request to process task " << task.task_id();
return ProcessTaskInternal(task);
}
Status DataServiceWorkerImpl::ProcessTaskInternal(const TaskDef& task_def)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
std::shared_ptr<Task>& task = tasks_[task_def.task_id()];
if (task) {
VLOG(1) << "Received request to process already-processed task "
<< task->task_def.task_id();
return Status::OK();
}
task = absl::make_unique<Task>(task_def);
VLOG(3) << "Began processing for task " << task_def.task_id()
<< " with processing mode " << task_def.processing_mode();
return Status::OK();
}
Status DataServiceWorkerImpl::EnsureTaskInitialized(
DataServiceWorkerImpl::Task& task) {
mutex_lock l(task.mu);
if (task.initialized) {
return Status::OK();
}
standalone::Dataset::Params params;
std::unique_ptr<standalone::Dataset> dataset;
std::unique_ptr<standalone::Iterator> iterator;
switch (task.task_def.dataset_case()) {
case TaskDef::kDatasetDef:
TF_RETURN_IF_ERROR(standalone::Dataset::FromGraph(
params, task.task_def.dataset_def().graph(), &dataset));
break;
case TaskDef::kPath: {
DatasetDef def;
Status s = ReadDatasetDef(task.task_def.path(), def);
if (!s.ok()) {
LOG(INFO) << "Failed to read dataset from " << task.task_def.path()
<< ": " << s << ". Falling back to reading from dispatcher.";
TF_RETURN_IF_ERROR(
dispatcher_->GetDatasetDef(task.task_def.dataset_id(), def));
}
TF_RETURN_IF_ERROR(
standalone::Dataset::FromGraph(params, def.graph(), &dataset));
break;
}
case TaskDef::DATASET_NOT_SET:
return errors::Internal("Unrecognized dataset case: ",
task.task_def.dataset_case());
}
switch (task.task_def.processing_mode()) {
case DISTRIBUTED_EPOCH: {
auto split_provider = absl::make_unique<DataServiceSplitProvider>(
config_.dispatcher_address(), config_.protocol(),
task.task_def.job_id(), config_.dispatcher_timeout_ms());
TF_RETURN_IF_ERROR(
dataset->MakeIterator(std::move(split_provider), &iterator));
break;
}
case PARALLEL_EPOCHS:
TF_RETURN_IF_ERROR(dataset->MakeIterator(&iterator));
break;
default:
return errors::InvalidArgument("Unrecognized processing mode: ",
task.task_def.processing_mode());
}
auto task_iterator = absl::make_unique<StandaloneTaskIterator>(
std::move(dataset), std::move(iterator));
TF_RETURN_IF_ERROR(
TaskRunner::Create(config_, task.task_def, cancellation_manager_,
std::move(task_iterator), task.task_runner));
task.initialized = true;
VLOG(3) << "Created iterator for task " << task.task_def.task_id();
return Status::OK();
}
Status DataServiceWorkerImpl::GetElement(const GetElementRequest* request,
GetElementResponse* response) {
VLOG(3) << "Received GetElement request for task " << request->task_id();
struct GetElementResult result;
TF_RETURN_IF_ERROR(GetElementResult(request, &result));
response->set_end_of_sequence(result.end_of_sequence);
response->set_skip_task(result.skip);
if (response->end_of_sequence()) {
mutex_lock l(mu_);
VLOG(3) << "Reached end_of_sequence for task " << request->task_id();
pending_completed_tasks_.insert(request->task_id());
task_completion_cv_.notify_one();
} else if (!response->skip_task()) {
TF_RETURN_IF_ERROR(
MoveElementToResponse(std::move(result.components), *response));
VLOG(3) << "Producing an element for task " << request->task_id();
}
return Status::OK();
}
Status DataServiceWorkerImpl::GetWorkerTasks(
const GetWorkerTasksRequest* request, GetWorkerTasksResponse* response) {
mutex_lock l(mu_);
for (const auto& it : tasks_) {
Task* task = it.second.get();
TaskInfo* task_info = response->add_tasks();
task_info->set_worker_address(worker_address_);
task_info->set_task_id(task->task_def.task_id());
task_info->set_job_id(task->task_def.job_id());
}
return Status::OK();
}
void DataServiceWorkerImpl::TaskCompletionThread() TF_LOCKS_EXCLUDED(mu_) {
while (true) {
{
mutex_lock l(mu_);
while (!cancelled_ && pending_completed_tasks_.empty()) {
task_completion_cv_.wait(l);
}
if (cancelled_) {
VLOG(3) << "Task completion thread shutting down";
return;
}
}
Status s = SendTaskUpdates();
if (!s.ok()) {
LOG(WARNING) << "Failed to send task updates to dispatcher: " << s;
mutex_lock l(mu_);
if (!cancelled_) {
task_completion_cv_.wait_for(
l, std::chrono::microseconds(kRetryIntervalMicros));
}
}
}
}
Status DataServiceWorkerImpl::SendTaskUpdates() TF_LOCKS_EXCLUDED(mu_) {
std::vector<TaskProgress> task_progress;
{
mutex_lock l(mu_);
VLOG(3) << "Sending " << pending_completed_tasks_.size()
<< " task updates to dispatcher";
task_progress.reserve(pending_completed_tasks_.size());
for (int task_id : pending_completed_tasks_) {
task_progress.emplace_back();
task_progress.back().set_task_id(task_id);
task_progress.back().set_completed(true);
}
}
TF_RETURN_IF_ERROR(dispatcher_->WorkerUpdate(worker_address_, task_progress));
mutex_lock l(mu_);
for (const auto& update : task_progress) {
pending_completed_tasks_.erase(update.task_id());
}
VLOG(3) << "Sent " << task_progress.size() << " task updates ";
return Status::OK();
}
void DataServiceWorkerImpl::HeartbeatThread() TF_LOCKS_EXCLUDED(mu_) {
while (true) {
int64 next_heartbeat_micros =
Env::Default()->NowMicros() + (config_.heartbeat_interval_ms() * 1000);
{
mutex_lock l(mu_);
while (!cancelled_ &&
Env::Default()->NowMicros() < next_heartbeat_micros) {
int64 time_to_wait_micros =
next_heartbeat_micros - Env::Default()->NowMicros();
heartbeat_cv_.wait_for(l,
std::chrono::microseconds(time_to_wait_micros));
}
if (cancelled_) {
VLOG(3) << "Heartbeat thread shutting down";
return;
}
if (!registered_) {
VLOG(1) << "Not performing heartbeat; worker is not yet registered";
continue;
}
}
Status s = Heartbeat();
if (!s.ok()) {
LOG(WARNING) << "Failed to send heartbeat to dispatcher: " << s;
}
}
}
Status DataServiceWorkerImpl::Heartbeat() TF_LOCKS_EXCLUDED(mu_) {
std::vector<int64> current_tasks;
{
mutex_lock l(mu_);
for (const auto& task : tasks_) {
current_tasks.push_back(task.first);
}
}
std::vector<TaskDef> new_tasks;
std::vector<int64> tasks_to_delete;
TF_RETURN_IF_ERROR(
dispatcher_->WorkerHeartbeat(worker_address_, transfer_address_,
current_tasks, new_tasks, tasks_to_delete));
mutex_lock l(mu_);
for (const auto& task : new_tasks) {
VLOG(1) << "Received new task from dispatcher with id " << task.task_id();
Status s = ProcessTaskInternal(task);
if (!s.ok() && !errors::IsAlreadyExists(s)) {
LOG(WARNING) << "Failed to start processing task " << task.task_id()
<< ": " << s;
}
}
for (int64 task_id : tasks_to_delete) {
VLOG(3) << "Deleting task " << task_id
<< " at the request of the dispatcher";
tasks_.erase(task_id);
finished_tasks_.insert(task_id);
}
return Status::OK();
}
} // namespace data
} // namespace tensorflow
<|endoftext|>
|
<commit_before>#pragma once
#include "helpers.hpp"
#include "priority_queue.hpp"
using std::pair;
using std::make_pair;
namespace search
{
namespace ds
{
struct OldKeys : public unordered_map<Cell, Key, Cell::Hasher>
{
auto update_with(pair<Cell, Key> cell_key_pair)
{
erase(cell_key_pair.first);
insert(cell_key_pair);
}
};
class DStarCore
{
//
// Algorithm
//
auto validate(Cell c) const
{
return c.row >= 0 && c.row < (int)matrix.rows() && c.col >= 0 && c.col < (int)matrix.cols();
}
auto valid_neighbours_of(Cell c) const
{
Cells neighbours;
for (auto direction = '1'; direction != '9'; ++direction)
{
auto n = DIRECTIONS.at(direction)(c);
if (validate(n))
neighbours.insert(n);
}
return neighbours;
}
auto initialize()
{
q.reset();
km = at(goal).r = 0;
q.push(goal);
}
auto update_vertex(LpState& s)
{
if (s.cell != goal)
{
auto minimum = huge();
for (auto neighbour : valid_neighbours_of(s.cell))
minimum = min(minimum, (at(neighbour).g + cost()));
s.r = minimum;
}
q.remove(s.cell);
if (s.g != s.r)
q.push(s.cell), old_keys.update_with( { s.cell, Key{ s, km } } );
}
//
// helpers
//
auto at(Cell c) const -> LpState const&
{
return matrix.at(c);
}
auto at(Cell c) -> LpState&
{
return matrix.at(c);
}
auto mark_bad_cells(Cells const& bad_cells)
{
for (auto c : bad_cells) at(c).bad = true;
}
auto mark_h_values_with(Cell terminal)
{
auto mark_h = [=](Cell c) { at(c).h = hfunc(c, terminal); };
matrix.each_cell(mark_h);
}
auto reset_statistics()
{
run_time = max_q_size = 0;
expansions.clear(), path.clear();
}
public:
//
// Constructor
//
DStarCore(unsigned rows, unsigned cols, Cell start, Cell goal, string heuristic, Cells const& bad_cells) :
matrix{ rows, cols },
start{ start },
goal{ goal },
hfunc{ HEURISTICS.at(heuristic) },
km{ 0 },
q{ [this](Cell l, Cell r) { return Key{ at(l), km } < Key{ at(r), km }; } },
old_keys { }
{
mark_bad_cells(bad_cells);
mark_h_values_with(start); //h value : start to current
reset_statistics();
}
//
// data members
//
Matrix matrix;
Cell const start, goal;
function<int(Cell, Cell)> const hfunc;
int km;
PriorityQueue < Cell, function<bool(Cell, Cell)> > q;
OldKeys old_keys;
//
// statistics
//
size_t max_q_size;
Cells expansions;
string path;
long long run_time;
};
}
}
<commit_msg>add update_neighbours_of<commit_after>#pragma once
#include "helpers.hpp"
#include "priority_queue.hpp"
using std::pair;
using std::make_pair;
namespace search
{
namespace ds
{
struct OldKeys : public unordered_map<Cell, Key, Cell::Hasher>
{
auto update_with(pair<Cell, Key> cell_key_pair)
{
erase(cell_key_pair.first);
insert(cell_key_pair);
}
};
class DStarCore
{
//
// Algorithm
//
auto validate(Cell c) const
{
return c.row >= 0 && c.row < (int)matrix.rows() && c.col >= 0 && c.col < (int)matrix.cols();
}
auto valid_neighbours_of(Cell c) const
{
Cells neighbours;
for (auto direction = '1'; direction != '9'; ++direction)
{
auto n = DIRECTIONS.at(direction)(c);
if (validate(n))
neighbours.insert(n);
}
return neighbours;
}
auto initialize()
{
q.reset();
km = at(goal).r = 0;
q.push(goal);
}
auto update_vertex(LpState& s)
{
if (s.cell != goal)
{
auto minimum = huge();
for (auto neighbour : valid_neighbours_of(s.cell))
minimum = min(minimum, (at(neighbour).g + cost()));
s.r = minimum;
}
q.remove(s.cell);
if (s.g != s.r)
q.push(s.cell), old_keys.update_with( { s.cell, Key{ s, km } } );
}
auto update_neighbours_of(Cell cell)
{
for (auto neighbour : valid_neighbours_of(cell))
if (!at(neighbour).bad)
update_vertex(at(neighbour));
}
//
// helpers
//
auto at(Cell c) const -> LpState const&
{
return matrix.at(c);
}
auto at(Cell c) -> LpState&
{
return matrix.at(c);
}
auto mark_bad_cells(Cells const& bad_cells)
{
for (auto c : bad_cells) at(c).bad = true;
}
auto mark_h_values_with(Cell terminal)
{
auto mark_h = [=](Cell c) { at(c).h = hfunc(c, terminal); };
matrix.each_cell(mark_h);
}
auto reset_statistics()
{
run_time = max_q_size = 0;
expansions.clear(), path.clear();
}
public:
//
// Constructor
//
DStarCore(unsigned rows, unsigned cols, Cell start, Cell goal, string heuristic, Cells const& bad_cells) :
matrix{ rows, cols },
start{ start },
goal{ goal },
hfunc{ HEURISTICS.at(heuristic) },
km{ 0 },
q{ [this](Cell l, Cell r) { return Key{ at(l), km } < Key{ at(r), km }; } },
old_keys { }
{
mark_bad_cells(bad_cells);
mark_h_values_with(start); //h value : start to current
reset_statistics();
}
//
// data members
//
Matrix matrix;
Cell const start, goal;
function<int(Cell, Cell)> const hfunc;
int km;
PriorityQueue < Cell, function<bool(Cell, Cell)> > q;
OldKeys old_keys;
//
// statistics
//
size_t max_q_size;
Cells expansions;
string path;
long long run_time;
};
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/login_prompt.h"
#include "app/l10n_util.h"
#include "base/command_line.h"
#include "base/lock.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h"
#include "chrome/browser/tab_contents/constrained_window.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "grit/generated_resources.h"
#include "net/base/auth.h"
#include "net/url_request/url_request.h"
using webkit_glue::PasswordForm;
class LoginHandlerImpl;
// Helper to remove the ref from an URLRequest to the LoginHandler.
// Should only be called from the IO thread, since it accesses an URLRequest.
void ResetLoginHandlerForRequest(URLRequest* request) {
ResourceDispatcherHostRequestInfo* info =
ResourceDispatcherHost::InfoForRequest(request);
if (!info)
return;
info->set_login_handler(NULL);
}
// Get the signon_realm under which this auth info should be stored.
//
// The format of the signon_realm for proxy auth is:
// proxy-host/auth-realm
// The format of the signon_realm for server auth is:
// url-scheme://url-host[:url-port]/auth-realm
//
// Be careful when changing this function, since you could make existing
// saved logins un-retrievable.
std::string GetSignonRealm(const GURL& url,
const net::AuthChallengeInfo& auth_info) {
std::string signon_realm;
if (auth_info.is_proxy) {
signon_realm = WideToASCII(auth_info.host_and_port);
signon_realm.append("/");
} else {
// Take scheme, host, and port from the url.
signon_realm = url.GetOrigin().spec();
// This ends with a "/".
}
signon_realm.append(WideToUTF8(auth_info.realm));
return signon_realm;
}
// ----------------------------------------------------------------------------
// LoginDialogTask
// This task is run on the UI thread and creates a constrained window with
// a LoginView to prompt the user. The response will be sent to LoginHandler,
// which then routes it to the URLRequest on the I/O thread.
class LoginDialogTask : public Task {
public:
LoginDialogTask(net::AuthChallengeInfo* auth_info, LoginHandler* handler)
: auth_info_(auth_info), handler_(handler) {
}
virtual ~LoginDialogTask() {
}
void Run() {
TabContents* parent_contents = handler_->GetTabContentsForLogin();
if (!parent_contents) {
// The request was probably cancelled.
return;
}
// Tell the password manager to look for saved passwords.
PasswordManager* password_manager =
parent_contents->GetPasswordManager();
std::vector<PasswordForm> v;
MakeInputForPasswordManager(parent_contents->GetURL(), &v);
password_manager->PasswordFormsSeen(v);
handler_->SetPasswordManager(password_manager);
std::wstring explanation = auth_info_->realm.empty() ?
l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION_NO_REALM,
auth_info_->host_and_port) :
l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION,
auth_info_->host_and_port,
auth_info_->realm);
handler_->BuildViewForPasswordManager(password_manager,
explanation);
}
private:
// Helper to create a PasswordForm and stuff it into a vector as input
// for PasswordManager::PasswordFormsSeen, the hook into PasswordManager.
void MakeInputForPasswordManager(
const GURL& origin_url,
std::vector<PasswordForm>* password_manager_input) {
PasswordForm dialog_form;
if (LowerCaseEqualsASCII(auth_info_->scheme, "basic")) {
dialog_form.scheme = PasswordForm::SCHEME_BASIC;
} else if (LowerCaseEqualsASCII(auth_info_->scheme, "digest")) {
dialog_form.scheme = PasswordForm::SCHEME_DIGEST;
} else {
dialog_form.scheme = PasswordForm::SCHEME_OTHER;
}
if (auth_info_->is_proxy) {
std::string origin = WideToASCII(auth_info_->host_and_port);
// We don't expect this to already start with http:// or https://.
DCHECK(origin.find("http://") != 0 && origin.find("https://") != 0);
origin = std::string("http://") + origin;
dialog_form.origin = GURL(origin);
} else {
dialog_form.origin = origin_url;
}
dialog_form.signon_realm = GetSignonRealm(dialog_form.origin, *auth_info_);
password_manager_input->push_back(dialog_form);
// Set the password form for the handler (by copy).
handler_->SetPasswordForm(dialog_form);
}
// Info about who/where/what is asking for authentication.
scoped_refptr<net::AuthChallengeInfo> auth_info_;
// Where to send the authentication when obtained.
// This is owned by the ResourceDispatcherHost that invoked us.
LoginHandler* handler_;
DISALLOW_EVIL_CONSTRUCTORS(LoginDialogTask);
};
// ----------------------------------------------------------------------------
// Public API
LoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,
URLRequest* request) {
LoginHandler* handler = LoginHandler::Create(request);
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE, new LoginDialogTask(auth_info, handler));
return handler;
}
<commit_msg>fix 32718<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/login_prompt.h"
#include "app/l10n_util.h"
#include "base/command_line.h"
#include "base/lock.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h"
#include "chrome/browser/tab_contents/constrained_window.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "grit/generated_resources.h"
#include "net/base/auth.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"
using webkit_glue::PasswordForm;
class LoginHandlerImpl;
// Helper to remove the ref from an URLRequest to the LoginHandler.
// Should only be called from the IO thread, since it accesses an URLRequest.
void ResetLoginHandlerForRequest(URLRequest* request) {
ResourceDispatcherHostRequestInfo* info =
ResourceDispatcherHost::InfoForRequest(request);
if (!info)
return;
info->set_login_handler(NULL);
}
// Get the signon_realm under which this auth info should be stored.
//
// The format of the signon_realm for proxy auth is:
// proxy-host/auth-realm
// The format of the signon_realm for server auth is:
// url-scheme://url-host[:url-port]/auth-realm
//
// Be careful when changing this function, since you could make existing
// saved logins un-retrievable.
std::string GetSignonRealm(const GURL& url,
const net::AuthChallengeInfo& auth_info) {
std::string signon_realm;
if (auth_info.is_proxy) {
signon_realm = WideToASCII(auth_info.host_and_port);
signon_realm.append("/");
} else {
// Take scheme, host, and port from the url.
signon_realm = url.GetOrigin().spec();
// This ends with a "/".
}
signon_realm.append(WideToUTF8(auth_info.realm));
return signon_realm;
}
// ----------------------------------------------------------------------------
// LoginDialogTask
// This task is run on the UI thread and creates a constrained window with
// a LoginView to prompt the user. The response will be sent to LoginHandler,
// which then routes it to the URLRequest on the I/O thread.
class LoginDialogTask : public Task {
public:
LoginDialogTask(const GURL& request_url,
net::AuthChallengeInfo* auth_info,
LoginHandler* handler)
: request_url_(request_url), auth_info_(auth_info), handler_(handler) {
}
virtual ~LoginDialogTask() {
}
void Run() {
TabContents* parent_contents = handler_->GetTabContentsForLogin();
if (!parent_contents) {
// The request was probably cancelled.
return;
}
// Tell the password manager to look for saved passwords.
PasswordManager* password_manager =
parent_contents->GetPasswordManager();
std::vector<PasswordForm> v;
MakeInputForPasswordManager(&v);
password_manager->PasswordFormsSeen(v);
handler_->SetPasswordManager(password_manager);
std::wstring explanation = auth_info_->realm.empty() ?
l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION_NO_REALM,
auth_info_->host_and_port) :
l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION,
auth_info_->host_and_port,
auth_info_->realm);
handler_->BuildViewForPasswordManager(password_manager,
explanation);
}
private:
// Helper to create a PasswordForm and stuff it into a vector as input
// for PasswordManager::PasswordFormsSeen, the hook into PasswordManager.
void MakeInputForPasswordManager(
std::vector<PasswordForm>* password_manager_input) {
PasswordForm dialog_form;
if (LowerCaseEqualsASCII(auth_info_->scheme, "basic")) {
dialog_form.scheme = PasswordForm::SCHEME_BASIC;
} else if (LowerCaseEqualsASCII(auth_info_->scheme, "digest")) {
dialog_form.scheme = PasswordForm::SCHEME_DIGEST;
} else {
dialog_form.scheme = PasswordForm::SCHEME_OTHER;
}
std::string host_and_port(WideToASCII(auth_info_->host_and_port));
if (net::GetHostAndPort(request_url_) != host_and_port) {
dialog_form.origin = GURL();
NOTREACHED();
} else if (auth_info_->is_proxy) {
std::string origin = host_and_port;
// We don't expect this to already start with http:// or https://.
DCHECK(origin.find("http://") != 0 && origin.find("https://") != 0);
origin = std::string("http://") + origin;
dialog_form.origin = GURL(origin);
} else {
dialog_form.origin = GURL(request_url_.scheme() + "://" + host_and_port);
}
dialog_form.signon_realm = GetSignonRealm(dialog_form.origin, *auth_info_);
password_manager_input->push_back(dialog_form);
// Set the password form for the handler (by copy).
handler_->SetPasswordForm(dialog_form);
}
// The url from the URLRequest initiating the auth challenge.
GURL request_url_;
// Info about who/where/what is asking for authentication.
scoped_refptr<net::AuthChallengeInfo> auth_info_;
// Where to send the authentication when obtained.
// This is owned by the ResourceDispatcherHost that invoked us.
LoginHandler* handler_;
DISALLOW_EVIL_CONSTRUCTORS(LoginDialogTask);
};
// ----------------------------------------------------------------------------
// Public API
LoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,
URLRequest* request) {
LoginHandler* handler = LoginHandler::Create(request);
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE, new LoginDialogTask(
request->url(), auth_info, handler));
return handler;
}
<|endoftext|>
|
<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "LinePolygonsCrossings.h"
#include <algorithm>
#include "../utils/polygonUtils.h"
#include "../sliceDataStorage.h"
#include "../utils/SVG.h"
namespace cura {
LinePolygonsCrossings::Crossing::Crossing(const coord_t x, const size_t point_idx)
: x(x)
, point_idx(point_idx)
{
}
LinePolygonsCrossings::PolyCrossings::PolyCrossings(const size_t poly_idx)
: poly_idx(poly_idx)
, min(std::numeric_limits<coord_t>::max(), NO_INDEX), max(std::numeric_limits<coord_t>::min(), NO_INDEX)
, n_crossings(0)
{
}
bool LinePolygonsCrossings::calcScanlineCrossings(bool fail_on_unavoidable_obstacles)
{
min_crossing_idx = NO_INDEX;
max_crossing_idx = NO_INDEX;
for(unsigned int poly_idx = 0; poly_idx < boundary.size(); poly_idx++)
{
PolyCrossings minMax(poly_idx);
ConstPolygonRef poly = boundary[poly_idx];
Point p0 = transformation_matrix.apply(poly[poly.size() - 1]);
for(unsigned int point_idx = 0; point_idx < poly.size(); point_idx++)
{
Point p1 = transformation_matrix.apply(poly[point_idx]);
if ((p0.Y >= transformed_startPoint.Y && p1.Y <= transformed_startPoint.Y) || (p1.Y >= transformed_startPoint.Y && p0.Y <= transformed_startPoint.Y))
{ // if line segment crosses the line through the transformed start and end point (aka scanline)
if (p1.Y == p0.Y) //Line segment is parallel with the scanline. That means that both endpoints lie on the scanline, so they will have intersected with the adjacent line.
{
p0 = p1;
continue;
}
const coord_t x = p0.X + (p1.X - p0.X) * (transformed_startPoint.Y - p0.Y) / (p1.Y - p0.Y); // intersection point between line segment and the scanline
if (x >= transformed_startPoint.X && x <= transformed_endPoint.X)
{
if (!((p1.Y == transformed_startPoint.Y && p1.Y < p0.Y) || (p0.Y == transformed_startPoint.Y && p0.Y < p1.Y)))
{ // perform edge case only for line segments on and below the scanline, not for line segments on and above.
// \/ will be no crossings and /\ two, but most importantly | will be one crossing.
minMax.n_crossings++;
}
if(x < minMax.min.x) //For the leftmost intersection, move x left to stay outside of the border.
//Note: The actual distance from the intersection to the border is almost always less than dist_to_move_boundary_point_outside, since it only moves along the direction of the scanline.
{
minMax.min.x = x;
minMax.min.point_idx = point_idx;
}
if(x > minMax.max.x) //For the rightmost intersection, move x right to stay outside of the border.
{
minMax.max.x = x;
minMax.max.point_idx = point_idx;
}
}
}
p0 = p1;
}
if (fail_on_unavoidable_obstacles && minMax.n_crossings % 2 == 1)
{ // if start area and end area are not the same
return false;
}
else if (minMax.min.point_idx != NO_INDEX) // then always also max.point_idx != NO_INDEX
{ // if this polygon crossed the scanline
if (min_crossing_idx == NO_INDEX || minMax.min.x < crossings[min_crossing_idx].min.x) { min_crossing_idx = crossings.size(); }
if (max_crossing_idx == NO_INDEX || minMax.max.x > crossings[max_crossing_idx].max.x) { max_crossing_idx = crossings.size(); }
crossings.push_back(minMax);
}
}
return true;
}
bool LinePolygonsCrossings::lineSegmentCollidesWithBoundary()
{
Point diff = endPoint - startPoint;
transformation_matrix = PointMatrix(diff);
transformed_startPoint = transformation_matrix.apply(startPoint);
transformed_endPoint = transformation_matrix.apply(endPoint);
for(ConstPolygonRef poly : boundary)
{
Point p0 = transformation_matrix.apply(poly.back());
for(Point p1_ : poly)
{
Point p1 = transformation_matrix.apply(p1_);
// when the boundary just touches the line don't disambiguate between the boundary moving on to actually cross the line
// and the boundary bouncing back, resulting in not a real collision - to keep the algorithm simple.
//
// disregard overlapping line segments; probably the next or previous line segment is not overlapping, but will give a collision
// when the boundary line segment fully overlaps with the line segment this edge case is not viewed as a collision
if (p1.Y != p0.Y && ((p0.Y >= transformed_startPoint.Y && p1.Y <= transformed_startPoint.Y) || (p1.Y >= transformed_startPoint.Y && p0.Y <= transformed_startPoint.Y)))
{
int64_t x = p0.X + (p1.X - p0.X) * (transformed_startPoint.Y - p0.Y) / (p1.Y - p0.Y);
if (x > transformed_startPoint.X && x < transformed_endPoint.X)
{
return true;
}
}
p0 = p1;
}
}
return false;
}
bool LinePolygonsCrossings::generateCombingPath(CombPath& combPath, int64_t max_comb_distance_ignored, bool fail_on_unavoidable_obstacles)
{
if (shorterThen(endPoint - startPoint, max_comb_distance_ignored) || !lineSegmentCollidesWithBoundary())
{
//We're not crossing any boundaries. So skip the comb generation.
combPath.push_back(startPoint);
combPath.push_back(endPoint);
return true;
}
bool success = calcScanlineCrossings(fail_on_unavoidable_obstacles);
if (!success)
{
return false;
}
CombPath basicPath;
generateBasicCombingPath(basicPath);
optimizePath(basicPath, combPath);
// combPath = basicPath; // uncomment to disable comb path optimization
return true;
}
void LinePolygonsCrossings::generateBasicCombingPath(CombPath& combPath)
{
for (PolyCrossings* crossing = getNextPolygonAlongScanline(transformed_startPoint.X)
; crossing != nullptr
; crossing = getNextPolygonAlongScanline(crossing->max.x))
{
generateBasicCombingPath(*crossing, combPath);
}
combPath.push_back(endPoint);
}
void LinePolygonsCrossings::generateBasicCombingPath(PolyCrossings& polyCrossings, CombPath& combPath)
{
// minimise the path length by measuring the length of both paths around the polygon so we can determine the shorter path
ConstPolygonRef poly = boundary[polyCrossings.poly_idx];
combPath.push_back(transformation_matrix.unapply(Point(polyCrossings.min.x - std::abs(dist_to_move_boundary_point_outside), transformed_startPoint.Y)));
// follow the path in the same direction as the winding order of the boundary polygon
std::vector<Point> fwd_points;
Point prev = combPath.back();
coord_t fwd_len = 0;
for (unsigned int point_idx = polyCrossings.min.point_idx
; point_idx != polyCrossings.max.point_idx
; point_idx = (point_idx < poly.size() - 1) ? (point_idx + 1) : (0))
{
const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside);
fwd_points.push_back(p);
fwd_len += vSize(p - prev);
prev = p;
}
// follow the path in the opposite direction of the winding order of the boundary polygon
std::vector<Point> rev_points;
prev = combPath.back();
coord_t rev_len = 0;
unsigned int min_idx = (polyCrossings.min.point_idx == 0)? poly.size() - 1 : polyCrossings.min.point_idx - 1;
unsigned int max_idx = (polyCrossings.max.point_idx == 0)? poly.size() - 1 : polyCrossings.max.point_idx - 1;
for (unsigned int point_idx = min_idx
; point_idx != max_idx
; point_idx = (point_idx > 0) ? (point_idx - 1) : (poly.size() - 1))
{
const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside);
rev_points.push_back(p);
rev_len += vSize(p - prev);
prev = p;
if (rev_len > fwd_len)
{
// this path is already longer than the forward path so there's no point in carrying on
break;
}
}
const Point last = transformation_matrix.unapply(Point(polyCrossings.max.x + std::abs(dist_to_move_boundary_point_outside), transformed_startPoint.Y));
if (fwd_points.size() > 0)
{
fwd_len += vSize(last - fwd_points.back());
}
if (rev_points.size() > 0)
{
rev_len += vSize(last - rev_points.back());
}
// use the points from the shortest path
for (auto& p : (fwd_len < rev_len) ? fwd_points : rev_points)
{
combPath.push_back(p);
}
combPath.push_back(last);
}
LinePolygonsCrossings::PolyCrossings* LinePolygonsCrossings::getNextPolygonAlongScanline(int64_t x)
{
PolyCrossings* ret = nullptr;
for(PolyCrossings& crossing : crossings)
{
if (crossing.min.x > x && (ret == nullptr || crossing.min.x < ret->min.x) )
{
ret = &crossing;
}
}
return ret;
}
bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimized_comb_path)
{
optimized_comb_path.push_back(startPoint);
for(unsigned int point_idx = 1; point_idx<comb_path.size(); point_idx++)
{
if(comb_path[point_idx] == comb_path[point_idx - 1]) //Two points are the same. Skip the second.
{
continue;
}
Point& current_point = optimized_comb_path.back();
if (PolygonUtils::polygonCollidesWithLineSegment(current_point, comb_path[point_idx], loc_to_line_grid))
{
if (PolygonUtils::polygonCollidesWithLineSegment(current_point, comb_path[point_idx - 1], loc_to_line_grid))
{
comb_path.cross_boundary = true;
}
// before we add this point, can we discard some of the previous points and still avoid clashing with the combing boundary?
const int max_short_circuit_len = 1 << 3; // test distances of 8, 4, 2, 1
for (unsigned n = std::min(max_short_circuit_len, (int)optimized_comb_path.size()); n > 0; n >>= 1)
{
if (optimized_comb_path.size() > n && !PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[optimized_comb_path.size() - n - 1], comb_path[point_idx - 1], loc_to_line_grid))
{
// we can remove n points from the path without it clashing with the combing boundary
for (unsigned i = 0; i < n; ++i)
{
optimized_comb_path.pop_back();
}
break;
}
}
optimized_comb_path.push_back(comb_path[point_idx - 1]);
if (point_idx == 1)
{
// we have just inserted the first point in the path that touches the boundary
// and as the first line in the comb is pointing from the start point towards the
// end point, we can maybe save some travel by replacing this first point with another
// that also lies on the second path of the comb, like this:
//
// 1
// /|
// / |
// / | ===> ----1
// S | S |
// | |
// 2----3 ... 2----3 ...
//
Point p = optimized_comb_path.back();
for (float frac : { 0.9, 0.9, 0.7, 0.5 })
{
// slide p towards the second point in the comb path
p = comb_path[1] + (p - comb_path[1]) * frac;
if (!PolygonUtils::polygonCollidesWithLineSegment(startPoint, p, loc_to_line_grid))
{
// using the new corner doesn't cause a conflict
optimized_comb_path.back() = p;
}
else
{
// quit loop and keep what we know to be good
break;
}
}
}
}
else
{
// : dont add the newest point
// TODO: add the below extra optimization? (+/- 7% extra computation time, +/- 2% faster print for Dual_extrusion_support_generation.stl)
while (optimized_comb_path.size() > 1)
{
if (PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[optimized_comb_path.size() - 2], comb_path[point_idx], loc_to_line_grid))
{
break;
}
else
{
optimized_comb_path.pop_back();
}
}
}
}
if (optimized_comb_path.size() > 1)
{
const unsigned n = optimized_comb_path.size();
// the penultimate corner may be deleted if the resulting path doesn't conflict with the boundary
if (!PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[n - 2], comb_path.back(), loc_to_line_grid))
{
optimized_comb_path.pop_back();
}
else {
// that wasn't possible so try and move the penultimate corner without conficting with the boundary
// in exactly the same way as we did at the start of the path
for (float frac : { 0.9, 0.9, 0.7, 0.5 })
{
// make a new point between the penultimate corner and the corner before that
Point p = optimized_comb_path[n - 2] + (optimized_comb_path[n - 1] - optimized_comb_path[n - 2]) * frac;
if (!PolygonUtils::polygonCollidesWithLineSegment(p, comb_path.back(), loc_to_line_grid))
{
// using the new corner doesn't cause a conflict
optimized_comb_path[n - 1] = p;
}
else
{
// quit loop and keep what we know to be good
break;
}
}
}
}
optimized_comb_path.push_back(comb_path.back());
return true;
}
}//namespace cura
<commit_msg>Bug fix in comb path generation - correct fwd path length before comparing with rev path length.<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "LinePolygonsCrossings.h"
#include <algorithm>
#include "../utils/polygonUtils.h"
#include "../sliceDataStorage.h"
#include "../utils/SVG.h"
namespace cura {
LinePolygonsCrossings::Crossing::Crossing(const coord_t x, const size_t point_idx)
: x(x)
, point_idx(point_idx)
{
}
LinePolygonsCrossings::PolyCrossings::PolyCrossings(const size_t poly_idx)
: poly_idx(poly_idx)
, min(std::numeric_limits<coord_t>::max(), NO_INDEX), max(std::numeric_limits<coord_t>::min(), NO_INDEX)
, n_crossings(0)
{
}
bool LinePolygonsCrossings::calcScanlineCrossings(bool fail_on_unavoidable_obstacles)
{
min_crossing_idx = NO_INDEX;
max_crossing_idx = NO_INDEX;
for(unsigned int poly_idx = 0; poly_idx < boundary.size(); poly_idx++)
{
PolyCrossings minMax(poly_idx);
ConstPolygonRef poly = boundary[poly_idx];
Point p0 = transformation_matrix.apply(poly[poly.size() - 1]);
for(unsigned int point_idx = 0; point_idx < poly.size(); point_idx++)
{
Point p1 = transformation_matrix.apply(poly[point_idx]);
if ((p0.Y >= transformed_startPoint.Y && p1.Y <= transformed_startPoint.Y) || (p1.Y >= transformed_startPoint.Y && p0.Y <= transformed_startPoint.Y))
{ // if line segment crosses the line through the transformed start and end point (aka scanline)
if (p1.Y == p0.Y) //Line segment is parallel with the scanline. That means that both endpoints lie on the scanline, so they will have intersected with the adjacent line.
{
p0 = p1;
continue;
}
const coord_t x = p0.X + (p1.X - p0.X) * (transformed_startPoint.Y - p0.Y) / (p1.Y - p0.Y); // intersection point between line segment and the scanline
if (x >= transformed_startPoint.X && x <= transformed_endPoint.X)
{
if (!((p1.Y == transformed_startPoint.Y && p1.Y < p0.Y) || (p0.Y == transformed_startPoint.Y && p0.Y < p1.Y)))
{ // perform edge case only for line segments on and below the scanline, not for line segments on and above.
// \/ will be no crossings and /\ two, but most importantly | will be one crossing.
minMax.n_crossings++;
}
if(x < minMax.min.x) //For the leftmost intersection, move x left to stay outside of the border.
//Note: The actual distance from the intersection to the border is almost always less than dist_to_move_boundary_point_outside, since it only moves along the direction of the scanline.
{
minMax.min.x = x;
minMax.min.point_idx = point_idx;
}
if(x > minMax.max.x) //For the rightmost intersection, move x right to stay outside of the border.
{
minMax.max.x = x;
minMax.max.point_idx = point_idx;
}
}
}
p0 = p1;
}
if (fail_on_unavoidable_obstacles && minMax.n_crossings % 2 == 1)
{ // if start area and end area are not the same
return false;
}
else if (minMax.min.point_idx != NO_INDEX) // then always also max.point_idx != NO_INDEX
{ // if this polygon crossed the scanline
if (min_crossing_idx == NO_INDEX || minMax.min.x < crossings[min_crossing_idx].min.x) { min_crossing_idx = crossings.size(); }
if (max_crossing_idx == NO_INDEX || minMax.max.x > crossings[max_crossing_idx].max.x) { max_crossing_idx = crossings.size(); }
crossings.push_back(minMax);
}
}
return true;
}
bool LinePolygonsCrossings::lineSegmentCollidesWithBoundary()
{
Point diff = endPoint - startPoint;
transformation_matrix = PointMatrix(diff);
transformed_startPoint = transformation_matrix.apply(startPoint);
transformed_endPoint = transformation_matrix.apply(endPoint);
for(ConstPolygonRef poly : boundary)
{
Point p0 = transformation_matrix.apply(poly.back());
for(Point p1_ : poly)
{
Point p1 = transformation_matrix.apply(p1_);
// when the boundary just touches the line don't disambiguate between the boundary moving on to actually cross the line
// and the boundary bouncing back, resulting in not a real collision - to keep the algorithm simple.
//
// disregard overlapping line segments; probably the next or previous line segment is not overlapping, but will give a collision
// when the boundary line segment fully overlaps with the line segment this edge case is not viewed as a collision
if (p1.Y != p0.Y && ((p0.Y >= transformed_startPoint.Y && p1.Y <= transformed_startPoint.Y) || (p1.Y >= transformed_startPoint.Y && p0.Y <= transformed_startPoint.Y)))
{
int64_t x = p0.X + (p1.X - p0.X) * (transformed_startPoint.Y - p0.Y) / (p1.Y - p0.Y);
if (x > transformed_startPoint.X && x < transformed_endPoint.X)
{
return true;
}
}
p0 = p1;
}
}
return false;
}
bool LinePolygonsCrossings::generateCombingPath(CombPath& combPath, int64_t max_comb_distance_ignored, bool fail_on_unavoidable_obstacles)
{
if (shorterThen(endPoint - startPoint, max_comb_distance_ignored) || !lineSegmentCollidesWithBoundary())
{
//We're not crossing any boundaries. So skip the comb generation.
combPath.push_back(startPoint);
combPath.push_back(endPoint);
return true;
}
bool success = calcScanlineCrossings(fail_on_unavoidable_obstacles);
if (!success)
{
return false;
}
CombPath basicPath;
generateBasicCombingPath(basicPath);
optimizePath(basicPath, combPath);
// combPath = basicPath; // uncomment to disable comb path optimization
return true;
}
void LinePolygonsCrossings::generateBasicCombingPath(CombPath& combPath)
{
for (PolyCrossings* crossing = getNextPolygonAlongScanline(transformed_startPoint.X)
; crossing != nullptr
; crossing = getNextPolygonAlongScanline(crossing->max.x))
{
generateBasicCombingPath(*crossing, combPath);
}
combPath.push_back(endPoint);
}
void LinePolygonsCrossings::generateBasicCombingPath(PolyCrossings& polyCrossings, CombPath& combPath)
{
// minimise the path length by measuring the length of both paths around the polygon so we can determine the shorter path
ConstPolygonRef poly = boundary[polyCrossings.poly_idx];
combPath.push_back(transformation_matrix.unapply(Point(polyCrossings.min.x - std::abs(dist_to_move_boundary_point_outside), transformed_startPoint.Y)));
// follow the path in the same direction as the winding order of the boundary polygon
std::vector<Point> fwd_points;
Point prev = combPath.back();
coord_t fwd_len = 0;
for (unsigned int point_idx = polyCrossings.min.point_idx
; point_idx != polyCrossings.max.point_idx
; point_idx = (point_idx < poly.size() - 1) ? (point_idx + 1) : (0))
{
const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside);
fwd_points.push_back(p);
fwd_len += vSize(p - prev);
prev = p;
}
const Point last = transformation_matrix.unapply(Point(polyCrossings.max.x + std::abs(dist_to_move_boundary_point_outside), transformed_startPoint.Y));
if (fwd_points.size() > 0)
{
fwd_len += vSize(last - fwd_points.back());
}
// follow the path in the opposite direction of the winding order of the boundary polygon
std::vector<Point> rev_points;
prev = combPath.back();
coord_t rev_len = 0;
unsigned int min_idx = (polyCrossings.min.point_idx == 0)? poly.size() - 1 : polyCrossings.min.point_idx - 1;
unsigned int max_idx = (polyCrossings.max.point_idx == 0)? poly.size() - 1 : polyCrossings.max.point_idx - 1;
for (unsigned int point_idx = min_idx
; point_idx != max_idx
; point_idx = (point_idx > 0) ? (point_idx - 1) : (poly.size() - 1))
{
const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside);
rev_points.push_back(p);
rev_len += vSize(p - prev);
prev = p;
if (rev_len > fwd_len)
{
// this path is already longer than the forward path so there's no point in carrying on
break;
}
}
if (rev_points.size() > 0)
{
rev_len += vSize(last - rev_points.back());
}
// use the points from the shortest path
for (auto& p : (fwd_len < rev_len) ? fwd_points : rev_points)
{
combPath.push_back(p);
}
combPath.push_back(last);
}
LinePolygonsCrossings::PolyCrossings* LinePolygonsCrossings::getNextPolygonAlongScanline(int64_t x)
{
PolyCrossings* ret = nullptr;
for(PolyCrossings& crossing : crossings)
{
if (crossing.min.x > x && (ret == nullptr || crossing.min.x < ret->min.x) )
{
ret = &crossing;
}
}
return ret;
}
bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimized_comb_path)
{
optimized_comb_path.push_back(startPoint);
for(unsigned int point_idx = 1; point_idx<comb_path.size(); point_idx++)
{
if(comb_path[point_idx] == comb_path[point_idx - 1]) //Two points are the same. Skip the second.
{
continue;
}
Point& current_point = optimized_comb_path.back();
if (PolygonUtils::polygonCollidesWithLineSegment(current_point, comb_path[point_idx], loc_to_line_grid))
{
if (PolygonUtils::polygonCollidesWithLineSegment(current_point, comb_path[point_idx - 1], loc_to_line_grid))
{
comb_path.cross_boundary = true;
}
// before we add this point, can we discard some of the previous points and still avoid clashing with the combing boundary?
const int max_short_circuit_len = 1 << 3; // test distances of 8, 4, 2, 1
for (unsigned n = std::min(max_short_circuit_len, (int)optimized_comb_path.size()); n > 0; n >>= 1)
{
if (optimized_comb_path.size() > n && !PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[optimized_comb_path.size() - n - 1], comb_path[point_idx - 1], loc_to_line_grid))
{
// we can remove n points from the path without it clashing with the combing boundary
for (unsigned i = 0; i < n; ++i)
{
optimized_comb_path.pop_back();
}
break;
}
}
optimized_comb_path.push_back(comb_path[point_idx - 1]);
if (point_idx == 1)
{
// we have just inserted the first point in the path that touches the boundary
// and as the first line in the comb is pointing from the start point towards the
// end point, we can maybe save some travel by replacing this first point with another
// that also lies on the second path of the comb, like this:
//
// 1
// /|
// / |
// / | ===> ----1
// S | S |
// | |
// 2----3 ... 2----3 ...
//
Point p = optimized_comb_path.back();
for (float frac : { 0.9, 0.9, 0.7, 0.5 })
{
// slide p towards the second point in the comb path
p = comb_path[1] + (p - comb_path[1]) * frac;
if (!PolygonUtils::polygonCollidesWithLineSegment(startPoint, p, loc_to_line_grid))
{
// using the new corner doesn't cause a conflict
optimized_comb_path.back() = p;
}
else
{
// quit loop and keep what we know to be good
break;
}
}
}
}
else
{
// : dont add the newest point
// TODO: add the below extra optimization? (+/- 7% extra computation time, +/- 2% faster print for Dual_extrusion_support_generation.stl)
while (optimized_comb_path.size() > 1)
{
if (PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[optimized_comb_path.size() - 2], comb_path[point_idx], loc_to_line_grid))
{
break;
}
else
{
optimized_comb_path.pop_back();
}
}
}
}
if (optimized_comb_path.size() > 1)
{
const unsigned n = optimized_comb_path.size();
// the penultimate corner may be deleted if the resulting path doesn't conflict with the boundary
if (!PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[n - 2], comb_path.back(), loc_to_line_grid))
{
optimized_comb_path.pop_back();
}
else {
// that wasn't possible so try and move the penultimate corner without conficting with the boundary
// in exactly the same way as we did at the start of the path
for (float frac : { 0.9, 0.9, 0.7, 0.5 })
{
// make a new point between the penultimate corner and the corner before that
Point p = optimized_comb_path[n - 2] + (optimized_comb_path[n - 1] - optimized_comb_path[n - 2]) * frac;
if (!PolygonUtils::polygonCollidesWithLineSegment(p, comb_path.back(), loc_to_line_grid))
{
// using the new corner doesn't cause a conflict
optimized_comb_path[n - 1] = p;
}
else
{
// quit loop and keep what we know to be good
break;
}
}
}
}
optimized_comb_path.push_back(comb_path.back());
return true;
}
}//namespace cura
<|endoftext|>
|
<commit_before>#include "tango-gl-renderer/axis.h"
#include "tango-gl-renderer/camera.h"
#include "tango-gl-renderer/cube.h"
#include "tango-gl-renderer/frustum.h"
#include "tango-gl-renderer/gl_util.h"
#include "tango-gl-renderer/grid.h"
#include "tango-gl-renderer/trace.h"
#include "dance_steps.h"
#include "tango_data.h"
const glm::vec3 kCubeScale = glm::vec3(0.3f, 0.3f, 0.3f);
DanceSteps::DanceSteps(){
c = new Cube();
c->SetScale(kCubeScale);
}
DanceSteps::~DanceSteps(){
delete c;
}
void DanceSteps::Render(const glm::mat4& projection_mat, const glm::mat4& view_mat) const {
float floor_height = TangoData::GetInstance().floor_height;
for(float y = 0.0f; y < 10.0f; y += 1.0f){
for(float x = 0.0f; x < 10.0f; x += 2.0f){
c->SetPosition(glm::vec3(x,floor_height,y));
c->Render(projection_mat, view_mat);
}
}
}
<commit_msg>First work on making dance floor<commit_after>#include "tango-gl-renderer/axis.h"
#include "tango-gl-renderer/camera.h"
#include "tango-gl-renderer/cube.h"
#include "tango-gl-renderer/frustum.h"
#include "tango-gl-renderer/gl_util.h"
#include "tango-gl-renderer/grid.h"
#include "tango-gl-renderer/trace.h"
#include "dance_steps.h"
#include "tango_data.h"
const glm::vec3 kCubeScale = glm::vec3(0.1f, 0.001f, 0.1f);
DanceSteps::DanceSteps(){
c = new Cube();
c->SetScale(kCubeScale);
}
DanceSteps::~DanceSteps(){
delete c;
}
void DanceSteps::Render(const glm::mat4& projection_mat, const glm::mat4& view_mat) const {
float floor_height = TangoData::GetInstance().floor_height;
for(float y = 0.0f; y < 10.0f; y += 0.5f){
for(float x = 0.0f; x < 10.0f; x += 0.5f){
c->SetPosition(glm::vec3(x,floor_height,y));
c->Render(projection_mat, view_mat);
}
}
}
<|endoftext|>
|
<commit_before>// Copyright 2015-2018 Elviss Strazdins. All rights reserved.
#pragma once
#include <vector>
#include "math/Box3.hpp"
#include "math/Plane.hpp"
#include "math/Vector4.hpp"
namespace ouzel
{
class ConvexVolume
{
public:
ConvexVolume()
{
}
ConvexVolume(const std::vector<Plane>& initPlanes):
planes(initPlanes)
{
}
bool isPointInside(const Vector4& position)
{
for (const Plane& plane : planes)
{
if (plane.dot(position) < 0.0F)
return false;
}
return true;
}
bool isSphereInside(const Vector4& position, float radius)
{
for (const Plane& plane : planes)
{
if (plane.dot(position) < -radius)
return false;
}
return true;
}
bool isBoxInside(const Box3& box)
{
for (const Plane& plane : planes)
{
if (plane.dot(Vector4(box.min.x, box.min.y, box.min.z, 1.0F)) < 0.0F &&
plane.dot(Vector4(box.max.x, box.min.y, box.min.z, 1.0F)) < 0.0F &&
plane.dot(Vector4(box.min.x, box.max.y, box.min.z, 1.0F)) < 0.0F &&
plane.dot(Vector4(box.min.x, box.min.y, box.max.z, 1.0F)) < 0.0F &&
plane.dot(Vector4(box.max.x, box.max.y, box.min.z, 1.0F)) < 0.0F &&
plane.dot(Vector4(box.max.x, box.min.y, box.max.z, 1.0F)) < 0.0F &&
plane.dot(Vector4(box.min.x, box.max.y, box.max.z, 1.0F)) < 0.0F &&
plane.dot(Vector4(box.max.x, box.max.y, box.max.z, 1.0F)) < 0.0F)
return false;
}
return true;
}
std::vector<Plane> planes;
};
}
<commit_msg>Optimize the isBoxInside method Make Plane's methods const<commit_after>// Copyright 2015-2018 Elviss Strazdins. All rights reserved.
#pragma once
#include <vector>
#include "math/Box3.hpp"
#include "math/Plane.hpp"
#include "math/Vector4.hpp"
namespace ouzel
{
class ConvexVolume
{
public:
ConvexVolume()
{
}
ConvexVolume(const std::vector<Plane>& initPlanes):
planes(initPlanes)
{
}
bool isPointInside(const Vector4& position) const
{
for (const Plane& plane : planes)
{
if (plane.dot(position) < 0.0F)
return false;
}
return true;
}
bool isSphereInside(const Vector4& position, float radius) const
{
for (const Plane& plane : planes)
{
if (plane.dot(position) < -radius)
return false;
}
return true;
}
bool isBoxInside(const Box3& box) const
{
Vector4 leftBottomBack(box.min.x, box.min.y, box.min.z, 1.0F);
Vector4 leftBottomFront(box.min.x, box.min.y, box.max.z, 1.0F);
Vector4 leftTopBack(box.min.x, box.max.y, box.min.z, 1.0F);
Vector4 leftTopFront(box.min.x, box.max.y, box.max.z, 1.0F);
Vector4 rightBottomBack(box.max.x, box.min.y, box.min.z, 1.0F);
Vector4 rightBottomFront(box.max.x, box.min.y, box.max.z, 1.0F);
Vector4 rightTopBack(box.max.x, box.max.y, box.min.z, 1.0F);
Vector4 rightTopFront(box.max.x, box.max.y, box.max.z, 1.0F);
for (const Plane& plane : planes)
{
if (plane.dot(leftBottomBack) < 0.0F &&
plane.dot(leftBottomFront) < 0.0F &&
plane.dot(leftTopBack) < 0.0F &&
plane.dot(leftTopFront) < 0.0F &&
plane.dot(rightBottomBack) < 0.0F &&
plane.dot(rightBottomFront) < 0.0F &&
plane.dot(rightTopBack) < 0.0F &&
plane.dot(rightTopFront) < 0.0F)
return false;
}
return true;
}
std::vector<Plane> planes;
};
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_configmgr.hxx"
#include "sal/config.h"
#include <cstddef>
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "osl/diagnose.hxx"
#include "rtl/string.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "span.hxx"
#include "xcdparser.hxx"
#include "xcsparser.hxx"
#include "xcuparser.hxx"
#include "xmldata.hxx"
#include "xmlreader.hxx"
namespace configmgr {
namespace {
namespace css = com::sun::star;
}
XcdParser::XcdParser(int layer, Dependencies const & dependencies, Data * data):
layer_(layer), dependencies_(dependencies), data_(data), state_(STATE_START)
{}
XcdParser::~XcdParser() {}
XmlReader::Text XcdParser::getTextMode() {
return nestedParser_.is()
? nestedParser_->getTextMode() : XmlReader::TEXT_NONE;
}
bool XcdParser::startElement(
XmlReader & reader, XmlReader::Namespace ns, Span const & name)
{
if (nestedParser_.is()) {
OSL_ASSERT(nesting_ != LONG_MAX);
++nesting_;
return nestedParser_->startElement(reader, ns, name);
}
switch (state_) {
case STATE_START:
if (ns == XmlReader::NAMESPACE_OOR &&
name.equals(RTL_CONSTASCII_STRINGPARAM("data")))
{
state_ = STATE_DEPENDENCIES;
return true;
}
break;
case STATE_DEPENDENCIES:
if (ns == XmlReader::NAMESPACE_NONE &&
name.equals(RTL_CONSTASCII_STRINGPARAM("dependency")))
{
if (dependency_.getLength() == 0) {
Span attrFile;
for (;;) {
XmlReader::Namespace attrNs;
Span attrLn;
if (!reader.nextAttribute(&attrNs, &attrLn)) {
break;
}
if (attrNs == XmlReader::NAMESPACE_NONE && //TODO: _OOR
attrLn.equals(RTL_CONSTASCII_STRINGPARAM("file")))
{
attrFile = reader.getAttributeValue(false);
}
}
if (!attrFile.is()) {
throw css::uno::RuntimeException(
(rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"no dependency file attribute in ")) +
reader.getUrl()),
css::uno::Reference< css::uno::XInterface >());
}
dependency_ = xmldata::convertFromUtf8(attrFile);
if (dependency_.getLength() == 0) {
throw css::uno::RuntimeException(
(rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"bad dependency file attribute in ")) +
reader.getUrl()),
css::uno::Reference< css::uno::XInterface >());
}
}
if (dependencies_.find(dependency_) == dependencies_.end()) {
return false;
}
state_ = STATE_DEPENDENCY;
dependency_ = rtl::OUString();
return true;
}
state_ = STATE_COMPONENTS;
// fall through
case STATE_COMPONENTS:
if (ns == XmlReader::NAMESPACE_OOR &&
name.equals(RTL_CONSTASCII_STRINGPARAM("component-schema")))
{
nestedParser_ = new XcsParser(layer_, data_);
nesting_ = 1;
return nestedParser_->startElement(reader, ns, name);
}
if (ns == XmlReader::NAMESPACE_OOR &&
name.equals(RTL_CONSTASCII_STRINGPARAM("component-data")))
{
nestedParser_ = new XcuParser(layer_ + 1, data_, 0);
nesting_ = 1;
return nestedParser_->startElement(reader, ns, name);
}
break;
default: // STATE_DEPENDENCY
OSL_ASSERT(false); // this cannot happen
break;
}
throw css::uno::RuntimeException(
(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("bad member <")) +
xmldata::convertFromUtf8(name) +
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("> in ")) + reader.getUrl()),
css::uno::Reference< css::uno::XInterface >());
}
void XcdParser::endElement(XmlReader const & reader) {
if (nestedParser_.is()) {
nestedParser_->endElement(reader);
if (--nesting_ == 0) {
nestedParser_.clear();
}
} else {
switch (state_) {
case STATE_DEPENDENCY:
state_ = STATE_DEPENDENCIES;
break;
case STATE_DEPENDENCIES:
case STATE_COMPONENTS:
break;
default:
OSL_ASSERT(false); // this cannot happen
break;
}
}
}
void XcdParser::characters(Span const & text) {
if (nestedParser_.is()) {
nestedParser_->characters(text);
}
}
}
<commit_msg>#i109991#<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_configmgr.hxx"
#include "sal/config.h"
#include <climits>
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "osl/diagnose.hxx"
#include "rtl/string.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "span.hxx"
#include "xcdparser.hxx"
#include "xcsparser.hxx"
#include "xcuparser.hxx"
#include "xmldata.hxx"
#include "xmlreader.hxx"
namespace configmgr {
namespace {
namespace css = com::sun::star;
}
XcdParser::XcdParser(int layer, Dependencies const & dependencies, Data * data):
layer_(layer), dependencies_(dependencies), data_(data), state_(STATE_START)
{}
XcdParser::~XcdParser() {}
XmlReader::Text XcdParser::getTextMode() {
return nestedParser_.is()
? nestedParser_->getTextMode() : XmlReader::TEXT_NONE;
}
bool XcdParser::startElement(
XmlReader & reader, XmlReader::Namespace ns, Span const & name)
{
if (nestedParser_.is()) {
OSL_ASSERT(nesting_ != LONG_MAX);
++nesting_;
return nestedParser_->startElement(reader, ns, name);
}
switch (state_) {
case STATE_START:
if (ns == XmlReader::NAMESPACE_OOR &&
name.equals(RTL_CONSTASCII_STRINGPARAM("data")))
{
state_ = STATE_DEPENDENCIES;
return true;
}
break;
case STATE_DEPENDENCIES:
if (ns == XmlReader::NAMESPACE_NONE &&
name.equals(RTL_CONSTASCII_STRINGPARAM("dependency")))
{
if (dependency_.getLength() == 0) {
Span attrFile;
for (;;) {
XmlReader::Namespace attrNs;
Span attrLn;
if (!reader.nextAttribute(&attrNs, &attrLn)) {
break;
}
if (attrNs == XmlReader::NAMESPACE_NONE && //TODO: _OOR
attrLn.equals(RTL_CONSTASCII_STRINGPARAM("file")))
{
attrFile = reader.getAttributeValue(false);
}
}
if (!attrFile.is()) {
throw css::uno::RuntimeException(
(rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"no dependency file attribute in ")) +
reader.getUrl()),
css::uno::Reference< css::uno::XInterface >());
}
dependency_ = xmldata::convertFromUtf8(attrFile);
if (dependency_.getLength() == 0) {
throw css::uno::RuntimeException(
(rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"bad dependency file attribute in ")) +
reader.getUrl()),
css::uno::Reference< css::uno::XInterface >());
}
}
if (dependencies_.find(dependency_) == dependencies_.end()) {
return false;
}
state_ = STATE_DEPENDENCY;
dependency_ = rtl::OUString();
return true;
}
state_ = STATE_COMPONENTS;
// fall through
case STATE_COMPONENTS:
if (ns == XmlReader::NAMESPACE_OOR &&
name.equals(RTL_CONSTASCII_STRINGPARAM("component-schema")))
{
nestedParser_ = new XcsParser(layer_, data_);
nesting_ = 1;
return nestedParser_->startElement(reader, ns, name);
}
if (ns == XmlReader::NAMESPACE_OOR &&
name.equals(RTL_CONSTASCII_STRINGPARAM("component-data")))
{
nestedParser_ = new XcuParser(layer_ + 1, data_, 0);
nesting_ = 1;
return nestedParser_->startElement(reader, ns, name);
}
break;
default: // STATE_DEPENDENCY
OSL_ASSERT(false); // this cannot happen
break;
}
throw css::uno::RuntimeException(
(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("bad member <")) +
xmldata::convertFromUtf8(name) +
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("> in ")) + reader.getUrl()),
css::uno::Reference< css::uno::XInterface >());
}
void XcdParser::endElement(XmlReader const & reader) {
if (nestedParser_.is()) {
nestedParser_->endElement(reader);
if (--nesting_ == 0) {
nestedParser_.clear();
}
} else {
switch (state_) {
case STATE_DEPENDENCY:
state_ = STATE_DEPENDENCIES;
break;
case STATE_DEPENDENCIES:
case STATE_COMPONENTS:
break;
default:
OSL_ASSERT(false); // this cannot happen
break;
}
}
}
void XcdParser::characters(Span const & text) {
if (nestedParser_.is()) {
nestedParser_->characters(text);
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
bool WaitForProcessCountToBe(int tabs, int workers) {
// The 1 is for the browser process.
int number_of_processes = 1 + workers +
(UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
// On Linux, we also have a zygote process and a sandbox host process.
number_of_processes += 2;
#endif
int cur_process_count;
for (int i = 0; i < 10; ++i) {
cur_process_count = GetBrowserProcessCount();
if (cur_process_count == number_of_processes)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(number_of_processes, cur_process_count);
return false;
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif
TEST_F(WorkerTest, WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
"use-machine-stack.html",
"worker-call.html",
"worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
// clearInterval() sometimes lets the timer continue to fire
// http://code.google.com/p/chromium/issues/detail?id=25548
// "worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
#if defined(OS_WIN)
// http://crbug.com/27636 - incorrect URL_MISMATCH exceptions sometimes get
// generated on the windows try bots.
#define SharedWorkerFastLayoutTests DISABLED_SharedWorkerFastLayoutTests
#endif
TEST_F(WorkerTest, SharedWorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"shared-worker-constructor.html",
"shared-worker-context-gc.html",
"shared-worker-event-listener.html",
"shared-worker-exception.html",
"shared-worker-gc.html",
// Lifecycle tests rely on layoutTestController.workerThreadCount which is
// not currently implemented.
//"shared-worker-frame-lifecycle.html",
//"shared-worker-lifecycle.html",
"shared-worker-load-error.html",
"shared-worker-location.html",
"shared-worker-name.html",
"shared-worker-navigator.html",
"shared-worker-replace-global-constructor.html",
"shared-worker-replace-self.html",
"shared-worker-script-error.html",
"shared-worker-shared.html",
"shared-worker-simple.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"shared-worker-importScripts.html",
"shared-worker-redirect.html",
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
// These tests (and the shared-worker versions below) are disabled due to
// limitations in lighttpd (doesn't handle all of the HTTP methods).
//"methods-async.html",
//"methods.html",
"shared-worker-close.html",
// Disabled due to limitations in lighttpd (does not handle methods other
// than GET/PUT/POST).
//"shared-worker-methods-async.html",
//"shared-worker-methods.html",
"shared-worker-xhr-file-not-found.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
"message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
"message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
// Now close a page and check that the queued workers were started.
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<commit_msg>Enable worker-timeout.html layout test. It's fixed upstream. TEST=worker-timeout.html BUG=25548 Review URL: http://codereview.chromium.org/396001<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
bool WaitForProcessCountToBe(int tabs, int workers) {
// The 1 is for the browser process.
int number_of_processes = 1 + workers +
(UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
// On Linux, we also have a zygote process and a sandbox host process.
number_of_processes += 2;
#endif
int cur_process_count;
for (int i = 0; i < 10; ++i) {
cur_process_count = GetBrowserProcessCount();
if (cur_process_count == number_of_processes)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(number_of_processes, cur_process_count);
return false;
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif
TEST_F(WorkerTest, WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
"use-machine-stack.html",
"worker-call.html",
"worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
"worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
#if defined(OS_WIN)
// http://crbug.com/27636 - incorrect URL_MISMATCH exceptions sometimes get
// generated on the windows try bots.
#define SharedWorkerFastLayoutTests DISABLED_SharedWorkerFastLayoutTests
#endif
TEST_F(WorkerTest, SharedWorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"shared-worker-constructor.html",
"shared-worker-context-gc.html",
"shared-worker-event-listener.html",
"shared-worker-exception.html",
"shared-worker-gc.html",
// Lifecycle tests rely on layoutTestController.workerThreadCount which is
// not currently implemented.
//"shared-worker-frame-lifecycle.html",
//"shared-worker-lifecycle.html",
"shared-worker-load-error.html",
"shared-worker-location.html",
"shared-worker-name.html",
"shared-worker-navigator.html",
"shared-worker-replace-global-constructor.html",
"shared-worker-replace-self.html",
"shared-worker-script-error.html",
"shared-worker-shared.html",
"shared-worker-simple.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"shared-worker-importScripts.html",
"shared-worker-redirect.html",
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
// These tests (and the shared-worker versions below) are disabled due to
// limitations in lighttpd (doesn't handle all of the HTTP methods).
//"methods-async.html",
//"methods.html",
"shared-worker-close.html",
// Disabled due to limitations in lighttpd (does not handle methods other
// than GET/PUT/POST).
//"shared-worker-methods-async.html",
//"shared-worker-methods.html",
"shared-worker-xhr-file-not-found.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
"message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
"message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
// Now close a page and check that the queued workers were started.
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.