hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e111110e518aadbdfbe6752d1effcf0144ba5230 | 4,940 | cpp | C++ | himan-plugins/source/hybrid_pressure.cpp | jrintala/fmi-data | 625f0a44919e6406440349425ee0b3f1a64a923d | [
"MIT"
] | null | null | null | himan-plugins/source/hybrid_pressure.cpp | jrintala/fmi-data | 625f0a44919e6406440349425ee0b3f1a64a923d | [
"MIT"
] | null | null | null | himan-plugins/source/hybrid_pressure.cpp | jrintala/fmi-data | 625f0a44919e6406440349425ee0b3f1a64a923d | [
"MIT"
] | null | null | null | /**
* @file hybrid_pressure.cpp
*
*/
#include "hybrid_pressure.h"
#include "forecast_time.h"
#include "level.h"
#include "logger.h"
#include "plugin_factory.h"
#include "util.h"
#include "cache.h"
#include "writer.h"
using namespace std;
using namespace himan::plugin;
mutex lnspMutex, mySingleFileWriteMutex;
map<string, himan::info_t> lnspInfos;
hybrid_pressure::hybrid_pressure()
{
itsLogger = logger("hybrid_pressure");
}
void hybrid_pressure::Process(std::shared_ptr<const plugin_configuration> conf)
{
Init(conf);
param p("P-HPA", 1, 0, 3, 0);
p.Unit(kHPa);
SetParams({p});
Start();
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void hybrid_pressure::Calculate(shared_ptr<info> myTargetInfo, unsigned short theThreadIndex)
{
params PParam{param("P-PA"), param("P-HPA")};
const param TParam("T-K");
level PLevel(himan::kHeight, 0, "HEIGHT");
bool isECMWF = (itsConfiguration->SourceProducer().Id() == 131 || itsConfiguration->SourceProducer().Id() == 134);
auto myThreadedLogger = logger("hybrid_pressureThread #" + to_string(theThreadIndex));
forecast_time forecastTime = myTargetInfo->Time();
level forecastLevel = myTargetInfo->Level();
forecast_type forecastType = myTargetInfo->ForecastType();
myThreadedLogger.Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " +
static_cast<string>(forecastLevel));
info_t PInfo;
if (isECMWF)
{
// For EC we calculate surface pressure from LNSP parameter
PLevel = level(himan::kHybrid, 1);
PParam = {param("LNSP-N")};
// To make calculation more efficient we calculate surface
// pressure once from LNSP and store it to cache as LNSP-PA
// Double-check pattern
const auto key = static_cast<string> (forecastType) + "_" + to_string(forecastTime.Step());
if (lnspInfos.find(key) == lnspInfos.end())
{
lock_guard<mutex> lock(lnspMutex);
if (lnspInfos.find(key) == lnspInfos.end())
{
PInfo = Fetch(forecastTime, PLevel, PParam, forecastType, false);
if (!PInfo)
{
myThreadedLogger.Warning("Skipping step " + to_string(forecastTime.Step()) + ", level " +
static_cast<string>(forecastLevel));
return;
}
myThreadedLogger.Info("Transforming LNSP to Pa");
for (auto& val : VEC(PInfo))
{
val = exp(val);
}
PInfo->SetParam(param("LNSP-PA"));
auto c = GET_PLUGIN(cache);
c->Insert(*PInfo, true);
lnspInfos[key] = PInfo;
}
}
PParam = {param("LNSP-PA")};
PInfo = Fetch(forecastTime, PLevel, PParam, forecastType, false);
}
else
{
PInfo = Fetch(forecastTime, PLevel, PParam, forecastType, false);
}
info_t TInfo = Fetch(forecastTime, forecastLevel, TParam, forecastType, false);
if (!PInfo || !TInfo)
{
myThreadedLogger.Warning("Skipping step " + to_string(forecastTime.Step()) + ", level " +
static_cast<string>(forecastLevel));
return;
}
SetAB(myTargetInfo, TInfo);
/*
* Vertical coordinates for full hybrid levels.
* For Hirlam data, coefficients A and B are already interpolated to full level coefficients in the grib-file.
* For Harmonie and ECMWF interpolation is done, when reading data from the grib-file. (NFmiGribMessage::PV)
*/
std::vector<double> ab = TInfo->Grid()->AB();
double A = kFloatMissing, B = kFloatMissing;
if (ab.size() == 2)
{
A = ab[0];
B = ab[1];
}
else
{
const size_t levelValue = static_cast<size_t>(forecastLevel.Value());
assert(levelValue <= ab.size());
A = (ab[levelValue - 1] + ab[levelValue]) * 0.5;
const size_t halfsize = static_cast<size_t>(static_cast<double>(ab.size()) * 0.5);
B = (ab[halfsize + levelValue - 1] + ab[halfsize + levelValue]) * 0.5;
}
auto& target = VEC(myTargetInfo);
for (auto&& tup : zip_range(target, VEC(PInfo)))
{
double& result = tup.get<0>();
double P = tup.get<1>();
if (P == kFloatMissing)
{
continue;
}
result = 0.01 * (A + P * B);
}
myThreadedLogger.Info("[CPU] Missing values: " + to_string(myTargetInfo->Data().MissingCount()) + "/" +
to_string(myTargetInfo->Data().Size()));
}
void hybrid_pressure::WriteToFile(const info& targetInfo, write_options writeOptions)
{
auto aWriter = GET_PLUGIN(writer);
writeOptions.write_empty_grid = false;
aWriter->WriteOptions(writeOptions);
// writing might modify iterator positions --> create a copy
auto tempInfo = targetInfo;
tempInfo.ResetParam();
while (tempInfo.NextParam())
{
if (itsConfiguration->FileWriteOption() == kDatabase || itsConfiguration->FileWriteOption() == kMultipleFiles)
{
aWriter->ToFile(tempInfo, itsConfiguration);
}
else
{
lock_guard<mutex> lock(mySingleFileWriteMutex);
aWriter->ToFile(tempInfo, itsConfiguration, itsConfiguration->ConfigurationFile());
}
}
if (itsConfiguration->UseDynamicMemoryAllocation())
{
DeallocateMemory(targetInfo);
}
}
| 23.75 | 115 | 0.676316 | [
"vector"
] |
e111ac4b4bf59dc724d77aeb91fd9641d7880969 | 2,726 | cpp | C++ | src/tools.cpp | Murasr/CarND-Extended-Kalman-Filter-Project | beb2524df15fcab5ea0cc4b2b7a7feb16d77378b | [
"MIT"
] | null | null | null | src/tools.cpp | Murasr/CarND-Extended-Kalman-Filter-Project | beb2524df15fcab5ea0cc4b2b7a7feb16d77378b | [
"MIT"
] | null | null | null | src/tools.cpp | Murasr/CarND-Extended-Kalman-Filter-Project | beb2524df15fcab5ea0cc4b2b7a7feb16d77378b | [
"MIT"
] | null | null | null | #include "tools.h"
#include <iostream>
using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;
Tools::Tools() {}
Tools::~Tools() {}
VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,
const vector<VectorXd> &ground_truth) {
/**
* TODO: Calculate the RMSE here.
*/
VectorXd rmse(4);
rmse << 0, 0, 0, 0;
if(estimations.size() != 0)
{
if(estimations.size() == ground_truth.size())
{
VectorXd sum(4);
sum << 0, 0, 0, 0;
for(int count = 0; count < estimations.size(); count++)
{
VectorXd diff = (estimations[count] - ground_truth[count]);
VectorXd mul = (diff.array() * diff.array());
sum += mul;
}
rmse = (sum.array())/estimations.size();
rmse = rmse.array().sqrt();
}
else
{
std::cout << "RMSE: estimations size and gt size not equal " << std::endl;
}
}
else
{
std::cout << "RMSE: estimations size is zero " << std::endl;
}
return rmse;
}
MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) {
/**
* TODO:
* Calculate a Jacobian here.
*/
MatrixXd Hj(3, 4);
Hj << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
double px = x_state(0);
double py = x_state(1);
double vx = x_state(2);
double vy = x_state(3);
double p_sqr = (px*px + py*py);
if(0 < p_sqr)
{
double p_sqroot = sqrt(p_sqr);
double p_sq_3_by_2 = p_sqr * p_sqroot;
Hj << px/p_sqroot, py/p_sqroot, 0, 0,
-1 * py/p_sqr, px/p_sqr, 0, 0,
py*(vx*py - vy*px)/p_sq_3_by_2, px*(vy*px - vx*py)/p_sq_3_by_2, px/p_sqroot, py/p_sqroot;
}
else
{
std::cout << "Jacobian: Position square is zero " << std::endl;
}
return Hj;
/* MatrixXd Hj(3, 4);
const double APPROX_ZERO = 0.0001;
// Unpack the state vector
double px = x_state(0);
double py = x_state(1);
double vx = x_state(2);
double vy = x_state(3);
// Calculate frequently used calculations
double px2 = px * px;
double py2 = py * py;
// If px2 is zero set it to a small value
if (fabs(px2) < APPROX_ZERO) {
px2 = APPROX_ZERO;
}
// If py2 is zero set it to a small value
if (fabs(py2) < APPROX_ZERO) {
py2 = APPROX_ZERO;
}
double ss = px2 + py2;
double srss = sqrt(ss);
// Create the Jacobian
Hj(0, 0) = px / srss;
Hj(0, 1) = py / srss;
Hj(0, 2) = 0;
Hj(0, 3) = 0;
Hj(1, 0) = -py / ss;
Hj(1, 1) = px / ss;
Hj(1, 2) = 0;
Hj(1, 3) = 0;
Hj(2, 0) = (py * (vx * py - px * vy)) / (ss * srss);
Hj(2, 1) = (px * (vy * px - py * vx)) / (ss * srss);
Hj(2, 2) = px / srss;
Hj(2, 3) = py / srss;
return Hj;*/
}
| 22.344262 | 99 | 0.532649 | [
"vector"
] |
e113c1223a86475927125e5f876fd2311dddf241 | 4,591 | hpp | C++ | modules/optimisation/include/facekit/optimisation/genetic_solver.hpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | null | null | null | modules/optimisation/include/facekit/optimisation/genetic_solver.hpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | null | null | null | modules/optimisation/include/facekit/optimisation/genetic_solver.hpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | 1 | 2017-11-29T12:03:08.000Z | 2017-11-29T12:03:08.000Z | /**
* @file genetic_solver.hpp
* @brief Genetic Solver implementation of "Genetic algorithms for modelling
* and optimisation"
* @ingroup optimisation
*
* @author Christophe Ecabert
* @date 10.04.18
* Copyright © 2018 Christophe Ecabert. All rights reserved.
*/
#ifndef __FACEKIT_GENETIC_SOLVER__
#define __FACEKIT_GENETIC_SOLVER__
#include "facekit/core/library_export.hpp"
#include "facekit/optimisation/population.hpp"
/**
* @namespace FaceKit
* @brief Development space
*/
namespace FaceKit {
/**
* @class GeneticSolver
* @brief Implementation of "Genetic algorithms for modelling
* and optimisation"
* @author Christophe Ecabert
* @date 10/04/18
* @ingroup optimisation
* @tparam T Data type
*/
template<typename T>
class FK_EXPORTS GeneticSolver {
public:
#pragma mark -
#pragma mark Type Definition
/** Chromosome */
using ChromosomeType = typename Population<T>::ChromosomeType;
/** Chromosome constructor callback */
using ChromosomeCtor = typename Population<T>::ChromosomeCtor;
/**
* @struct Parameters
* @brief Solver configuration
* @author Christophe Ecabert
* @date 10/04/18
* @ingroup optimisation
*/
struct Parameters {
/** CrossOver probability */
T p_crossover;
/** Mutation probability */
T p_mutation;
/** Fitness target */
T fitness_target;
/** Number max of generation/iteration */
size_t max_generation;
/** Fitness increase minimum in percentage */
T percentage_fitness;
/** Number of generation at maximum fitness before stopping */
size_t n_max_fitness_generation;
/**
* @name Parameters
* @fn Parameters(void)
* @brief Cnstructor
*/
Parameters(void) : p_crossover(0.8), p_mutation(0.02), max_generation(50), percentage_fitness(5.0), n_max_fitness_generation(5) {}
};
/**
* @enum ConvergenceType
* @brief List of convergence
*/
enum class ConvergenceType : int8_t {
/** Maximum number of generation reached */
kReachMaxGeneration = 0,
/** Reach convergence criteria */
kConverged
};
#pragma mark -
#pragma mark Initialisation
/**
* @name GeneticSolver
* @fn GeneticSolver(const size_t& pop_size, const size_t& chromo_size,
* const ChromosomeCtor& ctor)
* @brief Constructor
* @param[in] pop_size Population size (Number of chromosomes)
* @param[in] chromo_size Size of one chromosome
* @param[in] ctor Callback creating a derived chromosome
*/
GeneticSolver(const size_t& pop_size,
const size_t& chromo_size,
const ChromosomeCtor& ctor);
/**
* @name GeneticSolver
* @fn GeneticSolver(const GeneticSolver& other) = delete
* @brief Copy constructor
* @param[in] other Object to copy from
*/
GeneticSolver(const GeneticSolver& other) = delete;
/**
* @name operator=
* @fn GeneticSolver& operator=(const GeneticSolver& rhs) = delete
* @brief Assignment operator
* @param[in] rhs Object to assign from
* @return Newly assigned operator
*/
GeneticSolver& operator=(const GeneticSolver& rhs) = delete;
/**
* @name ~GeneticSolver
* @fn ~GeneticSolver(void)
* @brief Destructor
*/
~GeneticSolver(void);
#pragma mark -
#pragma mark Usage
/**
* @name Solve
* @fn ConvergenceType Solve(const Parameters& params)
* @brief Solve the given optimisation problem
* @param[in] params Configuration
*/
ConvergenceType Solve(const Parameters& params);
/**
* @name BestFitness
* @fn ChromosomeType* BestFitness(void) const
* @brief Give the chromosome with the best fitness
* @return Chromosome with solution
*/
ChromosomeType* BestFitness(void) const;
#pragma mark -
#pragma mark Accessors
#pragma mark -
#pragma mark Private
private:
/**
* @name CrossOver
* @fn void CrossOver(const T& rate)
* @brief Perform crossover
* @param[in] rate Crossover rate
*/
void CrossOver(const T& rate);
/**
* @name Mutate
* @fn void Mutate(const T& rate)
* @brief Perform mutation
* @param[in] rate Mutation rate
*/
void Mutate(const T& rate);
/** Current population */
Population<T>* curr_population_;
/** Next population */
Population<T>* next_population_;
/** Chromosome length */
size_t chromo_length_;
};
} // namespace FaceKit
#endif /* __FACEKIT_GENETIC_SOLVER__ */
| 25.364641 | 134 | 0.648007 | [
"object"
] |
e114a94f122dbf350e8436ec483b0f0c624ed150 | 2,792 | hpp | C++ | packages/monte_carlo/core/src/MonteCarlo_PositronState.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/monte_carlo/core/src/MonteCarlo_PositronState.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/monte_carlo/core/src/MonteCarlo_PositronState.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_PositronState.hpp
//! \author Luke Kersting
//! \brief Positron state class declaration
//!
//---------------------------------------------------------------------------//
#ifndef MONTE_CARLO_POSITRON_STATE_HPP
#define MONTE_CARLO_POSITRON_STATE_HPP
// Boost Includes
#include <boost/serialization/shared_ptr.hpp>
// FRENSIE Includes
#include "MonteCarlo_ChargedParticleState.hpp"
#include "Utility_TypeNameTraits.hpp"
namespace MonteCarlo{
//! The positron state class
class PositronState : public MonteCarlo::ChargedParticleState
{
private:
// Typedef for QuantityTraits
typedef Utility::QuantityTraits<double> QT;
public:
// The positron tag
struct PositronTag{};
// Typedef for the positron tag
typedef PositronTag ParticleTag;
//! The particle state type (for compile time usage)
static const ParticleType type = POSITRON;
//! Default constructor
PositronState();
//! Constructor
PositronState( const ParticleState::historyNumberType history_number );
//! Copy constructor (with possible creation of new generation)
PositronState( const PositronState& existing_positron_state,
const bool increment_generation_number = false,
const bool reset_collision_number = false );
//! Copy constructor (with possible creation of new generation)
PositronState( const ParticleState& existing_base_state,
const bool increment_generation_number = false,
const bool reset_collision_number = false );
//! Destructor
~PositronState()
{ /* ... */ }
//! Return the rest mass energy of the positron (MeV)
double getRestMassEnergy() const;
//! Clone the particle state (do not use to generate new particles!)
PositronState* clone() const;
//! Print the positron state
void toStream( std::ostream& os ) const;
private:
// Save the state to an archive
template<typename Archive>
void serialize( Archive& ar, const unsigned version )
{ ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(ChargedParticleState); }
// Declare the boost serialization access object as a friend
friend class boost::serialization::access;
};
} // end MonteCarlo namespace
BOOST_SERIALIZATION_CLASS_VERSION( PositronState, MonteCarlo, 0 );
BOOST_SERIALIZATION_CLASS_EXPORT_STANDARD_KEY( PositronState, MonteCarlo );
EXTERN_EXPLICIT_CLASS_SERIALIZE_INST( MonteCarlo, PositronState );
TYPE_NAME_TRAITS_QUICK_DECL2( PositronState, MonteCarlo );
#endif // end MonteCarlo_POSITRON_STATE_HPP
//---------------------------------------------------------------------------//
// end MonteCarlo_PositronState.hpp
//---------------------------------------------------------------------------//
| 30.021505 | 79 | 0.664398 | [
"object"
] |
e120592a065df3733b8a91f7c7d1f6d3812bd090 | 11,056 | cpp | C++ | src/metaspades/src/projects/hammer/hammer_tools.cpp | STRIDES-Codes/Exploring-the-Microbiome- | bd29c8c74d8f40a58b63db28815acb4081f20d6b | [
"MIT"
] | null | null | null | src/metaspades/src/projects/hammer/hammer_tools.cpp | STRIDES-Codes/Exploring-the-Microbiome- | bd29c8c74d8f40a58b63db28815acb4081f20d6b | [
"MIT"
] | null | null | null | src/metaspades/src/projects/hammer/hammer_tools.cpp | STRIDES-Codes/Exploring-the-Microbiome- | bd29c8c74d8f40a58b63db28815acb4081f20d6b | [
"MIT"
] | 2 | 2021-06-05T07:40:20.000Z | 2021-06-05T08:02:58.000Z | //***************************************************************************
//* Copyright (c) 2015 Saint Petersburg State University
//* Copyright (c) 2011-2014 Saint Petersburg Academic University
//* All Rights Reserved
//* See file LICENSE for details.
//***************************************************************************
#include "hammer_tools.hpp"
#include "valid_kmer_generator.hpp"
#include "globals.hpp"
#include "kmer_data.hpp"
#include "read_corrector.hpp"
#include "io/reads/ireadstream.hpp"
#include "io/kmers/mmapped_writer.hpp"
#include "utils/filesystem/path_helper.hpp"
#include <iostream>
#include <fstream>
#include <iomanip>
#include "config_struct_hammer.hpp"
using namespace std;
namespace hammer {
void InitializeSubKMerPositions(int tau) {
std::ostringstream log_sstream;
log_sstream.str("");
Globals::subKMerPositions = new std::vector<uint32_t>(tau + 2);
for (uint32_t i=0; i < (uint32_t)(tau + 1); ++i) {
Globals::subKMerPositions->at(i) = (i * K / (tau + 1) );
log_sstream << Globals::subKMerPositions->at(i) << " ";
}
Globals::subKMerPositions->at(tau + 1) = K;
INFO("Hamming graph threshold tau=" << cfg::get().general_tau << ", k=" << K << ", subkmer positions = [ " << log_sstream.str() << "]" );
}
std::string getFilename(const string & dirprefix, const string & suffix) {
std::ostringstream tmp;
tmp.str(""); tmp << dirprefix.data() << "/" << suffix.data();
return tmp.str();
}
string getFilename(const string & dirprefix, unsigned iter_count, const string & suffix ) {
ostringstream tmp;
tmp.str(""); tmp << dirprefix.data() << "/" << std::setfill('0') << std::setw(2) << iter_count << "." << suffix.data();
return tmp.str();
}
string getReadsFilename(const std::string & dirprefix, const std::string &fname, unsigned iter_no, const std::string & suffix) {
ostringstream tmp;
tmp.str("");
tmp << dirprefix.data() << "/" << fs::basename(fname) << '.' << std::setfill('0') << std::setw(2) << iter_no << "." << suffix.data();
return tmp.str();
}
string getFilename( const string & dirprefix, const string & suffix, int suffix_num ) {
ostringstream tmp;
tmp.str(""); tmp << dirprefix.data() << "/" << suffix.data() << "." << suffix_num;
return tmp.str();
}
string getFilename( const string & dirprefix, int iter_count, const string & suffix, int suffix_num ) {
ostringstream tmp;
tmp.str(""); tmp << dirprefix.data() << "/" << std::setfill('0') << std::setw(2) << iter_count << "." << suffix.data() << "." << suffix_num;
return tmp.str();
}
string getFilename( const string & dirprefix, int iter_count, const string & suffix, int suffix_num, const string & suffix2 ) {
ostringstream tmp;
tmp.str(""); tmp << dirprefix.data() << "/" << std::setfill('0') << std::setw(2) << iter_count << "." << suffix.data() << "." << suffix_num << "." << suffix2.data();
return tmp.str();
}
CorrectionStats CorrectReadsBatch(std::vector<bool> &res,
std::vector<Read> &reads, size_t buf_size,
const KMerData &data) {
unsigned correct_nthreads = min(cfg::get().correct_nthreads, cfg::get().general_max_nthreads);
bool discard_singletons = cfg::get().bayes_discard_only_singletons;
bool correct_threshold = cfg::get().correct_use_threshold;
bool discard_bad = cfg::get().correct_discard_bad;
ReadCorrector corrector(data, cfg::get().correct_stats);
# pragma omp parallel for shared(reads, res, data) num_threads(correct_nthreads)
for (size_t i = 0; i < buf_size; ++i) {
if (reads[i].size() >= K) {
res[i] =
corrector.CorrectOneRead(reads[i],
correct_threshold, discard_singletons, discard_bad);
} else
res[i] = false;
}
CorrectionStats stats;
stats.changedReads += corrector.changed_reads();
stats.changedNucleotides += corrector.changed_nucleotides();
stats.uncorrectedNucleotides += corrector.uncorrected_nucleotides();
stats.totalNucleotides += corrector.total_nucleotides();
return stats;
}
CorrectionStats CorrectReadFile(const KMerData &data,
const std::string &fname,
std::ofstream *outf_good, std::ofstream *outf_bad) {
int qvoffset = cfg::get().input_qvoffset;
int trim_quality = cfg::get().input_trim_quality;
unsigned correct_nthreads = min(cfg::get().correct_nthreads, cfg::get().general_max_nthreads);
size_t read_buffer_size = correct_nthreads * cfg::get().correct_readbuffer;
std::vector<Read> reads(read_buffer_size);
std::vector<bool> res(read_buffer_size, false);
ireadstream irs(fname, qvoffset);
VERIFY(irs.is_open());
unsigned buffer_no = 0;
CorrectionStats stats;
while (!irs.eof()) {
size_t buf_size = 0;
for (; buf_size < read_buffer_size && !irs.eof(); ++buf_size) {
irs >> reads[buf_size];
reads[buf_size].trimNsAndBadQuality(trim_quality);
}
INFO("Prepared batch " << buffer_no << " of " << buf_size << " reads.");
stats += CorrectReadsBatch(res, reads, buf_size,
data);
INFO("Processed batch " << buffer_no);
for (size_t i = 0; i < buf_size; ++i) {
reads[i].print(*(res[i] ? outf_good : outf_bad), qvoffset);
}
INFO("Written batch " << buffer_no);
++buffer_no;
}
return stats;
}
CorrectionStats CorrectPairedReadFiles(const KMerData &data,
const std::string &fnamel, const std::string &fnamer,
ofstream * ofbadl, ofstream * ofcorl, ofstream * ofbadr, ofstream * ofcorr, ofstream * ofunp) {
int qvoffset = cfg::get().input_qvoffset;
int trim_quality = cfg::get().input_trim_quality;
unsigned correct_nthreads = min(cfg::get().correct_nthreads, cfg::get().general_max_nthreads);
size_t read_buffer_size = correct_nthreads * cfg::get().correct_readbuffer;
std::vector<Read> l(read_buffer_size);
std::vector<Read> r(read_buffer_size);
std::vector<bool> left_res(read_buffer_size, false);
std::vector<bool> right_res(read_buffer_size, false);
unsigned buffer_no = 0;
ireadstream irsl(fnamel, qvoffset), irsr(fnamer, qvoffset);
VERIFY(irsl.is_open()); VERIFY(irsr.is_open());
CorrectionStats stats;
while (!irsl.eof() && !irsr.eof()) {
size_t buf_size = 0;
for (; buf_size < read_buffer_size && !irsl.eof() && !irsr.eof(); ++buf_size) {
irsl >> l[buf_size]; irsr >> r[buf_size];
l[buf_size].trimNsAndBadQuality(trim_quality);
r[buf_size].trimNsAndBadQuality(trim_quality);
}
INFO("Prepared batch " << buffer_no << " of " << buf_size << " reads.");
stats += CorrectReadsBatch(left_res, l, buf_size,
data);
stats += CorrectReadsBatch(right_res, r, buf_size,
data);
INFO("Processed batch " << buffer_no);
for (size_t i = 0; i < buf_size; ++i) {
if (left_res[i] && right_res[i]) {
l[i].print(*ofcorl, qvoffset);
r[i].print(*ofcorr, qvoffset);
} else {
l[i].print(*(left_res[i] ? ofunp : ofbadl), qvoffset);
r[i].print(*(right_res[i] ? ofunp : ofbadr), qvoffset);
}
}
INFO("Written batch " << buffer_no);
++buffer_no;
}
if (!irsl.eof() || !irsr.eof())
FATAL_ERROR("Pair of read files " + fnamel + " and " + fnamer + " contain unequal amount of reads");
return stats;
}
std::string getLargestPrefix(const std::string &str1, const std::string &str2) {
string substr = "";
for (size_t i = 0; i != str1.size() && i != str2.size(); ++i) {
if (str1[i] == str2[i])
substr += str1[i];
else
break;
}
return substr;
}
std::string CorrectSingleReadSet(size_t ilib, size_t iread, const std::string &fn, CorrectionStats &stats) {
std::string usuffix = std::to_string(ilib) + "_" +
std::to_string(iread) + ".cor.fastq";
std::string outcor = getReadsFilename(cfg::get().output_dir, fn, Globals::iteration_no, usuffix);
std::ofstream ofgood(outcor.c_str());
std::ofstream ofbad(getReadsFilename(cfg::get().output_dir, fn, Globals::iteration_no, "bad.fastq").c_str(),
std::ios::out | std::ios::ate);
stats += CorrectReadFile(*Globals::kmer_data, fn, &ofgood, &ofbad);
return outcor;
}
size_t CorrectAllReads() {
// Now for the reconstruction step; we still have the reads in rv, correcting them in place.
int correct_nthreads = std::min(cfg::get().correct_nthreads, cfg::get().general_max_nthreads);
INFO("Starting read correction in " << correct_nthreads << " threads.");
CorrectionStats stats;
const io::DataSet<> &dataset = cfg::get().dataset;
io::DataSet<> outdataset;
size_t ilib = 0;
for (const auto& lib : dataset.libraries()) {
auto outlib = lib;
outlib.clear();
size_t iread = 0;
for (auto I = lib.paired_begin(), E = lib.paired_end(); I != E; ++I, ++iread) {
INFO("Correcting pair of reads: " << I->first << " and " << I->second);
std::string usuffix = std::to_string(ilib) + "_" +
std::to_string(iread) + ".cor.fastq";
std::string unpaired = getLargestPrefix(I->first, I->second) + "_unpaired.fastq";
std::string outcorl = getReadsFilename(cfg::get().output_dir, I->first, Globals::iteration_no, usuffix);
std::string outcorr = getReadsFilename(cfg::get().output_dir, I->second, Globals::iteration_no, usuffix);
std::string outcoru = getReadsFilename(cfg::get().output_dir, unpaired, Globals::iteration_no, usuffix);
std::ofstream ofcorl(outcorl.c_str());
std::ofstream ofbadl(getReadsFilename(cfg::get().output_dir, I->first, Globals::iteration_no, "bad.fastq").c_str(),
std::ios::out | std::ios::ate);
std::ofstream ofcorr(outcorr.c_str());
std::ofstream ofbadr(getReadsFilename(cfg::get().output_dir, I->second, Globals::iteration_no, "bad.fastq").c_str(),
std::ios::out | std::ios::ate);
std::ofstream ofunp (outcoru.c_str());
stats += CorrectPairedReadFiles(*Globals::kmer_data,
I->first, I->second,
&ofbadl, &ofcorl, &ofbadr, &ofcorr, &ofunp);
outlib.push_back_paired(outcorl, outcorr);
outlib.push_back_single(outcoru);
}
for (auto I = lib.merged_begin(), E = lib.merged_end(); I != E; ++I, ++iread) {
INFO("Correcting merged reads: " << *I);
outlib.push_back_merged(CorrectSingleReadSet(ilib, iread, *I, stats));
}
for (auto I = lib.single_begin(), E = lib.single_end(); I != E; ++I, ++iread) {
INFO("Correcting single reads: " << *I);
outlib.push_back_single(CorrectSingleReadSet(ilib, iread, *I, stats));
}
outdataset.push_back(outlib);
ilib += 1;
}
cfg::get_writable().dataset = outdataset;
INFO("Correction done. Changed " << stats.changedNucleotides << " bases in " << stats.changedReads << " reads.");
INFO("Failed to correct " << stats.uncorrectedNucleotides << " bases out of " << stats.totalNucleotides << ".");
return stats.changedReads;
}
};
| 39.205674 | 167 | 0.628075 | [
"vector"
] |
e120faf6d5d66418523d20fa292fe41353892769 | 820 | cpp | C++ | 132.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 132.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 132.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ull = uint64_t;
using ll = int64_t;
using ld = long double;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
class Solution
{
public:
vi memo;
bool isPalindrome(const string& s, int start, int end)
{
int i = start, j = end - 1;
while (i < j)
{
if (s[i] != s[j])
return false;
i++;
j--;
}
return true;
}
int countMinCut(const string& s, int start)
{
if (start == s.size())
return 0;
if (memo[start] != -1)
return memo[start];
int ret = INT_MAX;
for (int i = start + 1; i <= s.size(); ++i)
{
if (isPalindrome(s, start, i))
ret = min(ret, 1 + countMinCut(s, i));
}
return memo[start] = ret;
}
int minCut(string s)
{
memo.assign(s.size(), -1);
return countMinCut(s, 0) - 1;
}
};
| 17.083333 | 55 | 0.584146 | [
"vector"
] |
e12176fbcef6958dd2662ae2cc5c33179a8c8c29 | 9,200 | cpp | C++ | src/SSVOpenHexagon/Global/Assets.cpp | mehlon/SSVOpenHexagon | a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad | [
"AFL-3.0"
] | null | null | null | src/SSVOpenHexagon/Global/Assets.cpp | mehlon/SSVOpenHexagon | a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad | [
"AFL-3.0"
] | null | null | null | src/SSVOpenHexagon/Global/Assets.cpp | mehlon/SSVOpenHexagon | a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad | [
"AFL-3.0"
] | null | null | null | // Copyright (c) 2013-2015 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
#include "SSVOpenHexagon/Global/Assets.hpp"
#include "SSVOpenHexagon/Global/Config.hpp"
#include "SSVOpenHexagon/Online/Definitions.hpp"
#include "SSVOpenHexagon/Online/Online.hpp"
#include "SSVOpenHexagon/Utils/Utils.hpp"
#include "SSVOpenHexagon/Data/MusicData.hpp"
using namespace std;
using namespace sf;
using namespace ssvs;
using namespace hg::Utils;
using namespace ssvu;
using namespace ssvuj;
using namespace ssvu::FileSystem;
namespace hg
{
HGAssets::HGAssets(bool mLevelsOnly) : levelsOnly{mLevelsOnly}
{
if(!levelsOnly)
loadAssetsFromJson(
assetManager, "Assets/", getFromFile("Assets/assets.json"));
loadAssets();
for(auto& v : levelDataIdsByPack)
ssvu::sort(v.second, [&](const auto& mA, const auto& mB)
{
return levelDatas[mA]->menuPriority <
levelDatas[mB]->menuPriority;
});
ssvu::sort(packIds, [&](const auto& mA, const auto& mB)
{
return packDatas[mA]->priority < packDatas[mB]->priority;
});
}
void HGAssets::loadAssets()
{
lo("::loadAssets") << "loading local profiles\n";
loadLocalProfiles();
for(const auto& packPath :
getScan<Mode::Single, Type::Folder>("Packs/"))
{
const auto& packPathStr(packPath.getStr());
string packName{packPathStr.substr(6, packPathStr.size() - 7)},
packLua;
for(const auto& p : getScan<Mode::Recurse, Type::File, Pick::ByExt>(
packPath, ".lua"))
packLua.append(p.getContentsAsStr());
ssvuj::Obj packRoot{getFromFile(packPath + "/pack.json")};
ssvu::getEmplaceUPtrMap<PackData>(packDatas, packName, packName,
getExtr<string>(packRoot, "name"),
getExtr<float>(packRoot, "priority"));
}
for(auto& p : packDatas)
{
const auto& pd(p.second);
string packId{pd->id}, packPath{"Packs/" + packId + "/"};
packIds.emplace_back(packId);
packPaths.emplace_back(packPath);
try
{
if(!levelsOnly)
{
lo("::loadAssets") << "loading " << packId << " music\n";
loadMusic(packPath);
}
if(!levelsOnly)
{
lo("::loadAssets") << "loading " << packId
<< " music data\n";
loadMusicData(packPath);
}
lo("::loadAssets") << "loading " << packId << " style data\n";
loadStyleData(packPath);
lo("::loadAssets") << "loading " << packId << " level data\n";
loadLevelData(packPath);
if(!levelsOnly &&
Path(packPath + "Sounds/").exists<ssvufs::Type::Folder>())
{
lo("::loadAssets") << "loading " << packId
<< " custom sounds\n";
loadCustomSounds(packId, packPath);
}
}
catch(const std::runtime_error& mEx)
{
ssvu::lo("FATAL ERROR")
<< "Exception during asset loading: " << mEx.what()
<< std::endl;
}
catch(...)
{
ssvu::lo("FATAL ERROR")
<< "Exception during asset loading: unknown." << std::endl;
}
lo().flush();
}
}
void HGAssets::loadCustomSounds(const string& mPackName, const Path& mPath)
{
for(const auto& p : getScan<Mode::Single, Type::File, Pick::ByExt>(
mPath + "Sounds/", ".ogg"))
assetManager.load<SoundBuffer>(
mPackName + "_" + p.getFileName(), p);
}
void HGAssets::loadMusic(const Path& mPath)
{
for(const auto& p : getScan<Mode::Single, Type::File, Pick::ByExt>(
mPath + "Music/", ".ogg"))
{
auto& music(
assetManager.load<Music>(p.getFileNameNoExtensions(), p));
music.setVolume(Config::getMusicVolume());
music.setLoop(true);
}
}
void HGAssets::loadMusicData(const Path& mPath)
{
for(const auto& p : getScan<Mode::Single, Type::File, Pick::ByExt>(
mPath + "Music/", ".json"))
{
MusicData musicData{loadMusicFromJson(getFromFile(p))};
musicDataMap.insert(make_pair(musicData.id, musicData));
}
}
void HGAssets::loadStyleData(const Path& mPath)
{
for(const auto& p : getScan<Mode::Single, Type::File, Pick::ByExt>(
mPath + "Styles/", ".json"))
{
StyleData styleData{getFromFile(p), p};
styleDataMap.insert(make_pair(styleData.id, styleData));
}
}
void HGAssets::loadLevelData(const Path& mPath)
{
for(const auto& p : getScan<Mode::Single, Type::File, Pick::ByExt>(
mPath + "Levels/", ".json"))
{
auto levelData(new LevelData{getFromFile(p), mPath});
levelDataIdsByPack[levelData->packPath].emplace_back(levelData->id);
levelDatas.insert(
make_pair(levelData->id, UPtr<LevelData>(levelData)));
}
}
void HGAssets::loadLocalProfiles()
{
for(const auto& p : getScan<Mode::Single, Type::File, Pick::ByExt>(
"Profiles/", ".json"))
{
// string fileName{getNameFromPath(p, "Profiles/", ".json")};
ProfileData profileData{loadProfileFromJson(getFromFile(p))};
profileDataMap.insert(
make_pair(profileData.getName(), profileData));
}
}
void HGAssets::saveCurrentLocalProfile()
{
if(currentProfilePtr == nullptr) return;
ssvuj::Obj profileRoot;
ssvuj::arch(profileRoot, "version", Config::getVersion());
ssvuj::arch(profileRoot, "name", getCurrentLocalProfile().getName());
ssvuj::arch(
profileRoot, "scores", getCurrentLocalProfile().getScores());
for(const auto& n : getCurrentLocalProfile().getTrackedNames())
profileRoot["trackedNames"].append(n);
ssvuj::writeToFile(profileRoot, getCurrentLocalProfileFilePath());
}
const MusicData& SSVU_ATTRIBUTE(pure) HGAssets::getMusicData(
const string& mId)
{
return musicDataMap.find(mId)->second;
}
const StyleData& SSVU_ATTRIBUTE(pure) HGAssets::getStyleData(
const string& mId)
{
return styleDataMap.find(mId)->second;
}
float HGAssets::getLocalScore(const string& mId)
{
return getCurrentLocalProfile().getScore(mId);
}
void HGAssets::setLocalScore(const string& mId, float mScore)
{
getCurrentLocalProfile().setScore(mId, mScore);
}
void HGAssets::setCurrentLocalProfile(const string& mName)
{
currentProfilePtr = &profileDataMap.find(mName)->second;
}
ProfileData& SSVU_ATTRIBUTE(pure) HGAssets::getCurrentLocalProfile()
{
return *currentProfilePtr;
}
const ProfileData& SSVU_ATTRIBUTE(
pure) HGAssets::getCurrentLocalProfile() const
{
return *currentProfilePtr;
}
string HGAssets::getCurrentLocalProfileFilePath()
{
return "Profiles/" + currentProfilePtr->getName() + ".json";
}
void HGAssets::createLocalProfile(const string& mName)
{
ssvuj::Obj root;
ssvuj::arch(root, "name", mName);
ssvuj::arch(root, "scores", ssvuj::Obj{});
ssvuj::writeToFile(root, "Profiles/" + mName + ".json");
profileDataMap.clear();
loadLocalProfiles();
}
SizeT SSVU_ATTRIBUTE(pure) HGAssets::getLocalProfilesSize() { return profileDataMap.size(); }
vector<string> HGAssets::getLocalProfileNames()
{
vector<string> result;
for(auto& pair : profileDataMap)
result.emplace_back(pair.second.getName());
return result;
}
string HGAssets::getFirstLocalProfileName()
{
return begin(profileDataMap)->second.getName();
}
void HGAssets::refreshVolumes()
{
soundPlayer.setVolume(Config::getSoundVolume());
musicPlayer.setVolume(Config::getMusicVolume());
}
void HGAssets::stopMusics() { musicPlayer.stop(); }
void HGAssets::stopSounds() { soundPlayer.stop(); }
void HGAssets::playSound(const string& mId, SoundPlayer::Mode mMode)
{
if(Config::getNoSound() || !assetManager.has<SoundBuffer>(mId)) return;
soundPlayer.play(assetManager.get<SoundBuffer>(mId), mMode);
}
void HGAssets::playMusic(const string& mId, Time mPlayingOffset)
{
if(assetManager.has<Music>(mId))
musicPlayer.play(assetManager.get<Music>(mId), mPlayingOffset);
}
}
| 34.716981 | 97 | 0.562174 | [
"vector"
] |
e12c9205c35300f07197a5e5d3dd168a3b9fc369 | 8,113 | hpp | C++ | include/hpritl.hpp | stillwater-sc/hpr-itl | b9cb650054be432189257e51af943138f3970eee | [
"MIT"
] | 8 | 2018-10-31T10:22:02.000Z | 2020-07-31T22:24:22.000Z | include/hpritl.hpp | stillwater-sc/hpr-itl | b9cb650054be432189257e51af943138f3970eee | [
"MIT"
] | 1 | 2019-04-01T12:49:45.000Z | 2019-04-01T12:49:45.000Z | examples/positdot/include/blas.hpp | lvandam/posit_blas_hdl | 4427bcf13cede86f626772903c546cbeae42457e | [
"Apache-2.0"
] | 1 | 2019-10-25T07:09:36.000Z | 2019-10-25T07:09:36.000Z | #pragma once
// blas.hpp : include file containing templated C++ interfaces to BLAS routines
//
// Copyright (C) 2017 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <vector>
namespace sw {
namespace hprblas {
// LEVEL 1 BLAS operators
// sum of magnitudes of the vector elements
template<typename vector_T>
typename vector_T::value_type asum(size_t n, const vector_T& x, size_t incx) {
typename vector_T::value_type sum = 0;
size_t ix;
for (ix = 0; ix < n; ix += incx) {
sum += x[ix];
}
return sum;
}
// a time x plus y
template<typename scale_T, typename vector_T>
void axpy(size_t n, scale_T a, const vector_T& x, size_t incx, vector_T& y, size_t incy) {
size_t cnt, ix, iy;
for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < x.size() && iy < y.size(); ++cnt, ix += incx, iy += incy) {
y[iy] += a * x[ix];
}
}
// vector copy
template<typename vector_T>
void copy(size_t n, const vector_T& x, size_t incx, vector_T& y, size_t incy) {
size_t cnt, ix, iy;
for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < x.size() && iy < y.size(); ++cnt, ix += incx, iy += incy) {
y[iy] = x[ix];
}
}
// dot product: the operator vector::x[index] is limited to uint32_t, so the arguments are limited to uint32_t as well
// since we do not support arbitrary posit configuration conversions, the element type of the vectors x and y are declared to be the same.
// TODO: investigate if the vector<> index is always a 32bit entity?
template<typename Ty>
Ty dot(size_t n, const std::vector<Ty>& x, size_t incx, const std::vector<Ty>& y, size_t incy) {
Ty product = 0;
size_t cnt, ix, iy;
for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < x.size() && iy < y.size(); ++cnt, ix += incx, iy += incy) {
product += x[ix] * y[iy];
}
return product;
}
// fused dot product operators
// Fused dot product with quire continuation
template<typename Qy, typename Ty>
void fused_dot(Qy& sum_of_products, size_t n, const std::vector<Ty>& x, size_t incx, const std::vector<Ty>& y, size_t incy) {
size_t ix, iy;
for (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) {
sum_of_products += sw::unum::quire_mul(x[ix], y[iy]);
}
}
// Standalone fused dot product
template<size_t nbits, size_t es, size_t capacity = 10>
sw::unum::posit<nbits, es> fused_dot(size_t n, const std::vector< sw::unum::posit<nbits, es> >& x, size_t incx, const std::vector< sw::unum::posit<nbits, es> >& y, size_t incy) {
sw::unum::quire<nbits, es, capacity> q = 0;
size_t ix, iy;
for (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) {
q += sw::unum::quire_mul(x[ix], y[iy]);
if (sw::unum::_trace_quire_add) std::cout << q << '\n';
}
sw::unum::posit<nbits, es> sum;
convert(q.to_value(), sum); // one and only rounding step of the fused-dot product
return sum;
}
template<typename Vector, size_t nbits, size_t es, size_t capacity = 10>
sw::unum::posit<nbits, es> fused_dot(const Vector& x, const Vector& y) {
sw::unum::quire<nbits, es, capacity> q = 0;
size_t ix, iy, n = size(x);
for (ix = 0, iy = 0; ix < n && iy < n; ix = ix + 1, iy = iy + 1) {
q += sw::unum::quire_mul(x[ix], y[iy]);
}
sw::unum::posit<nbits, es> sum;
convert(q.to_value(), sum); // one and only rounding step of the fused-dot product
return sum;
}
// rotation of points in the plane
template<typename rotation_T, typename vector_T>
void rot(size_t n, vector_T& x, size_t incx, vector_T& y, size_t incy, rotation_T c, rotation_T s) {
// x_i = c*x_i + s*y_i
// y_i = c*y_i - s*x_i
size_t cnt, ix, iy;
for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < x.size() && iy < y.size(); ++cnt, ix += incx, iy += incy) {
rotation_T x_i = c*x[ix] + s*y[iy];
rotation_T y_i = c*y[iy] - s*x[ix];
y[iy] = y_i;
x[ix] = x_i;
}
}
// compute parameters for a Givens rotation
template<typename T>
void rotg(T& a, T& b, T& c, T&s) {
// Given Cartesian coordinates (a,b) of a point, return parameters c,s,r, and z associated with the Givens rotation.
}
// scale a vector
template<typename scale_T, typename vector_T>
void scale(size_t n, scale_T a, vector_T& x, size_t incx) {
size_t cnt, ix;
for (cnt = 0, ix = 0; cnt < n && ix < x.size(); ix += incx) {
x[ix] *= a;
}
}
// swap two vectors
template<typename vector_T>
void swap(size_t n, vector_T& x, size_t incx, vector_T& y, size_t incy) {
size_t cnt, ix, iy;
for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < x.size() && iy < y.size(); ++cnt, ix += incx, iy += incy) {
typename vector_T::value_type tmp = x[ix];
x[ix] = y[iy];
y[iy] = tmp;
}
}
// find the index of the element with maximum absolute value
template<typename vector_T>
size_t amax(size_t n, const vector_T& x, size_t incx) {
typename vector_T::value_type running_max = -INFINITY;
size_t ix, index;
for (ix = 0; ix < x.size(); ix += incx) {
if (x[ix] > running_max) {
index = ix;
running_max = x[ix];
}
}
return index;
}
// find the index of the element with minimum absolute value
template<typename vector_T>
size_t amin(size_t n, const vector_T& x, size_t incx) {
typename vector_T::value_type running_min = INFINITY;
size_t ix, index;
for (ix = 0; ix < x.size(); ix += incx) {
if (x[ix] < running_min) {
index = ix;
running_min = x[ix];
}
}
return index;
}
// absolute value of a complex number
template<typename T>
T cabs(T z) {
}
// print a vector
template<typename vector_T>
void print(std::ostream& ostr, size_t n, vector_T& x, size_t incx = 1) {
size_t cnt, ix;
for (cnt = 0, ix = 0; cnt < n && ix < x.size(); ++cnt, ix += incx) {
cnt == 0 ? ostr << "[" << x[ix] : ostr << ", " << x[ix];
}
ostr << "]";
}
// LEVEL 2 BLAS operators
template<typename Ty>
void matvec(const std::vector<Ty>& A, const std::vector<Ty>& x, std::vector<Ty>& b) {
// preconditions
size_t d = x.size();
assert(A.size() == d*d);
assert(b.size() == d);
for (size_t i = 0; i < d; ++i) {
b[i] = 0;
for (size_t j = 0; j < d; ++j) {
//std::cout << "b[" << i << "] = " << b[i] << std::endl;
//std::cout << "A[" << i << "][" << j << "] = " << A[i*d + j] << std::endl;
//std::cout << "x[" << j << "] = " << x[j] << std::endl;
b[i] = b[i] + A[i*d + j] * x[j];
}
//std::cout << "b[" << i << "] = " << b[i] << std::endl;
}
}
template<size_t nbits, size_t es>
void matvec(const std::vector< sw::unum::posit<nbits, es> >& A, const std::vector< sw::unum::posit<nbits, es> >& x, std::vector< sw::unum::posit<nbits, es> >& b) {
// preconditions
size_t d = x.size();
assert(A.size() == d*d);
assert(b.size() == d);
for (size_t i = 0; i < d; ++i) {
b[i] = 0;
for (size_t j = 0; j < d; ++j) {
//std::cout << "b[" << i << "] = " << b[i] << std::endl;
//std::cout << "A[" << i << "][" << j << "] = " << A[i*d + j] << std::endl;
//std::cout << "x[" << j << "] = " << x[j] << std::endl;
b[i] = b[i] + A[i*d + j] * x[j];
}
//std::cout << "b[" << i << "] = " << b[i] << std::endl;
}
}
template<typename Ty>
void eye(std::vector<Ty>& I) {
// preconditions
int d = int(std::sqrt(I.size()));
assert(I.size() == d*d);
for (int i = 0; i < d; ++i) {
for (int j = 0; j < d; ++j) {
I[i*d + j] = (i == j ? Ty(1) : Ty(0));
}
}
}
// LEVEL 3 BLAS operators
template<typename Ty>
void matmul(const std::vector<Ty>& A, const std::vector<Ty>& B, std::vector<Ty>& C) {
// preconditions
int d = int(std::sqrt(A.size()));
assert(A.size() == d*d);
assert(B.size() == d*d);
assert(C.size() == d*d);
for (int i = 0; i < d; ++i) {
for (int j = 0; j < d; ++j) {
C[i*d + j] = Ty(0);
for (int k = 0; k < d; ++k) {
C[i*d + j] = C[i*d + j] + A[i*d + k] * B[k*d + j];
}
}
}
}
} // namespace blas
} // namespace sw
| 33.114286 | 180 | 0.557254 | [
"vector"
] |
e136c15fbfd2ea495084c85623d8c407f8bd038d | 10,554 | cpp | C++ | ThirdParty/libless/src/value/UrlValue.cpp | pablokawan/ABx | 064d6df265c48c667ce81b0a83f84e5e22a7ff53 | [
"MIT"
] | null | null | null | ThirdParty/libless/src/value/UrlValue.cpp | pablokawan/ABx | 064d6df265c48c667ce81b0a83f84e5e22a7ff53 | [
"MIT"
] | null | null | null | ThirdParty/libless/src/value/UrlValue.cpp | pablokawan/ABx | 064d6df265c48c667ce81b0a83f84e5e22a7ff53 | [
"MIT"
] | null | null | null | #include "less/value/UrlValue.h"
#include "less/value/FunctionLibrary.h"
#ifdef WITH_LIBPNG
#include <png.h>
#endif
#ifdef WITH_LIBJPEG
#include <jpeglib.h>
#include <setjmp.h>
#include <stdio.h>
struct urlvalue_jpeg_error_mgr {
struct jpeg_error_mgr pub; /* "public" fields */
jmp_buf setjmp_buffer; /* for return to caller */
};
typedef struct urlvalue_jpeg_error_mgr* urlvalue_jpeg_error_ptr;
METHODDEF(void)
urlvalue_jpeg_error_exit(j_common_ptr cinfo) {
/* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
urlvalue_jpeg_error_ptr myerr = (urlvalue_jpeg_error_ptr)cinfo->err;
/* Always display the message. */
/* We could postpone this until after returning, if we chose. */
(*cinfo->err->output_message)(cinfo);
/* Return control to the setjmp point */
longjmp(myerr->setjmp_buffer, 1);
}
#endif
UrlValue_Img::UrlValue_Img() {
}
UrlValue::UrlValue(Token& token, std::string& path) : Value() {
tokens.push_back(token);
this->path = path;
type = Value::URL;
}
UrlValue::~UrlValue() {
}
std::string UrlValue::getPath() const {
return path;
}
std::string UrlValue::getRelativePath() const {
std::string source = tokens.front().source;
size_t pos = source.find_last_of("/\\");
std::string relative_path;
// if the source stylesheet is not in the current working directory
// then add its directory to the path.
if (pos != std::string::npos) {
relative_path.append(source.substr(0, pos + 1));
relative_path.append(this->path);
} else
relative_path = this->path;
return relative_path;
}
Value* UrlValue::operator+(const Value& v) const {
(void)v;
throw new ValueException("You can not add urls.", *this->getTokens());
}
Value* UrlValue::operator-(const Value& v) const {
(void)v;
throw new ValueException("You can not substract urls.", *this->getTokens());
}
Value* UrlValue::operator*(const Value& v) const {
(void)v;
throw new ValueException("You can not multiply urls.", *this->getTokens());
}
Value* UrlValue::operator/(const Value& v) const {
(void)v;
throw new ValueException("You can not divide urls.", *this->getTokens());
}
bool UrlValue::operator<(const Value& v) const {
const UrlValue* u;
const BooleanValue* b;
if (v.type == URL) {
u = static_cast<const UrlValue*>(&v);
return (path < u->getPath());
} else if (v.type == BOOLEAN) {
b = static_cast<const BooleanValue*>(&v);
return b->getValue();
} else {
throw new ValueException("You can only compare urls with urls.",
*this->getTokens());
}
}
bool UrlValue::operator==(const Value& v) const {
const UrlValue* u;
const BooleanValue* b;
if (v.type == URL) {
u = static_cast<const UrlValue*>(&v);
return (path == u->getPath());
} else if (v.type == BOOLEAN) {
// any url is falsy.
b = static_cast<const BooleanValue*>(&v);
return (false == b->getValue());
} else {
throw new ValueException("You can only compare urls with urls.",
*this->getTokens());
}
}
bool UrlValue::loadImg(UrlValue_Img& img) const {
return loadPng(img) || loadJpeg(img);
}
bool UrlValue::loadPng(UrlValue_Img& img) const {
#ifdef WITH_LIBPNG
unsigned char header[8]; // 8 is the maximum size that can be checked
/* open file and test for it being a png */
png_structp png_ptr;
png_infop info_ptr;
png_byte color_type;
int channels;
std::string path = getRelativePath();
FILE* fp = fopen(path.c_str(), "rb");
if (!fp)
return false; //"Image file could not be opened"
fread(header, 1, 8, fp);
if (png_sig_cmp(header, 0, 8))
return false; //"Image is not a PNG file"
/* initialize stuff */
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
throw new ValueException("png_create_read_struct failed",
*this->getTokens());
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
throw new ValueException("png_create_info_struct failed",
*this->getTokens());
if (setjmp(png_jmpbuf(png_ptr)))
throw new ValueException("Error during init_io", *this->getTokens());
png_init_io(png_ptr, fp);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
img.width = png_get_image_width(png_ptr, info_ptr);
img.height = png_get_image_height(png_ptr, info_ptr);
channels = png_get_channels(png_ptr, info_ptr);
color_type = png_get_color_type(png_ptr, info_ptr);
if (color_type == PNG_COLOR_TYPE_PALETTE) {
png_set_palette_to_rgb(png_ptr);
channels = 3;
}
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_set_tRNS_to_alpha(png_ptr);
channels += 1;
}
png_color_16p pBackground;
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_bKGD)) {
png_get_bKGD(png_ptr, info_ptr, &pBackground);
img.background.setRGB(
pBackground->red, pBackground->green, pBackground->blue);
} else {
img.background.setRGB(255, 255, 255);
}
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
png_ptr = NULL;
info_ptr = NULL;
fclose(fp);
return true;
#else
(void)img;
return false;
#endif
}
bool UrlValue::loadJpeg(UrlValue_Img& img) const {
#ifdef WITH_LIBJPEG
struct jpeg_decompress_struct cinfo;
struct urlvalue_jpeg_error_mgr jerr;
/* More stuff */
FILE* infile;
JSAMPARRAY buffer; /* Output row buffer */
int row_stride; /* physical row width in output buffer */
std::string path = getRelativePath();
unsigned int rgb[3];
if ((infile = fopen(path.c_str(), "rb")) == NULL) {
return false;
}
/* Step 1: allocate and initialize JPEG decompression object */
/* We set up the normal JPEG error routines, then override error_exit. */
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = urlvalue_jpeg_error_exit;
/* Establish the setjmp return context for urlvalue_jpeg_error_exit to use. */
if (setjmp(jerr.setjmp_buffer)) {
/* If we get here, the JPEG code has signaled an error.
* We need to clean up the JPEG object, close the input file, and return.
*/
jpeg_destroy_decompress(&cinfo);
fclose(infile);
return false;
}
/* Now we can initialize the JPEG decompression object. */
jpeg_create_decompress(&cinfo);
/* Step 2: specify data source (eg, a file) */
jpeg_stdio_src(&cinfo, infile);
/* Step 3: read file parameters with jpeg_read_header() */
(void)jpeg_read_header(&cinfo, TRUE);
/* We can ignore the return value from jpeg_read_header since
* (a) suspension is not possible with the stdio data source, and
* (b) we passed TRUE to reject a tables-only JPEG file as an error.
* See libjpeg.txt for more info.
*/
/* Step 4: set parameters for decompression */
/* In this example, we don't need to change any of the defaults set by
* jpeg_read_header(), so we do nothing here.
*/
/* Step 5: Start decompressor */
(void)jpeg_start_decompress(&cinfo);
/* We can ignore the return value since suspension is not possible
* with the stdio data source.
*/
img.width = cinfo.output_width;
img.height = cinfo.output_height;
/* We may need to do some setup of our own at this point before reading
* the data. After jpeg_start_decompress() we have the correct scaled
* output image dimensions available, as well as the output colormap
* if we asked for color quantization.
* In this example, we need to make an output work buffer of the right size.
*/
/* JSAMPLEs per row in output buffer */
row_stride = cinfo.output_width * cinfo.output_components;
/* Make a one-row-high sample array that will go away when done with image */
buffer = (*cinfo.mem->alloc_sarray)(
(j_common_ptr)&cinfo, JPOOL_IMAGE, row_stride, 1);
/* Step 6: while (scan lines remain to be read) */
/* jpeg_read_scanlines(...); */
/* Here we use the library's state variable cinfo.output_scanline as the
* loop counter, so that we don't have to keep track ourselves.
*/
while (cinfo.output_scanline < cinfo.output_height) {
/* jpeg_read_scanlines expects an array of pointers to scanlines.
* Here the array is only one element long, but you could ask for
* more than one scanline at a time if that's more convenient.
*/
(void)jpeg_read_scanlines(&cinfo, buffer, 1);
/* Assume put_scanline_someplace wants a pointer and sample count. */
// put_scanline_someplace(buffer[0], row_stride);
if (cinfo.out_color_space == JCS_RGB &&
(cinfo.output_scanline == 1 ||
cinfo.output_scanline == cinfo.output_height)) {
if (cinfo.output_scanline == 1) {
rgb[0] = buffer[0][0];
rgb[1] = buffer[0][1];
rgb[2] = buffer[0][2];
if (rgb[0] != buffer[0][row_stride - cinfo.output_components] ||
rgb[1] != buffer[0][row_stride - cinfo.output_components + 1] ||
rgb[2] != buffer[0][row_stride - cinfo.output_components + 2]) {
rgb[0] = rgb[1] = rgb[2] = 0;
}
} else if (rgb[0] != buffer[0][0] ||
rgb[1] != buffer[0][1] ||
rgb[2] != buffer[0][2] ||
rgb[0] != buffer[0][row_stride - cinfo.output_components] ||
rgb[1] != buffer[0][row_stride - cinfo.output_components + 1] ||
rgb[2] != buffer[0][row_stride - cinfo.output_components + 2]) {
rgb[0] = rgb[1] = rgb[2] = 0;
}
}
}
img.background.setRGB(rgb[0], rgb[1], rgb[2]);
/* Step 7: Finish decompression */
(void)jpeg_finish_decompress(&cinfo);
/* We can ignore the return value since suspension is not possible
* with the stdio data source.
*/
/* Step 8: Release JPEG decompression object */
/* This is an important step since it will release a good deal of memory. */
jpeg_destroy_decompress(&cinfo);
/* After finish_decompress, we can close the input file.
* Here we postpone it until after no more JPEG errors are possible,
* so as to simplify the setjmp error logic above. (Actually, I don't
* think that jpeg_destroy can do an error exit, but why assume anything...)
*/
fclose(infile);
return true;
#else
(void)img;
return false;
#endif
}
unsigned int UrlValue::getImageWidth() const {
UrlValue_Img img;
return (loadImg(img) ? img.width : 0);
}
unsigned int UrlValue::getImageHeight() const {
UrlValue_Img img;
return (loadImg(img) ? img.height : 0);
}
Color UrlValue::getImageBackground() const {
UrlValue_Img img;
loadImg(img);
return img.background;
}
| 29.729577 | 81 | 0.667709 | [
"object"
] |
e137084062291dc030b96219e21cd78a8693ed94 | 3,194 | hpp | C++ | include/cex/session.hpp | hispid/libcex | ddab6b73b04248249626a6800e4e79c878ccdc34 | [
"MIT"
] | null | null | null | include/cex/session.hpp | hispid/libcex | ddab6b73b04248249626a6800e4e79c878ccdc34 | [
"MIT"
] | null | null | null | include/cex/session.hpp | hispid/libcex | ddab6b73b04248249626a6800e4e79c878ccdc34 | [
"MIT"
] | null | null | null | //*************************************************************************
// File session.hpp
// Date 24.04.2018
// Copyright (c) 2018-2019 by Patrick Fial
//-------------------------------------------------------------------------
// Session functions
//*************************************************************************
#ifndef __SESSION_HPP__
#define __SESSION_HPP__
/*! \file session.hpp
\brief Session middleware function
Example:
```
// using default session options
app.use(cex::sessionHandler());
```*/
//***************************************************************************
// includes
//***************************************************************************
#include <string>
#include "core.hpp"
namespace cex
{
//**************************************************************************
// Middlewares
//***************************************************************************
// Session
//***************************************************************************
/*! \struct SessionOptions
\brief Contains all options for the sessionHandler middleware
Example:
```
auto opts = std::make_shared<cex::SessionOptions>();
opts->expires = 60*60*24*3;
opts->maxAge= 144;
opts->domain= "my.domain.de";
opts->path= "/somePath";
opts->name= "sessionID";
opts->secure= false;
opts->httpOnly=true;
opts->sameSiteLax= true;
opts->sameSiteStrict= true;
app.use(cex::sessionHandler(opts));
```
will set the following cookie:
```
Set-Cookie: sessionID=D7D1AB0E9B41E9291933C28DB7110A8B6C01B47D13EF82D712676E12AFF97A85; Domain=my.domain.de; Path=/somePath; Expires=Sun, 10 Feb 2019 08:54:31 CET; Max-Age=144; HttpOnly; SameSite=Strict
```
*/
struct SessionOptions
{
SessionOptions() : name("sessionId"), secure(false), httpOnly(true), sameSiteStrict(false), sameSiteLax(false), expires(0), maxAge(0) {}
/*! \brief Sets the expires cookie option. Must be a relative time offset in seconds. */
time_t expires;
/*! \brief Sets the maxAge cookie option */
long maxAge;
/*! \brief Sets the domain cookie option */
std::string domain;
/*! \brief sets the path cookie option */
std::string path;
/*! \brief sets the name cookie option */
std::string name;
/*! \brief sets the secure cookie option */
bool secure;
/*! \brief sets the HTTP-only cookie option */
bool httpOnly;
/*! \brief sets the same-site (strict) cookie option */
bool sameSiteStrict;
/*! \brief sets the same-site (lax) cookie option */
bool sameSiteLax;
};
/*! \public
\brief Creates a middleware function which gets/creates session IDs
Extracts the cookie with the configured name from the request. If no cookie could be found, a new session ID is created and a
cookie is attached to the Response object. The session ID is also added to the Request object's property list. The name of the
property corresponds to the cookie/session ID name.
*/
MiddlewareFunction sessionHandler(const std::shared_ptr<SessionOptions>& opts = nullptr);
//***************************************************************************
} // namespace cex
#endif // __SESSION_HPP_
| 29.036364 | 202 | 0.546024 | [
"object"
] |
e13d34a9b6de8f100238135aaa15b96929d91dc9 | 6,469 | cpp | C++ | src/qt/createnewsdialog.cpp | skydogenet/mainchain | 813cdd64ab7589c591a40abcb7395e49f8aefd40 | [
"MIT"
] | 1 | 2021-11-11T04:35:36.000Z | 2021-11-11T04:35:36.000Z | src/qt/createnewsdialog.cpp | skydogenet/mainchain | 813cdd64ab7589c591a40abcb7395e49f8aefd40 | [
"MIT"
] | 1 | 2021-11-17T19:56:34.000Z | 2021-11-17T19:56:34.000Z | src/qt/createnewsdialog.cpp | skydogenet/mainchain | 813cdd64ab7589c591a40abcb7395e49f8aefd40 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/createnewsdialog.h>
#include <qt/forms/ui_createnewsdialog.h>
#include <amount.h>
#include <wallet/wallet.h>
#include <txdb.h>
#include <validation.h>
#include <qt/skydogeunits.h>
#include <qt/newstablemodel.h>
#include <qt/newstypestablemodel.h>
#include <qt/platformstyle.h>
#include <QMessageBox>
CreateNewsDialog::CreateNewsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::CreateNewsDialog),
platformStyle(_platformStyle)
{
ui->setupUi(this);
ui->feeAmount->setValue(0);
ui->labelCharsRemaining->setText(QString::number(NEWS_HEADLINE_CHARS));
ui->pushButtonCreate->setIcon(platformStyle->SingleColorIcon(":/icons/broadcastnews"));
ui->pushButtonHelp->setIcon(platformStyle->SingleColorIcon(":/icons/transaction_0"));
}
CreateNewsDialog::~CreateNewsDialog()
{
delete ui;
}
void CreateNewsDialog::on_pushButtonCreate_clicked()
{
if (!newsTypesModel)
return;
QMessageBox messageBox;
const CAmount& nFee = ui->feeAmount->value();
std::string strText = ui->plainTextEdit->toPlainText().toStdString();
// Format strings for confirmation dialog
QString strFee = BitcoinUnits::formatWithUnit(BitcoinUnit::SKYDOGE, nFee, false, BitcoinUnits::separatorAlways);
// Show confirmation dialog
int nRes = QMessageBox::question(this, tr("Confirm news broadcast"),
tr("Are you sure you want to spend %1 to broadcast this news?").arg(strFee),
QMessageBox::Ok, QMessageBox::Cancel);
if (nRes == QMessageBox::Cancel)
return;
#ifdef ENABLE_WALLET
if (vpwallets.empty()) {
messageBox.setWindowTitle("Wallet Error!");
messageBox.setText("No active wallets to create the transaction.");
messageBox.exec();
return;
}
if (vpwallets[0]->IsLocked()) {
// Locked wallet message box
messageBox.setWindowTitle("Wallet locked!");
messageBox.setText("Wallet must be unlocked to create transactions.");
messageBox.exec();
return;
}
// Lookup selected type
NewsType type;
if (!newsTypesModel->GetType(ui->comboBoxCategory->currentIndex(), type)) {
messageBox.setWindowTitle("Invalid news type!");
messageBox.setText("Failed to locate news type!");
messageBox.exec();
return;
}
// Block until the wallet has been updated with the latest chain tip
vpwallets[0]->BlockUntilSyncedToCurrentChain();
// Get hex bytes of data
std::string strHex = HexStr(strText.begin(), strText.end());
std::vector<unsigned char> vBytes = ParseHex(strHex);
// Create news OP_RETURN script
CScript script;
script.resize(vBytes.size() + type.header.size() + 1);
script[0] = OP_RETURN;
memcpy(&script[1], type.header.data(), type.header.size());
memcpy(&script[type.header.size() + 1], vBytes.data(), vBytes.size());
CTransactionRef tx;
std::string strFail = "";
if (!vpwallets[0]->CreateOPReturnTransaction(tx, strFail, nFee, script))
{
messageBox.setWindowTitle("Creating transaction failed!");
QString createError = "Error creating transaction!\n\n";
createError += QString::fromStdString(strFail);
messageBox.setText(createError);
messageBox.exec();
return;
}
// Success message box
messageBox.setWindowTitle("Transaction created!");
QString result = "txid: " + QString::fromStdString(tx->GetHash().ToString());
result += "\n";
messageBox.setText(result);
messageBox.exec();
#endif
}
void CreateNewsDialog::on_pushButtonHelp_clicked()
{
QMessageBox messageBox;
messageBox.setWindowTitle("News Help");
QString str = tr("With this page you can pay a fee to broadcast news on any topic. "
"Clicking \"Broadcast\" will create a transaction with an OP_RETURN "
"output that encodes the text you have entered. Anyone subscribed to "
"the topic will see posts filtered by time and sorted by fee amount.");
messageBox.setText(str);
messageBox.exec();
}
void CreateNewsDialog::on_plainTextEdit_textChanged()
{
QString currentText = ui->plainTextEdit->toPlainText();
if (currentText == cacheText)
return;
cacheText = currentText;
std::string strText = currentText.toStdString();
// Reset highlights
QTextCursor cursor(ui->plainTextEdit->document());
cursor.setPosition(0, QTextCursor::MoveAnchor);
cursor.setPosition(strText.size(), QTextCursor::KeepAnchor);
cursor.setCharFormat(QTextCharFormat());
// Update the number of characters remaining label
if (strText.size() >= NEWS_HEADLINE_CHARS)
ui->labelCharsRemaining->setText(QString::number(0));
else
ui->labelCharsRemaining->setText(QString::number(NEWS_HEADLINE_CHARS - strText.size()));
// Where the headline ends
size_t nHeadlineEnd = 0;
// Check for any newlines
bool fNewLine = false;
for (size_t i = 0; i < strText.size(); i++) {
if (strText[i] == '\n' || strText[i] == '\r') {
ui->labelCharsRemaining->setText(QString::number(0));
nHeadlineEnd = i;
fNewLine = true;
break;
}
}
if (fNewLine)
nHeadlineEnd = nHeadlineEnd < NEWS_HEADLINE_CHARS ? nHeadlineEnd : NEWS_HEADLINE_CHARS;
else
nHeadlineEnd = strText.size() < NEWS_HEADLINE_CHARS ? strText.size() : NEWS_HEADLINE_CHARS;
// Highlight characters that will fit into the headline
cursor = QTextCursor(ui->plainTextEdit->document());
QTextCharFormat highlight;
highlight.setBackground(Qt::green);
cursor.setPosition(0, QTextCursor::MoveAnchor);
cursor.setPosition(nHeadlineEnd, QTextCursor::KeepAnchor);
cursor.setCharFormat(highlight);
}
void CreateNewsDialog::updateTypes()
{
if (!newsTypesModel)
return;
ui->comboBoxCategory->clear();
std::vector<NewsType> vType = newsTypesModel->GetTypes();
for (const NewsType t : vType)
ui->comboBoxCategory->addItem(QString::fromStdString(t.title));
}
void CreateNewsDialog::setNewsTypesModel(NewsTypesTableModel* newsTypesModelIn)
{
newsTypesModel = newsTypesModelIn;
updateTypes();
}
| 32.18408 | 116 | 0.67893 | [
"vector"
] |
e14ede080d08b145a7663b80649b39ba2eeecea1 | 4,128 | cpp | C++ | mstream/anom.cpp | scooter-dangle/MStream | 2f48a53ca3f5b2aa4783ec2feaf5041bec4468e1 | [
"Apache-2.0"
] | 69 | 2020-09-18T16:58:35.000Z | 2022-03-29T11:39:08.000Z | mstream/anom.cpp | scooter-dangle/MStream | 2f48a53ca3f5b2aa4783ec2feaf5041bec4468e1 | [
"Apache-2.0"
] | 1 | 2021-06-08T18:24:44.000Z | 2021-06-09T20:14:06.000Z | mstream/anom.cpp | scooter-dangle/MStream | 2f48a53ca3f5b2aa4783ec2feaf5041bec4468e1 | [
"Apache-2.0"
] | 15 | 2020-09-18T23:27:49.000Z | 2021-12-28T02:19:39.000Z | #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
#define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
#include <vector>
#include <cmath>
#include <limits>
#include "anom.hpp"
#include "numerichash.hpp"
#include "recordhash.hpp"
#include "categhash.hpp"
double counts_to_anom(double tot, double cur, int cur_t) {
double cur_mean = tot / cur_t;
double sqerr = pow(MAX(0, cur - cur_mean), 2);
return sqerr / cur_mean + sqerr / (cur_mean * MAX(1, cur_t - 1));
}
vector<double> *mstream(vector<vector<double> > &numeric, vector<vector<long> > &categ, vector<int> ×, int num_rows,
int num_buckets, double factor, int dimension1, int dimension2) {
int length = times.size(), cur_t = 1;
Recordhash cur_count(num_rows, num_buckets, dimension1, dimension2);
Recordhash total_count(num_rows, num_buckets, dimension1, dimension2);
auto *anom_score = new vector<double>(length);
vector<Numerichash> numeric_score(dimension1, Numerichash(num_rows, num_buckets));
vector<Numerichash> numeric_total(dimension1, Numerichash(num_rows, num_buckets));
vector<Categhash> categ_score(dimension2, Categhash(num_rows, num_buckets));
vector<Categhash> categ_total(dimension2, Categhash(num_rows, num_buckets));
vector<double> cur_numeric(0);
vector<double> max_numeric(0);
vector<double> min_numeric(0);
if (dimension1) {
max_numeric.resize(dimension1, numeric_limits<double>::min());
min_numeric.resize(dimension1, numeric_limits<double>::max());
}
vector<long> cur_categ(0);
for (int i = 0; i < length; i++) {
if (i == 0 || times[i] > cur_t) {
cur_count.lower(factor);
for (int j = 0; j < dimension1; j++) {
numeric_score[j].lower(factor);
}
for (int j = 0; j < dimension2; j++) {
categ_score[j].lower(factor);
}
cur_t = times[i];
}
if (dimension1)
cur_numeric.swap(numeric[i]);
if (dimension2)
cur_categ.swap(categ[i]);
double sum = 0.0, t, cur_score;
for (int node_iter = 0; node_iter < dimension1; node_iter++) {
cur_numeric[node_iter] = log10(1 + cur_numeric[node_iter]);
if (!i) {
max_numeric[node_iter] = cur_numeric[node_iter];
min_numeric[node_iter] = cur_numeric[node_iter];
cur_numeric[node_iter] = 0;
} else {
min_numeric[node_iter] = MIN(min_numeric[node_iter], cur_numeric[node_iter]);
max_numeric[node_iter] = MAX(max_numeric[node_iter], cur_numeric[node_iter]);
if (max_numeric[node_iter] == min_numeric[node_iter]) cur_numeric[node_iter] = 0;
else cur_numeric[node_iter] = (cur_numeric[node_iter] - min_numeric[node_iter]) /
(max_numeric[node_iter] - min_numeric[node_iter]);
}
numeric_score[node_iter].insert(cur_numeric[node_iter], 1);
numeric_total[node_iter].insert(cur_numeric[node_iter], 1);
t = counts_to_anom(numeric_total[node_iter].get_count(cur_numeric[node_iter]),
numeric_score[node_iter].get_count(cur_numeric[node_iter]), cur_t);
sum = sum+t;
}
cur_count.insert(cur_numeric, cur_categ, 1);
total_count.insert(cur_numeric, cur_categ, 1);
for (int node_iter = 0; node_iter < dimension2; node_iter++) {
categ_score[node_iter].insert(cur_categ[node_iter], 1);
categ_total[node_iter].insert(cur_categ[node_iter], 1);
t = counts_to_anom(categ_total[node_iter].get_count(cur_categ[node_iter]),
categ_score[node_iter].get_count(cur_categ[node_iter]), cur_t);
sum = sum+t;
}
cur_score = counts_to_anom(total_count.get_count(cur_numeric, cur_categ),
cur_count.get_count(cur_numeric, cur_categ), cur_t);
sum = sum + cur_score;
(*anom_score)[i] = log(1 + sum);
}
return anom_score;
}
| 42.122449 | 121 | 0.608527 | [
"vector"
] |
e150b23a1e1cb36b49d10e7c344ab020963048b3 | 4,624 | hxx | C++ | inetsrv/query/apps/ifilttst/clog.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/query/apps/ifilttst/clog.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/query/apps/ifilttst/clog.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1996 - 1997.
//
// File: mylog.hxx
//
// Contents: A class that performs logging operations, optionally using NTLOG
// To emulate ntlog without linking to ntlog.lib or using ntlog.dll
// compile with the NO_NTLOG flag defined.
//
// Classes: CLog
//
// Functions:
//
// Coupling:
//
// Notes:
//
// History: 10-15-1996 ericne Created
//
//----------------------------------------------------------------------------
#define NO_NTLOG
#ifndef _CMYLOG
#define _CMYLOG
#include <ntlog.h>
// This is only if we do not intend on using ntlog.dll
#ifdef NO_NTLOG
// The number of different messages that can be logged. This is used to
// track of the log statistics
const ULONG cMessageLevels = 16;
// Used to determine whether a log message is a test, variation, or neither
const DWORD dwTestTypesMask = ( TLS_VARIATION | TLS_TEST );
// The different message types
const DWORD dwMessageTypesMask = ( TLS_INFO | TLS_SEV1 | TLS_SEV2 |
TLS_ABORT | TLS_WARN | TLS_BLOCK |
TLS_PASS | TLS_SEV3 );
#endif
const size_t MaxLogLineLength = 1024;
// By default, the log will be initialized using dwDefaultStyle as the logging
// style.
const DWORD dwDefaultStyle = ( TLS_INFO | TLS_SEV1 | TLS_SEV2 | TLS_SEV3 |
TLS_WARN | TLS_BLOCK | TLS_PASS | TLS_TEST |
TLS_TESTDEBUG | TLS_VARIATION | TLS_ABORT |
TLS_REFRESH | TLS_SORT | TLS_PROLOG );
// To determine if a particular message exceeds the threshold and should be,
// dwStyle is AND'ed with this mask to ignore the non-useful bits
const DWORD dwThresholdMask = ( TLS_ABORT | TLS_SEV1 | TLS_SEV2 |
TLS_SEV3 | TLS_WARN | TLS_PASS | TLS_INFO );
//+---------------------------------------------------------------------------
//
// Class: CLog ()
//
// Purpose: Log module that can emulate ntlog, or use ntlog based on a
// compile flag
//
// Interface: CLog -- Constructor
// ~CLog -- Destructor
// Enable -- Activates the log object
// Disable -- Disables the log object
// SetThreshold -- Sets a threshold for all logged messages
// InitLog -- Initializes the log
// Log -- Takes a variable number of arguments
// vLog -- Takes a va_list as a parameter
// m_dwThreshold -- Messages that don't exceed this threshold
// are not logged
// m_fEnabled -- TRUE if the the log is enabled
// #ifdef NO_NTLOG
// ReportStats -- Used to report the statistics for this log
// Called from destructor
// m_pLogFile -- FILE* for the log file
// m_dwLogStyle -- Style used to initialize the log
// m_ulNbrMessages -- Keeps track of the log statistics
// m_CriticalSection -- For multi-threaded applications
// #else
// m_hLog -- Handle to the log returned by tlCreateLog
// #endif
//
// History: 1-15-1997 ericne Created
//
// Notes:
//
//----------------------------------------------------------------------------
class CLog
{
public:
CLog();
virtual ~CLog();
virtual void Enable();
virtual void Disable();
virtual void SetThreshold( DWORD );
virtual BOOL InitLog( LPCTSTR, DWORD = dwDefaultStyle );
virtual BOOL Log( DWORD, LPTSTR, int, LPCTSTR, ... );
virtual BOOL vLog( DWORD, LPTSTR, int, LPCTSTR, va_list );
virtual BOOL AddParticipant();
virtual BOOL RemoveParticipant();
virtual void ReportStats( );
protected:
DWORD m_dwThreshold;
BOOL m_fEnabled;
#ifdef NO_NTLOG
FILE* m_pLogFile;
DWORD m_dwLogStyle;
ULONG m_ulNbrMessages[ cMessageLevels ];
CRITICAL_SECTION m_CriticalSection;
#else
HANDLE m_hLog;
#endif
};
#endif
| 31.243243 | 81 | 0.504542 | [
"object"
] |
e150fd71692a83d2cad5cfae7c2a8006cc867b60 | 14,809 | cc | C++ | common/segments.cc | jsbejeau/rtbkit | 8f1d043efce5c42c6a3e490e16f98f0e04eb3a21 | [
"Apache-2.0"
] | 2 | 2017-03-01T04:57:50.000Z | 2020-02-13T20:51:43.000Z | common/segments.cc | jsbejeau/rtbkit | 8f1d043efce5c42c6a3e490e16f98f0e04eb3a21 | [
"Apache-2.0"
] | null | null | null | common/segments.cc | jsbejeau/rtbkit | 8f1d043efce5c42c6a3e490e16f98f0e04eb3a21 | [
"Apache-2.0"
] | null | null | null | /* segments.cc
Jeremy Barnes, 12 March 2012
Copyright (c) 2012 Datacratic. All rights reserved.
Implementation of segments.
*/
#include "rtbkit/common/segments.h"
#include <boost/function_output_iterator.hpp>
#include "jml/arch/format.h"
#include "jml/arch/exception.h"
#include "jml/arch/backtrace.h"
#include "jml/utils/exc_assert.h"
#include "soa/types/value_description.h"
#include "jml/db/persistent.h"
#include <boost/make_shared.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace ML;
using namespace ML::DB;
using namespace Datacratic;
namespace Datacratic {
void
DefaultDescription<SegmentList>::
parseJsonTyped(SegmentList * val, JsonParsingContext & context)
const
{
Json::Value v = context.expectJson();
//cerr << "got segments " << v << endl;
*val = std::move(SegmentList::createFromJson(v));
}
void
DefaultDescription<SegmentList>::
printJsonTyped(const SegmentList * val, JsonPrintingContext & context)
const
{
context.startArray(val->ints.size() + val->strings.size());
if (val->weights.empty()) {
for (unsigned i = 0; i < val->ints.size(); ++i) {
context.newArrayElement();
context.writeInt(val->ints[i]);
}
for (unsigned i = 0; i < val->strings.size(); ++i) {
context.newArrayElement();
context.writeString(val->strings[i]);
}
}
else {
throw ML::Exception("weights unsupported");
}
context.endArray();
}
bool
DefaultDescription<SegmentList>::
isDefaultTyped(const SegmentList * val)
const
{
return val->empty();
}
DefaultDescription<SegmentsBySource>::
DefaultDescription(ValueDescriptionT<SegmentList> * newInner)
: inner(newInner)
{
// inner = reinterpret_cast<DefaultDescription<SegmentList> *>(newInner);
}
void
DefaultDescription<SegmentsBySource>::
parseJsonTyped(SegmentsBySource * val, JsonParsingContext & context)
const
{
Json::Value v = context.expectJson();
//cerr << "got segments " << v << endl;
*val = std::move(RTBKIT::SegmentsBySource::createFromJson(v));
}
void
DefaultDescription<SegmentsBySource>::
printJsonTyped(const SegmentsBySource * val,
JsonPrintingContext & context) const
{
context.startObject();
for (const auto & v: *val) {
context.startMember(v.first);
inner->printJsonTyped(v.second.get(), context);
}
context.endObject();
}
bool
DefaultDescription<SegmentsBySource>::
isDefaultTyped(const SegmentsBySource * val)
const
{
return val->empty();
}
}
namespace RTBKIT {
/*****************************************************************************/
/* SEGMENTS */
/*****************************************************************************/
SegmentList::
SegmentList()
{
}
SegmentList::
SegmentList(const std::vector<string> & segs)
{
for (unsigned i = 0; i < segs.size(); ++i)
add(segs[i]);
sort();
}
SegmentList::
SegmentList(const std::vector<int> & segs)
: ints(segs.begin(), segs.end())
{
sort();
}
SegmentList::
SegmentList(const std::vector<std::pair<int, float> > & segs)
{
for (unsigned i = 0; i < segs.size(); ++i)
add(segs[i].first, segs[i].second);
sort();
}
bool
SegmentList::
contains(int i) const
{
return std::binary_search(ints.begin(), ints.end(), i);
}
bool
SegmentList::
contains(const std::string & str) const
{
int i = parseSegmentNum(str);
if (i == -1)
return std::binary_search(strings.begin(), strings.end(), str);
else return contains(i);
}
#if 0
float
SegmentList::
weight(int i) const
{
}
float
SegmentList::
weight(const std::string & str) const
{
}
#endif
template<typename Seq1, typename Seq2>
bool anyMatchesLookup(const Seq1 & seq1, const Seq2 & seq2)
{
auto it2 = seq2.begin(), end2 = seq2.end();
for (auto it1 = seq1.begin(), end1 = seq1.end();
it1 != end1; ++it1)
if (std::binary_search(it2, end2, *it1)) return true;
return false;
}
template<typename Seq1, typename Seq2>
bool anyMatches(const Seq1 & seq1, const Seq2 & seq2)
{
if (seq1.empty() || seq2.empty())
return false;
else if (seq1.size() * 5 < seq2.size()) {
// seq2 is much bigger... look up individually each element
return anyMatchesLookup(seq1, seq2);
}
else if (seq2.size() * 5 < seq1.size()) {
// seq1 is much bigger... look up individually each element
return anyMatchesLookup(seq2, seq1);
}
else {
// roughly equal sizes; jointly iterate
auto it1 = seq1.begin(), end1 = seq1.end();
auto it2 = seq2.begin(), end2 = seq2.end();
while (it1 != end1 && it2 != end2) {
if (*it1 == *it2) return true;
else if (*it1 < *it2) ++it1;
else ++it2;
}
return false;
}
}
bool
SegmentList::
match(const SegmentList & other) const
{
return anyMatches(ints, other.ints)
|| anyMatches(strings, other.strings);
}
bool
SegmentList::
match(const std::vector<int> & other) const
{
return anyMatches(ints, other);
}
bool
SegmentList::
match(const std::vector<std::string> & other) const
{
return anyMatches(strings, other);
}
size_t
SegmentList::
size() const
{
return ints.size() + strings.size();
}
bool
SegmentList::
empty() const
{
return ints.empty() && strings.empty();
}
SegmentList
SegmentList::
createFromJson(const Json::Value & json)
{
SegmentList result;
if (!json.isArray())
throw Exception("augment must be an array of augmentations");
for (unsigned i = 0; i < json.size(); ++i) {
const Json::Value & val = json[i];
if (val.isArray()) {
if (val.size() != 2)
throw ML::Exception("can't create weighted segment from "
+ json.toString());
float weight = val[1].asDouble();
if (val[0].isInt())
result.add(val[0].asInt(), weight);
else if (val[0].isNumeric())
result.add(val[0].asDouble(), weight);
else result.add(val[0].asString(), weight);
}
else if (val.isInt())
result.add(val.asInt());
else if (val.isNumeric())
result.add(val.asDouble());
else result.add(val.asString());
}
return result;
}
Json::Value
SegmentList::
toJson() const
{
Json::Value result(Json::arrayValue);
if (weights.empty()) {
if (strings.empty()) {
for (unsigned i = 0; i < ints.size(); ++i)
result[i] = ints[i];
}
else {
for (unsigned i = 0; i < ints.size(); ++i)
result[i] = ML::format("%d", ints[i]);
for (unsigned i = 0; i < strings.size(); ++i)
result[i + ints.size()] = strings[i];
}
}
else {
if (strings.empty()) {
for (unsigned i = 0; i < ints.size(); ++i) {
result[i][0] = ints[i];
result[i][1] = weights[i];
}
}
else {
for (unsigned i = 0; i < ints.size(); ++i) {
result[i][0] = ML::format("%d", ints[i]);
result[i][1] = weights[i];
}
for (unsigned i = 0; i < strings.size(); ++i) {
result[i + ints.size()][0] = strings[i];
result[i + ints.size()][1] = weights[i + ints.size()];
}
}
}
return result;
}
std::string
SegmentList::
toJsonStr() const
{
return boost::trim_copy(toJson().toString());
}
std::string
SegmentList::
toString() const
{
return toJsonStr();
}
void
SegmentList::
add(int i, float weight)
{
ints.push_back(i);
if (weight != 1.0 || !weights.empty()) {
if (weights.empty())
weights.resize(size() - 1, 1.0);
weights.insert(weights.begin() + ints.size() - 1, weight);
ExcAssertEqual(weights.size(), size());
}
}
void
SegmentList::
add(const std::string & str, float weight)
{
int i = parseSegmentNum(str);
if (i == -1) {
strings.push_back(str);
if (weight != 1.0 || !weights.empty()) {
if (weights.empty())
weights.resize(size() - 1, 1.0);
weights.push_back(weight);
ExcAssertEqual(weights.size(), size());
}
}
else add(i, weight);
}
int
SegmentList::
parseSegmentNum(const std::string & str)
{
if (str.empty()) return -1;
else if (str.length() == 1 && str[0] == '0') {
return 0;
}
else if (str[0] != '0' && isdigit(str[0])) {
char * endptr = const_cast<char *>(str.c_str() + str.length());
long i = strtol(str.c_str(), &endptr, 10);
if (endptr == str.c_str() + str.length()) {
if (i < 0) return -1;
return i;
}
}
return -1;
}
void
SegmentList::
sort()
{
if (weights.empty()) {
std::sort(ints.begin(), ints.end());
std::sort(strings.begin(), strings.end());
}
else {
ExcAssertEqual(weights.size(), size());
vector<pair<int, float> > isorted(ints.size());
for (unsigned i = 0; i < ints.size(); ++i)
isorted[i] = make_pair(ints[i], weights[i]);
std::sort(isorted.begin(), isorted.end());
vector<pair<string, float> > ssorted(strings.size());
for (unsigned i = 0; i < strings.size(); ++i)
ssorted[i] = make_pair(strings[i], weights[i + ints.size()]);
std::sort(ssorted.begin(), ssorted.end());
for (unsigned i = 0; i < ints.size(); ++i) {
ints[i] = isorted[i].first;
weights[i] = isorted[i].second;
}
for (unsigned i = 0; i < strings.size(); ++i) {
strings[i] = ssorted[i].first;
weights[i + ints.size()] = ssorted[i].second;
}
}
}
void
SegmentList::
serialize(ML::DB::Store_Writer & store) const
{
unsigned char version = 0;
store << version << ints << strings << weights;
}
void
SegmentList::
reconstitute(ML::DB::Store_Reader & store)
{
unsigned char version;
store >> version;
if (version > 0)
throw ML::Exception("unknown SegmentList version");
store >> ints >> strings >> weights;
}
std::string
SegmentList::
serializeToString() const
{
return ML::DB::serializeToString(*this);
}
SegmentList
SegmentList::
reconstituteFromString(const std::string & str)
{
return ML::DB::reconstituteFromString<SegmentList>(str);
}
void
SegmentList::
forEach(const std::function<void (int, string, float)> & onSegment) const
{
for (unsigned i = 0; i < ints.size(); ++i)
onSegment(ints[i], ML::format("%d", ints[i]),
weights.empty() ? 1.0 : weights[i]);
for (unsigned i = 0; i < strings.size(); ++i)
onSegment(-1, strings[i],
weights.empty() ? 1.0 : weights[i + ints.size()]);
}
/*****************************************************************************/
/* SEGMENTS BY SOURCE */
/*****************************************************************************/
SegmentsBySource::
SegmentsBySource()
{
}
SegmentsBySource::
SegmentsBySource(SegmentsBySourceBase && other)
: SegmentsBySourceBase(other)
{
}
SegmentsBySource::
SegmentsBySource(const SegmentsBySourceBase & other)
: SegmentsBySourceBase(other)
{
}
void
SegmentsBySource::
sortAll()
{
for (auto it = begin(), end = this->end();
it != end; ++it)
it->second->sort();
}
const SegmentList &
SegmentsBySource::
get(const std::string & str) const
{
static const SegmentList NONE;
auto it = find(str);
if (it == end()) return NONE;
if (!it->second)
throw ML::Exception("invalid segment list in segments");
return *it->second;
}
void
SegmentsBySource::
addSegment(const std::string & source,
const std::shared_ptr<SegmentList> & segs)
{
if (!insert(make_pair(source, segs)).second)
throw ML::Exception("attempt to add same segments twice");
}
void
SegmentsBySource::
addInts(const std::string & source,
const std::vector<int> & segs)
{
if (!insert(make_pair(source, std::make_shared<SegmentList>(segs))).second)
throw ML::Exception("attempt to add same segments twice");
}
void
SegmentsBySource::
addStrings(const std::string & source,
const std::vector<string> & segs)
{
if (!insert(make_pair(source, std::make_shared<SegmentList>(segs))).second)
throw ML::Exception("attempt to add same segments twice");
}
void
SegmentsBySource::
addWeightedInts(const std::string & source,
const std::vector<pair<int, float> > & segs)
{
if (!insert(make_pair(source, std::make_shared<SegmentList>(segs))).second)
throw ML::Exception("attempt to add same segments twice");
}
void
SegmentsBySource::
add(const std::string & source, const std::string & segment, float weight)
{
auto & entry = (*this)[source];
if (!entry) entry.reset(new SegmentList());
entry->add(segment, weight);
}
void
SegmentsBySource::
add(const std::string & source, int segment, float weight)
{
auto & entry = (*this)[source];
if (!entry) entry.reset(new SegmentList());
entry->add(segment, weight);
}
Json::Value
SegmentsBySource::
toJson() const
{
Json::Value result;
for (auto it = begin(), end = this->end(); it != end; ++it)
result[it->first] = it->second->toJson();
return result;
}
SegmentsBySource
SegmentsBySource::
createFromJson(const Json::Value & json)
{
SegmentsBySource result;
for (auto it = json.begin(), end = json.end(); it != end; ++it) {
if (it->isNull()) continue;
auto segs = std::make_shared<SegmentList>();
*segs = SegmentList::createFromJson(*it);
result.addSegment(it.memberName(), segs);
}
return result;
}
void
SegmentsBySource::
serialize(ML::DB::Store_Writer & store) const
{
unsigned char version = 0;
store << version;
store << compact_size_t(size());
for (auto it = begin(), end = this->end(); it != end; ++it) {
store << it->first;
it->second->serialize(store);
}
}
void
SegmentsBySource::
reconstitute(ML::DB::Store_Reader & store)
{
unsigned char version;
store >> version;
if (version != 0)
throw ML::Exception("invalid version");
compact_size_t sz(store);
SegmentsBySourceBase newMe;
for (unsigned i = 0; i < sz; ++i) {
string k;
store >> k;
auto l = std::make_shared<SegmentList>();
store >> *l;
newMe[k] = l;
}
swap(newMe);
}
} // namespace RTBKIT
| 23.847021 | 79 | 0.570194 | [
"vector"
] |
ff15e1f09c21f280727e990018b775fe987a35d1 | 1,931 | cpp | C++ | Hackerrank/DP/The Coin Change Problem/A.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | 2 | 2018-12-11T14:37:24.000Z | 2022-01-23T18:11:54.000Z | Hackerrank/DP/The Coin Change Problem/A.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | Hackerrank/DP/The Coin Change Problem/A.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | //LOOKED AT EDITORIAL
// It's fantastic, the way changing the order of loops can completely change the way you look at a problem
#include<bits/stdc++.h>
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1000000001
#define MOD 1000000007
#define ll long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long int>
#define sc(n) scanf("%d",&n);
#define scll(n) scanf("%lld",&n);
#define scld(n) scanf("%Lf",&n);
#define scr(s) {char temp[1000000];scanf("%s",temp);s = temp;}
using namespace std;
int main()
{
int n,m;
sc(n);sc(m);
ll* l = (ll*)calloc(n+1,sizeof(ll));
int* min1 = (int*)calloc(n+1,sizeof(int));
for(int i=0;i<n+1;i++) min1[i] = 0;
l[0] = 1;
vector<int> v;
bitset<51> bs;
bs.reset();
for(int i=0;i<m;i++)
{
int a;
sc(a);
v.pu(a);
if(a<=n){l[a]=0;bs[a] = true;}
}
for(int j=0;j<m;j++)
{
for(int i=v[j];i<=n;i++) l[i]+=l[i-v[j]];
}
// for(int i=1;i<=n;i++)
// {
// bitset<251> bs1;
// bs1.reset();
// for(int k=0;k<m;k++)
// {
// if(i-v[k]>=0)
// {
// // bs[i-v[k]] = true;
// for(int j=0;j<m;j++) if(i-v[k]-v[j]>0) {bs1[i-v[k]-v[j]] = true;}
// }
// }
// for(int j=0;j<n;j++) cout<<bs1[j]<<" ";cout<<endl;
// for(int j=0;j<m;j++)
// {
//
// if(i>=v[j] && v[j]>=min1[i-v[j]])
// {
// // l[i]+=l[i-v[j]];
// cout<<v[j]<<" "<<min1[i-v[j]]<<endl;
// {
// l[i]+=l[i-v[j]];
// if(bs[i-v[j]]) min1[i] = max(v[j],i-v[j]);
// min1[i] = max(v[j],min1[i]);
// }
// else l[i]++;
// else if(i%v[j]==0) l[i]++;
// if((bs[i-v[j]] && i-v[j]>v[j]) || (!bs[i-v[j]])) l[i]+=l[i-v[j]];
// else if(bs[i-v[j]] && i==2*v[j]) l[i]++;
// }
// }
// }
// for(int i=0;i<=n;i++) cout<<l[i]<<" ";cout<<endl;
printf("%lld\n",l[n]);
return 0;
}
| 24.443038 | 106 | 0.457276 | [
"vector"
] |
ff16218b8a68a290e0797765b0700309ed5f1bda | 28,268 | cpp | C++ | src/modules/mod_wmts_wrapper/mod_wmts_wrapper.cpp | edplato/onearth | 3bc7717b7cdf21ca7747d94c31078208494deb96 | [
"Apache-2.0"
] | 131 | 2015-01-19T15:42:50.000Z | 2022-03-30T16:38:11.000Z | src/modules/mod_wmts_wrapper/mod_wmts_wrapper.cpp | edplato/onearth | 3bc7717b7cdf21ca7747d94c31078208494deb96 | [
"Apache-2.0"
] | 59 | 2015-02-04T02:29:57.000Z | 2021-10-12T19:25:09.000Z | src/modules/mod_wmts_wrapper/mod_wmts_wrapper.cpp | edplato/onearth | 3bc7717b7cdf21ca7747d94c31078208494deb96 | [
"Apache-2.0"
] | 51 | 2015-02-12T13:30:20.000Z | 2021-09-24T01:35:08.000Z | /*
* Copyright (c) 2002-2017, California Institute of Technology.
* All rights reserved. Based on Government Sponsored Research under contracts NAS7-1407 and/or NAS7-03001.
*
* 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 California Institute of Technology (Caltech), its operating division the Jet Propulsion Laboratory (JPL),
* the National Aeronautics and Space Administration (NASA), 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 CALIFORNIA INSTITUTE OF TECHNOLOGY 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.
*
* 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 <apr.h>
#include <apr_general.h>
#include <httpd.h>
#include <http_config.h>
#include <http_log.h>
#include <http_protocol.h>
#include <http_request.h>
#include <apr_tables.h>
#include <apr_strings.h>
#include <apr_lib.h>
#include "mod_wmts_wrapper.h"
#include "mod_reproject.h"
// Check a file extension against the specified MIME type
int check_valid_extension(wmts_wrapper_conf *dconf, const char *extension)
{
wmts_wrapper_conf *cfg = (wmts_wrapper_conf *)dconf;
if (apr_strnatcasecmp(cfg->mime_type, "image/png") == 0) {
return (apr_strnatcasecmp(".png", extension) == 0);
}
if (apr_strnatcasecmp(cfg->mime_type, "image/jpeg") == 0) {
return (apr_strnatcasecmp(".jpg", extension) == 0 || apr_strnatcasecmp(".jpeg", extension) == 0);
}
if (apr_strnatcasecmp(cfg->mime_type, "application/vnd.mapbox-vector-tile") == 0) {
return (apr_strnatcasecmp(".mvt", extension) == 0);
}
if (apr_strnatcasecmp(cfg->mime_type, "image/tiff") == 0) {
return (apr_strnatcasecmp(".tif", extension) == 0 || apr_strnatcasecmp(".tiff", extension) == 0);
}
if (apr_strnatcasecmp(cfg->mime_type, "image/lerc") == 0) {
return (apr_strnatcasecmp(".lerc", extension) == 0);
}
}
// argstr_to_table and argstr_to_table are taken from Apache 2.4
void argstr_to_table(char *str, apr_table_t *parms)
{
char *key;
char *value;
char *strtok_state;
if (str == NULL) {
return;
}
key = apr_strtok(str, "&", &strtok_state);
// int i;
// for (i=0;key[i]!=0;i++) key[i]=apr_toupper(key[i]);
while (key) {
value = strchr(key, '=');
if (value) {
*value = '\0'; /* Split the string in two */
value++; /* Skip passed the = */
}
else {
value = NULL;
}
ap_unescape_url(key);
ap_unescape_url(value);
apr_table_set(parms, key, value);
key = apr_strtok(NULL, "&", &strtok_state);
}
}
void ap_args_to_table(request_rec *r, apr_table_t **table)
{
apr_table_t *t = apr_table_make(r->pool, 10);
argstr_to_table(apr_pstrdup(r->pool, r->args), t);
*table = t;
}
static const char *get_base_uri(request_rec *r)
{
const char *uri = r->uri;
int uri_len = strlen(uri);
int i;
for (i=0;i<uri_len; i++)
{
if (uri[uri_len-i] == '/') break;
}
return apr_pstrmemdup(r->pool, uri, uri_len-i);
}
static wmts_error wmts_make_error(int status, const char *exceptionCode, const char *locator, const char *exceptionText)
{
wmts_error error;
error.status = status;
error.exceptionCode = exceptionCode;
error.locator = locator;
error.exceptionText = exceptionText;
return error;
}
static int wmts_return_all_errors(request_rec *r, int errors, wmts_error *wmts_errors)
{
static char preamble[]=
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<ExceptionReport xmlns=\"http://www.opengis.net/ows/1.1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd\" version=\"1.1.0\" xml:lang=\"en\">";
static char postamble[]="\n</ExceptionReport>" ;
ap_set_content_type(r,"text/xml");
ap_rputs(preamble, r);
int i;
for(i = 0; i < errors; i++)
{
wmts_error error = wmts_errors[i];
static char preexception[]="\n<Exception exceptionCode=\"";
static char prelocator[]="\" locator=\"";
static char postlocator[]="\">";
static char pretext[]="\n<ExceptionText>";
static char posttext[]="</ExceptionText>";
static char postexception[]="</Exception>";
ap_rputs(preexception, r);
ap_rputs(error.exceptionCode, r);
ap_rputs(prelocator, r);
ap_rputs(error.locator, r);
ap_rputs(postlocator, r);
ap_rputs(pretext, r);
ap_rputs(error.exceptionText, r);
ap_rputs(posttext, r);
ap_rputs(postexception, r);
r->status = error.status;
error.exceptionCode = 0;
}
ap_rputs(postamble, r);
return OK; // Request handled
}
static apr_array_header_t* tokenize(apr_pool_t *p, const char *s, char sep)
{
apr_array_header_t* arr = apr_array_make(p, 10, sizeof(char *));
while (sep == *s) s++;
char *val;
while (*s && (val = ap_getword(p, &s, sep))) {
char **newelt = (char **)apr_array_push(arr);
*newelt = val;
}
return arr;
}
static const char *add_date_to_uri(apr_pool_t *p, const char *source_str, const char *date_str)
{
if (const char *datefield = ap_strstr(source_str, "${date}")) {
const char *prefix = apr_pstrmemdup(p, source_str, datefield - source_str);
return apr_pstrcat(p, prefix, date_str, datefield + strlen("${date}"), NULL);
}
return source_str;
}
static const char *remove_date_from_uri(apr_pool_t *p, apr_array_header_t *tokens)
{
int i;
char *out_uri = (char *)apr_pcalloc(p, MAX_STRING_LEN);
char *ptr = out_uri;
for (i=0; i<tokens->nelts; i++) {
if (i == tokens->nelts - 5) continue;
*ptr++ = '/';
const char *token = (const char *)APR_ARRAY_IDX(tokens, i, const char *);
apr_cpystrn(ptr, token, MAX_STRING_LEN);
ptr += strlen(token);
}
return out_uri;
}
static const char *get_blank_tile_filename(request_rec *r)
{
const char *blank_tile_filename;
const char *uri = r->uri;
const char *file_ext = uri + strlen(uri) - 4;
apr_table_t *args_table;
ap_args_to_table(r, &args_table);
const char *param = apr_table_get(args_table, "FORMAT");
if (apr_strnatcasecmp(param, "image/jpeg") == 0 || apr_strnatcasecmp(file_ext, ".jpg") == 0) {
blank_tile_filename = "black.jpg";
} else if (apr_strnatcasecmp(param, "image/png") == 0 || apr_strnatcasecmp(file_ext, ".png") == 0) {
blank_tile_filename = "transparent.png";
} else if (apr_strnatcasecmp(param, "application/vnd.mapbox-vector-tile") == 0 || apr_strnatcasecmp(file_ext, ".mvt") == 0) {
blank_tile_filename = "empty.mvt";
} else {
return NULL;
}
return apr_psprintf(r->pool, "%s/%s", get_base_uri(r), blank_tile_filename);
}
static int handleKvP(request_rec *r)
{
wmts_error wmts_errors[10];
int errors = 0;
wmts_wrapper_conf *cfg = (wmts_wrapper_conf *)ap_get_module_config(r->per_dir_config, &wmts_wrapper_module);
apr_table_t *args_table;
ap_args_to_table(r, &args_table);
const char *param = NULL;
const char *version = NULL;
if ((param = apr_table_get(args_table, "VERSION")) && strlen(param)) {
if (apr_strnatcasecmp(param, "1.0.0") == 0) {
version = param;
} else {
wmts_errors[errors++] = wmts_make_error(400,"InvalidParameterValue","VERSION", "VERSION is invalid");
}
} else {
wmts_errors[errors++] = wmts_make_error(400,"MissingParameterValue","VERSION", "Missing VERSION parameter");
}
const char *style = NULL;
if ((param = apr_table_get(args_table, "STYLE")) && strlen(param)) {
style = param;
} else {
style = "default";
}
const char *time = NULL;
if ((param = apr_table_get(args_table, "TIME")) && strlen(param)) {
// Verify that the date is in the right format
if (ap_regexec(cfg->date_regexp, param, 0, NULL, 0) == AP_REG_NOMATCH
&& apr_strnatcasecmp(param, "default")) {
wmts_errors[errors++] = wmts_make_error(400,"InvalidParameterValue","TIME", "Invalid time format, must be YYYY-MM-DD or YYYY-MM-DDThh:mm:ssZ");
} else {
time = param;
}
}
const char *request = NULL;
if ((param = apr_table_get(args_table, "REQUEST")) && strlen(param)) {
if (apr_strnatcasecmp(param, "GetCapabilities") != 0 && apr_strnatcasecmp(param, "GetTile") != 0 && apr_strnatcasecmp(param, "GetTileService") != 0) {
wmts_errors[errors++] = wmts_make_error(501, "OperationNotSupported","REQUEST", "The request type is not supported");
} else {
request = param;
}
} else {
wmts_errors[errors++] = wmts_make_error(400,"MissingParameterValue","REQUEST", "Missing REQUEST parameter");
}
const char *layer = NULL;
if ((param = apr_table_get(args_table, "LAYER")) && strlen(param)) {
layer = param;
} else {
if (request && apr_strnatcasecmp(request, "GetCapabilities") != 0 && apr_strnatcasecmp(request, "GetTileService") != 0) {
wmts_errors[errors++] = wmts_make_error(400,"MissingParameterValue","LAYER", "Missing LAYER parameter");
}
}
const char *service = NULL;
if (((param = apr_table_get(args_table, "SERVICE")) || (param = apr_table_get(args_table, "wmts.cgi?SERVICE"))) && strlen(param)) { // mod_onearth is doing weird things with the arguments list
if (apr_strnatcasecmp(param, "WMTS"))
wmts_errors[errors++] = wmts_make_error(400,"InvalidParameterValue","SERVICE", "Unrecognized service");
} else {
wmts_errors[errors++] = wmts_make_error(400,"MissingParameterValue","SERVICE", "Missing SERVICE parameter");
}
const char *format = NULL;
if (request && apr_strnatcasecmp(request, "GetTile") == 0) {
if ((param = apr_table_get(args_table, "FORMAT")) && strlen(param)) {
if (apr_strnatcasecmp(param, "image/jpeg") == 0) {
format = ".jpg";
} else if (apr_strnatcasecmp(param, "image/png") == 0) {
format = ".png";
} else if (apr_strnatcasecmp(param, "image/tiff") == 0) {
format = ".tiff";
} else if (apr_strnatcasecmp(param, "image/lerc") == 0) {
format = ".lerc";
} else if (apr_strnatcasecmp(param, "application/vnd.mapbox-vector-tile") == 0) {
format = ".mvt";
} else {
wmts_errors[errors++] = wmts_make_error(400,"InvalidParameterValue","FORMAT", "FORMAT is invalid for LAYER");
}
} else {
wmts_errors[errors++] = wmts_make_error(400,"MissingParameterValue","FORMAT", "Missing FORMAT parameter");
}
const char *tilematrixset = NULL;
if ((param = apr_table_get(args_table, "TILEMATRIXSET")) && strlen(param)) {
tilematrixset = param;
} else {
wmts_errors[errors++] = wmts_make_error(400,"MissingParameterValue","TILEMATRIXSET", "Missing TILEMATRIXSET parameter");
}
const char *tile_l = NULL;
if ((param = apr_table_get(args_table, "TILEMATRIX")) && strlen(param)) {
tile_l = param;
} else {
wmts_errors[errors++] = wmts_make_error(400,"MissingParameterValue","TILEMATRIX", "Missing TILEMATRIX parameter");
}
const char *tile_x = NULL;
if ((param = apr_table_get(args_table, "TILEROW")) && strlen(param)) {
tile_x = param;
} else {
wmts_errors[errors++] = wmts_make_error(400,"MissingParameterValue","TILEROW", "Missing TILEROW parameter");
}
const char *tile_y = NULL;
if ((param = apr_table_get(args_table, "TILECOL")) && strlen(param)) {
tile_y = param;
} else {
wmts_errors[errors++] = wmts_make_error(400,"MissingParameterValue","TILECOL", "Missing TILECOL parameter");
}
if (errors) {
return wmts_return_all_errors(r, errors, wmts_errors);
}
const char *out_uri = apr_psprintf(r->pool, "%s/%s/%s/%s/%s/%s/%s%s",
get_base_uri(r),
layer,
style,
tilematrixset,
tile_l,
tile_x,
tile_y,
format
);
apr_table_set(r->notes, "mod_wmts_wrapper_date", time ? time : "default");
apr_table_set(r->notes, "mod_onearth_handled", "true");
ap_internal_redirect(out_uri, r);
return OK;
} else if (request && apr_strnatcasecmp(request, "GetCapabilities") == 0) {
ap_internal_redirect(apr_psprintf(r->pool, "%s/%s", get_base_uri(r), "getCapabilities.xml"), r);
return DECLINED;
} else if (request && apr_strnatcasecmp(request, "GetTileService") == 0) {
ap_internal_redirect(apr_psprintf(r->pool, "%s/%s", get_base_uri(r), "getTileService.xml"), r);
return DECLINED;
}
if (errors) {
return wmts_return_all_errors(r, errors, wmts_errors);
}
return DECLINED;
}
// static const char *get_date_from_uri(apr_pool_t *p, wmts_wrapper_conf *cfg, const char *uri)
// {
// const char *pattern = "\\d{4}-\\d{2}-\\d{2}";
// ap_regex_t *time_regexp = (ap_regex_t *)apr_palloc(p, sizeof(ap_regex_t));
// ap_regmatch_t matches[AP_MAX_REG_MATCH];
// ap_regcomp(time_regexp, pattern, 0);
// if (ap_regexec(time_regexp, uri, AP_MAX_REG_MATCH, matches, 0) != AP_REG_NOMATCH) {
// return apr_pstrmemdup(p, uri + matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so);
// }
// return "";
// }
/* The pre-hook function does a few things.
-- For requests with a date, it verifies that the date is good, then adds the date to the request
notes while stripping it from the URI. It then redirects the request to the URI without a date.
This allows us to keep a flat directory structure for the configs despite the fact that
the date param is always changing.
-- Then, when the request comes back around (this time into the TMS directory), we grab the configuration for
mod_reproject, modify it with a source path that includes the date, and put the new config in the request_config
area.
-- We also do a basic check to see if the tile request is within the accepted dimensions for this TMS.
This is possible because we're grabbing the mod_reproject configuration and getting those values from it.
*/
static int pre_hook(request_rec *r)
{
char *err_msg;
// If mod_onearth is configured for this endpoint and hasn't handled the request yet, ignore it.
if (module *onearth_module = (module *)ap_find_linked_module("mod_onearth.c")) {
wms_cfg *onearth_config = (wms_cfg *)ap_get_module_config(r->per_dir_config, onearth_module);
if (onearth_config->caches && (!r->prev || !apr_table_get(r->prev->notes, "mod_onearth_handled"))) {
apr_table_set(r->notes, "mod_wmts_wrapper_enabled", "true");
return DECLINED;
}
}
// Make sure that this note survives into the next request.
if (r->prev && apr_table_get(r->prev->notes, "mod_onearth_handled")) {
apr_table_set(r->notes, "mod_onearth_handled", "true");
}
wmts_error wmts_errors[5];
int errors = 0;
wmts_wrapper_conf *cfg = (wmts_wrapper_conf *)ap_get_module_config(r->per_dir_config, &wmts_wrapper_module);
if (!cfg->role) return DECLINED;
if (apr_strnatcasecmp(cfg->role, "root") == 0) {
return DECLINED;
} else if (apr_strnatcasecmp(cfg->role, "style") == 0 && cfg->time) {
// If we've already handled the date, but are still getting stuck at the STYLE part of the REST request, we know the TMS is bad.
if (apr_table_get(r->notes, "mod_wmts_wrapper_date") || (r->prev && apr_table_get(r->prev->notes, "mod_wmts_wrapper_date"))) {
wmts_errors[errors++] = wmts_make_error(400,"InvalidParameterValue","TILEMATRIXSET", "TILEMATRIXSET is invalid for LAYER");
return wmts_return_all_errors(r, errors, wmts_errors);
}
apr_array_header_t *tokens = tokenize(r->pool, r->uri, '/');
char *datetime_str = (char *)APR_ARRAY_IDX(tokens, tokens->nelts - 5, char *);
// Verify that the date is in the right format
if (ap_regexec(cfg->date_regexp, datetime_str, 0, NULL, 0) == AP_REG_NOMATCH
&& apr_strnatcasecmp(datetime_str, "default")) {
wmts_errors[errors++] = wmts_make_error(400,"InvalidParameterValue","TIME", "Invalid time format, must be YYYY-MM-DD or YYYY-MM-DDThh:mm:ssZ");
return wmts_return_all_errors(r, errors, wmts_errors);
}
// Rewrite URI to exclude date and put the date in the notes for the redirect.
const char *out_uri = remove_date_from_uri(r->pool, tokens);
// request_rec *rr = ap_sub_req_lookup_uri(out_uri, r, r->output_filters);
apr_table_set(r->notes, "mod_wmts_wrapper_date", datetime_str);
// return ap_run_sub_req(rr);
ap_internal_redirect(out_uri, r);
return DECLINED;
} else if (apr_strnatcasecmp(cfg->role, "tilematrixset") == 0) {
// If we get to this point, we know mod_reproject is configured for this endpoint, so keep mod_onearth from handling it
if (module *old_onearth_module = (module *)ap_find_linked_module("mod_onearth.c")) {
apr_table_set(r->notes, "mod_onearth_handled", "true");
}
const char *datetime_str = r->prev && apr_table_get(r->prev->notes, "mod_wmts_wrapper_date")
? apr_table_get(r->prev->notes, "mod_wmts_wrapper_date")
: "default";
// Start by verifying the requested tile coordinates/format from the URI against the mod_reproject configuration for this endpoint
apr_array_header_t *tokens = tokenize(r->pool, r->uri, '/');
const char *dim;
dim = *(char **)apr_array_pop(tokens);
const char *extension = ap_strchr(dim, '.');
if (extension && cfg->mime_type) {
if (!check_valid_extension(cfg, extension)) {
err_msg = "FORMAT is invalid for LAYER";
wmts_errors[errors++] = wmts_make_error(400, "InvalidParameterValue","FORMAT", err_msg);
}
}
if (!isdigit(*dim)) wmts_errors[errors++] = wmts_make_error(400, "InvalidParameterValue","TILECOL", "TILECOL is not a valid integer");
int tile_x = apr_atoi64(dim);
dim = *(char **)apr_array_pop(tokens);
if (!isdigit(*dim)) wmts_errors[errors++] = wmts_make_error(400, "InvalidParameterValue","TILEROW", "TILEROW is not a valid integer");
int tile_y = apr_atoi64(dim);
dim = *(char **)apr_array_pop(tokens);
if (!isdigit(*dim)) wmts_errors[errors++] = wmts_make_error(400, "InvalidParameterValue","TILEMATRIX", "TILEMATRIX is not a valid integer");
int tile_l = apr_atoi64(dim);
module *reproject_module = (module *)ap_find_linked_module("mod_reproject.cpp");
repro_conf *reproject_config = (repro_conf *)ap_get_module_config(r->per_dir_config, reproject_module);
if (reproject_config->source) {
// Get the tile grid bounds from mod_reproject config and comapre them with the requested tile.
if (tile_l > reproject_config->raster.n_levels || tile_l < 0) {
wmts_errors[errors++] = wmts_make_error(400, "InvalidParameterValue","TILEMATRIX", "Invalid TILEMATRIX");
} else if (tile_x >= reproject_config->raster.rsets[tile_l].width || tile_x < 0) {
err_msg = apr_psprintf(r->pool, "TILECOL is out of range, maximum value is %d", reproject_config->raster.rsets[tile_l].width - 1);
wmts_errors[errors++] = wmts_make_error(400, "TileOutOfRange","TILECOL", err_msg);
} else if (tile_y >= reproject_config->raster.rsets[tile_l].height || tile_y < 0) {
err_msg = apr_psprintf(r->pool, "TILEROW is out of range, maximum value is %d", reproject_config->raster.rsets[tile_l].height - 1);
wmts_errors[errors++] = wmts_make_error(400, "TileOutOfRange","TILEROW", err_msg);
}
if (errors) return wmts_return_all_errors(r, errors, wmts_errors);
if (cfg->time) {
// If this is a directory that mod_reproject is configured to run in, create a new configuration, replacing the
// source URL ${date} field with the date for this request.
if (reproject_config->source) {
repro_conf *out_cfg = (repro_conf *)apr_palloc(r->pool, sizeof(repro_conf));
memcpy(out_cfg, reproject_config, sizeof(repro_conf));
out_cfg->source = add_date_to_uri(r->pool, reproject_config->source, datetime_str);
ap_set_module_config(r->request_config, reproject_module, out_cfg);
}
}
}
if (errors) return wmts_return_all_errors(r, errors, wmts_errors);
}
return DECLINED;
}
/* The handler is set to run at the very end of the stack. Essentially, if a request hasn't been
picked up by this point, we know that something is wrong with it and use the Role tag to determine
what that is.
*/
static int post_hook(request_rec *r)
{
wmts_error wmts_errors[5];
int errors = 0;
wmts_wrapper_conf *cfg = (wmts_wrapper_conf *)ap_get_module_config(r->per_dir_config, &wmts_wrapper_module);
if (!cfg->role) return DECLINED;
// First check to see if request is for a valid file.
apr_finfo_t *fileinfo = (apr_finfo_t *)apr_palloc(r->pool, sizeof(apr_finfo_t));
if (apr_stat(fileinfo, r->filename, 0, r->pool) == APR_SUCCESS) return DECLINED;
if (!apr_strnatcasecmp(cfg->role, "root")) {
// If mod_onearth has handled and failed this request, we serve up the appropriate blank tile (if it exists)
if (apr_table_get(r->notes, "mod_onearth_failed")) {
if (const char *blank_tile_url = get_blank_tile_filename(r)) {
ap_internal_redirect(blank_tile_url, r);
}
return DECLINED;
}
if (r->args) return handleKvP(r);
wmts_errors[errors++] = wmts_make_error(400, "InvalidParameterValue", "LAYER", "LAYER does not exist");
return wmts_return_all_errors(r, errors, wmts_errors);
}
if (!apr_strnatcasecmp(cfg->role, "layer")) {
// If we've already handled a date for this request, we know that it's a TMS error and not a STYLE error
if (r->prev && apr_table_get(r->prev->notes, "mod_wmts_wrapper_date") && !r->prev->args) {
wmts_errors[errors++] = wmts_make_error(400,"InvalidParameterValue","TILEMATRIXSET", "TILEMATRIXSET is invalid for LAYER");
} else {
wmts_errors[errors++] = wmts_make_error(400,"InvalidParameterValue","STYLE", "STYLE is invalid for LAYER");
}
return wmts_return_all_errors(r, errors, wmts_errors);
}
if (!apr_strnatcasecmp(cfg->role, "style")) {
wmts_errors[errors++] = wmts_make_error(400,"InvalidParameterValue","TILEMATRIXSET", "TILEMATRIXSET is invalid for LAYER");
return wmts_return_all_errors(r, errors, wmts_errors);
}
if (!apr_strnatcasecmp(cfg->role, "tilematrixset")) {
// This would be a tile-level request and as such errors are handled by the pre-hook.
}
return DECLINED;
}
static const char *set_module(cmd_parms *cmd, void *dconf, const char *role)
{
wmts_wrapper_conf *cfg = (wmts_wrapper_conf *)dconf;
cfg->role = apr_pstrdup(cmd->pool, role);
const char *pattern = "^\\d{4}-\\d{2}-\\d{2}$|^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$";
cfg->date_regexp = (ap_regex_t *)apr_palloc(cmd->pool, sizeof(ap_regex_t));
if (ap_regcomp(cfg->date_regexp, pattern, 0)) {
return "Error -- bad date regexp";
}
return NULL;
}
static const char *enable_time(cmd_parms *cmd, void *dconf, int arg)
{
wmts_wrapper_conf *cfg = (wmts_wrapper_conf *)dconf;
cfg->time = arg;
return NULL;
}
static const char *set_mime_type(cmd_parms *cmd, void *dconf, const char *format)
{
wmts_wrapper_conf *cfg = (wmts_wrapper_conf *)dconf;
cfg->mime_type = apr_pstrdup(cmd->pool, format);
return NULL;
}
static void *create_dir_config(apr_pool_t *p, char *unused)
{
return apr_pcalloc(p, sizeof(wmts_wrapper_conf));
}
static void* merge_dir_conf(apr_pool_t *p, void *BASE, void *ADD) {
wmts_wrapper_conf *base = (wmts_wrapper_conf *)BASE;
wmts_wrapper_conf *add = (wmts_wrapper_conf *)ADD;
wmts_wrapper_conf *cfg = (wmts_wrapper_conf *)apr_palloc(p, sizeof(wmts_wrapper_conf));
cfg->role = ( add->role == NULL ) ? base->role : add->role;
cfg->time = ( add->time == NULL ) ? base->time : add->time;
cfg->date_regexp = ( add->date_regexp == NULL ) ? base->date_regexp : add->date_regexp;
cfg->mime_type = ( add->mime_type == NULL ) ? base->mime_type : add->mime_type;
return cfg;
}
static void register_hooks(apr_pool_t *p)
{
ap_hook_handler(pre_hook, NULL, NULL, APR_HOOK_FIRST-1);
ap_hook_handler(post_hook, NULL, NULL, APR_HOOK_LAST);
}
static const command_rec cmds[] =
{
AP_INIT_TAKE1(
"WMTSWrapperRole",
(cmd_func) set_module, // Callback
0, // Self pass argument
ACCESS_CONF,
"Set role for the WMTS module in this <Directory> block"
),
AP_INIT_FLAG(
"WMTSWrapperEnableTime",
(cmd_func) enable_time, // Callback
0, // Self pass argument
ACCESS_CONF,
"Enable Time handling for WMTS wrapper module for this layer directory"
),
AP_INIT_TAKE1(
"WMTSWrapperMimeType",
(cmd_func) set_mime_type, // Callback
0, // Self pass argument
ACCESS_CONF,
"Set MIME for the WMTS module in this <Directory> block"
),
{NULL}
};
module AP_MODULE_DECLARE_DATA wmts_wrapper_module = {
STANDARD20_MODULE_STUFF,
create_dir_config,
merge_dir_conf,
0, // No server_config
0, // No server_merge
cmds, // configuration directives
register_hooks // processing hooks
};
| 43.091463 | 246 | 0.640123 | [
"vector"
] |
ff20973a70d1006dc8d6d2e5541dac49a675944e | 1,485 | hpp | C++ | include/codegen/include/GlobalNamespace/BetaBuildInfoText.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/BetaBuildInfoText.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/BetaBuildInfoText.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: TMPro
namespace TMPro {
// Forward declaring type: TextMeshProUGUI
class TextMeshProUGUI;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: BetaBuildInfoText
class BetaBuildInfoText : public UnityEngine::MonoBehaviour {
public:
// private TMPro.TextMeshProUGUI _text
// Offset: 0x18
TMPro::TextMeshProUGUI* text;
// protected System.Void Start()
// Offset: 0xB7B3F8
void Start();
// public System.Void .ctor()
// Offset: 0xB7B420
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static BetaBuildInfoText* New_ctor();
}; // BetaBuildInfoText
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BetaBuildInfoText*, "", "BetaBuildInfoText");
#pragma pack(pop)
| 34.534884 | 85 | 0.691582 | [
"object"
] |
ff20d35e14312c8294bf11760a906b467342ef69 | 600 | hpp | C++ | sources/Notebook.hpp | Almog-David/CPP_Ex2_b | 2fde78801fe65b03809bb76d6e013597af27bf04 | [
"MIT"
] | null | null | null | sources/Notebook.hpp | Almog-David/CPP_Ex2_b | 2fde78801fe65b03809bb76d6e013597af27bf04 | [
"MIT"
] | null | null | null | sources/Notebook.hpp | Almog-David/CPP_Ex2_b | 2fde78801fe65b03809bb76d6e013597af27bf04 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <unordered_map>
#include "Direction.hpp"
#define LIMIT 100
using namespace std;
namespace ariel
{
class Notebook
{
private:
unordered_map<int, unordered_map<int, vector<char>>> notebook;
public:
Notebook();
~Notebook();
void write(int page, int row, int col, Direction direction, string text);
string read(int page, int row, int col, Direction direction, int numOfChars);
void erase(int page, int row, int col, Direction direction, int numOfChars);
void show(int page);
};
}; | 26.086957 | 85 | 0.656667 | [
"vector"
] |
ff22543029c8de5cd8ea5f2e7cb1efcccbe8a7f8 | 3,404 | cc | C++ | lib/spot-2.8.1/spot/twaalgos/isweakscc.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | lib/spot-2.8.1/spot/twaalgos/isweakscc.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | lib/spot-2.8.1/spot/twaalgos/isweakscc.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | // -*- coding: utf-8 -*-
// Copyright (C) 2012-2019 Laboratoire de Recherche et Développement
// de l'Epita (LRDE).
//
// This file is part of Spot, a model checking library.
//
// Spot 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.
//
// Spot 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 this program. If not, see <http://www.gnu.org/licenses/>.
#include "config.h"
#include <spot/tl/formula.hh>
#include <spot/twaalgos/isweakscc.hh>
#include <spot/twaalgos/genem.hh>
namespace spot
{
namespace
{
[[noreturn]] static void
invalid_scc_number(const char* fn)
{
throw std::invalid_argument(std::string(fn) + "(): invalid SCC number");
}
}
bool
scc_has_rejecting_cycle(scc_info& map, unsigned scc)
{
if (SPOT_UNLIKELY(scc >= map.scc_count()))
invalid_scc_number("scc_has_rejecting_cycle");
acc_cond neg_acc = map.get_aut()->get_acceptance().complement();
return !generic_emptiness_check_for_scc(map, scc, neg_acc);
}
bool
is_inherently_weak_scc(scc_info& map, unsigned scc)
{
if (SPOT_UNLIKELY(scc >= map.scc_count()))
invalid_scc_number("is_inherently_weak_scc");
// Weak SCCs are inherently weak.
if (is_weak_scc(map, scc))
return true;
// If we reach this place, we now the SCC has an accepting cycle.
// The question is now to find whether is also contains a
// rejecting cycle.
return !scc_has_rejecting_cycle(map, scc);
}
bool
is_weak_scc(scc_info& map, unsigned scc)
{
if (SPOT_UNLIKELY(scc >= map.scc_count()))
invalid_scc_number("is_weak_scc");
// Rejecting SCCs are weak.
if (map.is_rejecting_scc(scc))
return true;
// If all transitions use the same acceptance set, the SCC is weak.
return map.marks_of(scc).size() == 1;
}
bool
is_complete_scc(scc_info& map, unsigned scc)
{
if (SPOT_UNLIKELY(scc >= map.scc_count()))
invalid_scc_number("is_complete_scc");
auto a = map.get_aut();
for (auto s: map.states_of(scc))
{
bool has_succ = false;
bdd sumall = bddfalse;
for (auto& t: a->out(s))
{
has_succ = true;
bool in = true;
for (auto d: a->univ_dests(t.dst))
if (map.scc_of(d) != scc)
{
in = false;
break;
}
if (!in)
continue;
sumall |= t.cond;
if (sumall == bddtrue)
break;
}
if (!has_succ || sumall != bddtrue)
return false;
}
return true;
}
bool
is_terminal_scc(scc_info& map, unsigned scc)
{
if (SPOT_UNLIKELY(scc >= map.scc_count()))
invalid_scc_number("is_terminal_scc");
// If all transitions use all acceptance conditions, the SCC is weak.
return (map.is_accepting_scc(scc)
&& map.marks_of(scc).size() == 1
&& is_complete_scc(map, scc));
}
}
| 29.6 | 78 | 0.62691 | [
"model"
] |
ff241b4a19bdf7dd95eff8cd37b85f56264f209d | 1,624 | cpp | C++ | lib/lsd/OggReader.cpp | nonwill/lsd2dsl | 00e2a9832666dff03667b07815d73fab3fa8378e | [
"MIT"
] | 1 | 2020-12-28T20:23:35.000Z | 2020-12-28T20:23:35.000Z | dictlsd/OggReader.cpp | al-yakubovich/lsd2dsl | 22503988bcbd4ea7006a3ac291e71476f8e20a1a | [
"MIT"
] | null | null | null | dictlsd/OggReader.cpp | al-yakubovich/lsd2dsl | 22503988bcbd4ea7006a3ac291e71476f8e20a1a | [
"MIT"
] | 1 | 2020-10-09T02:58:27.000Z | 2020-10-09T02:58:27.000Z | #include "OggReader.h"
#include "BitStream.h"
#include <vorbis/vorbisfile.h>
#include <stdexcept>
#include <assert.h>
namespace dictlsd {
size_t read_func(void *ptr, size_t size, size_t nmemb, void *datasource) {
auto bstr = static_cast<IRandomAccessStream*>(datasource);
bstr->readSome(ptr, size * nmemb);
return nmemb;
}
ov_callbacks callbacks {
read_func,
NULL,
NULL,
NULL
};
OggReader::OggReader(IRandomAccessStream *bstr)
: _vbitstream(0)
{
_vfile.reset(new OggVorbis_File());
int res = ov_open_callbacks(bstr, _vfile.get(), NULL, 0, callbacks);
if (res) {
throw std::runtime_error("can't read ogg file");
}
}
const unsigned BUFF_SIZE = 4096;
short buffer[BUFF_SIZE / 2];
void OggReader::readSamples(unsigned count, std::vector<short> &vec) {
vec.clear();
count *= 2; // samples -> bytes
while (count) {
unsigned toRead = std::min(count, BUFF_SIZE);
long bytesRead = ov_read(_vfile.get(), (char*)buffer, toRead, 0, 2, 1, &_vbitstream);
if (bytesRead == OV_HOLE ||
bytesRead == OV_EBADLINK ||
bytesRead == OV_EINVAL)
{
throw std::runtime_error("error reading samples");
}
if (bytesRead == 0) {
throw std::runtime_error("unexpected eof");
}
count -= bytesRead;
std::copy(buffer, buffer + bytesRead / sizeof(short), std::back_inserter(vec));
}
}
uint64_t OggReader::totalSamples() {
return ov_pcm_total(_vfile.get(), -1);
}
OggReader::~OggReader() { }
}
| 25.777778 | 94 | 0.601601 | [
"vector"
] |
ff2424fb60170b0e8f75fbc38c5c73d8b6f7b948 | 2,239 | cpp | C++ | src/examples/tutorial/ascent_intro/cpp/ascent_scene_example3.cpp | srini009/ascent | 70558059dc3fe514206781af6e48715d8934c37c | [
"BSD-3-Clause"
] | null | null | null | src/examples/tutorial/ascent_intro/cpp/ascent_scene_example3.cpp | srini009/ascent | 70558059dc3fe514206781af6e48715d8934c37c | [
"BSD-3-Clause"
] | null | null | null | src/examples/tutorial/ascent_intro/cpp/ascent_scene_example3.cpp | srini009/ascent | 70558059dc3fe514206781af6e48715d8934c37c | [
"BSD-3-Clause"
] | null | null | null | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) Lawrence Livermore National Security, LLC and other Ascent
// Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
// other details. No copyright assignment is required to contribute to Ascent.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//-----------------------------------------------------------------------------
///
/// file: ascent_scene_example3.cpp
///
//-----------------------------------------------------------------------------
#include <iostream>
#include "ascent.hpp"
#include "conduit_blueprint.hpp"
#include "ascent_tutorial_cpp_utils.hpp"
using namespace ascent;
using namespace conduit;
int main(int argc, char **argv)
{
Node mesh;
// (call helper to create example tet mesh as in blueprint example 2)
tutorial_tets_example(mesh);
// Use Ascent to render with views with different camera parameters
Ascent a;
// open ascent
a.open();
// publish mesh to ascent
a.publish(mesh);
// setup actions
Node actions;
Node &add_act = actions.append();
add_act["action"] = "add_scenes";
// declare a scene to render the dataset
Node &scenes = add_act["scenes"];
//
// You can define renders to control the parameters of a single output image.
// Scenes support multiple renders.
//
// See the Renders docs for more details:
// https://ascent.readthedocs.io/en/latest/Actions/Scenes.html#renders-optional
//
// setup our scene (s1) with two renders (r1 and r2)
scenes["s1/plots/p1/type"] = "pseudocolor";
scenes["s1/plots/p1/field"] = "var1";
// render a view (r1) with a slight adjustment to camera azimuth
scenes["s1/renders/r1/image_name"] = "out_scene_ex3_view1";
scenes["s1/renders/r1/camera/azimuth"] = 10.0;
// render a view (r2) that zooms in from the default camera
scenes["s1/renders/r2/image_name"] = "out_scene_ex3_view2";
scenes["s1/renders/r2/camera/zoom"] = 3.0;
// print our full actions tree
std::cout << actions.to_yaml() << std::endl;
// execute the actions
a.execute(actions);
a.close();
}
| 29.077922 | 83 | 0.579723 | [
"mesh",
"render"
] |
ff261a94d7070671c2b8d63c15635170729ead51 | 1,880 | cpp | C++ | src/day23.cpp | foolnotion/aoc2020 | 49738011e8181af438c13556a294b939880916c9 | [
"Unlicense"
] | null | null | null | src/day23.cpp | foolnotion/aoc2020 | 49738011e8181af438c13556a294b939880916c9 | [
"Unlicense"
] | null | null | null | src/day23.cpp | foolnotion/aoc2020 | 49738011e8181af438c13556a294b939880916c9 | [
"Unlicense"
] | 2 | 2020-12-12T21:42:53.000Z | 2020-12-16T20:56:56.000Z | #include <algorithm>
#include <bitset>
#include <execution>
#include <fmt/format.h>
#include <functional>
#include <initializer_list>
#include <list>
#include <robin_hood.h>
#include <stack>
#include "advent.hpp"
#include "util.hpp"
struct node {
int64_t value;
node* next { nullptr };
};
int day23(int argc, char** argv)
{
//std::vector<int> cups { 3, 8, 9, 1, 2, 5, 4, 6, 7 };
std::vector<int> cups { 6, 2, 4, 3, 9, 7, 1, 5, 8 };
std::vector<node*> index(1'000'000 + 1);
std::vector<node> nodes(1'000'000);
for (int i = 0; i < cups.size(); ++i) {
nodes[i] = { cups[i], nullptr };
index[nodes[i].value] = &nodes[i];
if (i > 0) {
nodes[i - 1].next = &nodes[i];
}
}
for (int i = cups.size(); i < 1'000'000; ++i) {
nodes[i] = { i+1, nullptr };
index[nodes[i].value] = &nodes[i];
if (i > 0) {
nodes[i - 1].next = &nodes[i];
}
}
nodes.back().next = &nodes[0];
int lo = 1;
int hi = 1'000'000;
int move = 0;
int max_rounds = 10'000'000;
std::array<int64_t, 3> picked;
node *p = &nodes[0], *q = nullptr, *r = nullptr;
for (int round = 0; round < max_rounds; ++round) {
q = p->next;
picked[0] = q->value; q = q->next;
picked[1] = q->value; q = q->next;
picked[2] = q->value;
auto d = p->value - 1; if (d < lo) d = hi;
while(std::find(picked.begin(), picked.end(), d) != picked.end()) {
if (--d < lo) d = hi;
}
r = index[d];
auto tmp = q->next;
q->next = r->next;
r->next = p->next;
p->next = tmp;
p = p->next;
}
auto x = index[1];
fmt::print("{} {} {}\n", x->value, x->next->value, x->next->next->value);
fmt::print("{}\n", x->next->value * x->next->next->value);
return 0;
}
| 23.5 | 77 | 0.485106 | [
"vector"
] |
ff28cc0a7758673da1fd0049527219cc441ff670 | 688 | cpp | C++ | Kattis-Solutions/Almost Perfect.cpp | SurgicalSteel/Competitive-Programming | 3662b676de94796f717b25dc8d1b93c6851fb274 | [
"MIT"
] | 14 | 2016-02-11T09:26:13.000Z | 2022-03-27T01:14:29.000Z | Kattis-Solutions/Almost Perfect.cpp | SurgicalSteel/Competitive-Programming | 3662b676de94796f717b25dc8d1b93c6851fb274 | [
"MIT"
] | null | null | null | Kattis-Solutions/Almost Perfect.cpp | SurgicalSteel/Competitive-Programming | 3662b676de94796f717b25dc8d1b93c6851fb274 | [
"MIT"
] | 7 | 2016-10-25T19:29:35.000Z | 2021-12-05T18:31:39.000Z | //template provided by SurgicalSteel a.k.a Yuwono Bangun Nagoro
#include <bits/stdc++.h>
#define psb push_back
using namespace std;
long long int absolutey(long long int x)
{
if(x>0){return x;}
else{return x*-1;}
}
int main()
{
int x;
long long int res=0,a=0;
while(cin>>x)
{
vector<long long int> v;
for(int i=1;i<=sqrt(x);++i)
{
if(i==1){v.psb(i);}
else if(x%i==0&&(x/i)!=i){v.psb(i);v.psb(x/i);}
else if(x%i==0&&(x/i)==i){v.psb(i);}
}
res=0;
a=0;
for(int i=0;i<v.size();++i){res+=v[i];}
a=res-x;
if(res==x){printf("%d perfect\n",x);}
else if(absolutey(a)<=2){printf("%d almost perfect\n",x);}
else{printf("%d not perfect\n",x);}
}
return 0;
}
| 20.848485 | 63 | 0.579942 | [
"vector"
] |
ff2a97fc8dbafac17dd13cae54353b8685ad4769 | 29,574 | cpp | C++ | plugins/protein/src/FrodockLoader.cpp | masrice/megamol | d48fc4889f500528609053a5445202a9c0f6e5fb | [
"BSD-3-Clause"
] | 49 | 2017-08-23T13:24:24.000Z | 2022-03-16T09:10:58.000Z | plugins/protein/src/FrodockLoader.cpp | masrice/megamol | d48fc4889f500528609053a5445202a9c0f6e5fb | [
"BSD-3-Clause"
] | 200 | 2018-07-20T15:18:26.000Z | 2022-03-31T11:01:44.000Z | plugins/protein/src/FrodockLoader.cpp | masrice/megamol | d48fc4889f500528609053a5445202a9c0f6e5fb | [
"BSD-3-Clause"
] | 31 | 2017-07-31T16:19:29.000Z | 2022-02-14T23:41:03.000Z | /*
* FrodockLoader.cpp
*
* Copyright (C) 2010 by University of Stuttgart (VISUS).
* All rights reserved.
*/
#include "FrodockLoader.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/FilePathParam.h"
#include "mmcore/param/IntParam.h"
#include "mmcore/param/StringParam.h"
#include "mmcore/utility/log/Log.h"
#include "mmcore/utility/sys/ASCIIFileBuffer.h"
#include "mmcore/utility/sys/MemmappedFile.h"
#include "stdafx.h"
#include "vislib/ArrayAllocator.h"
#include "vislib/SmartPtr.h"
#include "vislib/StringConverter.h"
#include "vislib/StringTokeniser.h"
#include "vislib/math/mathfunctions.h"
#include "vislib/net/DNS.h"
#include "vislib/net/IPEndPoint.h"
#include "vislib/net/SocketException.h"
#include "vislib/sys/sysfunctions.h"
#include "vislib/types.h"
#include <ctime>
#include <iostream>
#include <omp.h>
using namespace megamol;
using namespace megamol::core;
using namespace megamol::protein;
using namespace megamol::protein_calls;
/*
* protein::FrodockLoader::FrodockLoader
*/
FrodockLoader::FrodockLoader(void)
: Module()
, filenameSlot("filename", "The path to the PDB data file to be loaded")
, dataOutSlot("dataout", "The slot providing the loaded data")
, strideFlagSlot("strideFlag", "The flag wether STRIDE should be used or not.")
, receptorDataCallerSlot("receptorData", "The slot providing the data of the receptor molecule.")
, ligandDataCallerSlot("ligandData", "The slot providing the data of the ligand.")
, fileServerNameSlot("fileServerName", "The file server name (for linux file paths).")
, hostAddressSlot("hostAddress", "The host address of the machine on which Frodock is running.")
, portSlot("port", "The port over which the communication is executed.")
, bbox(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f)
, datahash(0)
, currentSolution(-1) {
this->filenameSlot << new param::FilePathParam("");
this->MakeSlotAvailable(&this->filenameSlot);
this->dataOutSlot.SetCallback(megamol::protein_calls::MolecularDataCall::ClassName(),
megamol::protein_calls::MolecularDataCall::FunctionName(
megamol::protein_calls::MolecularDataCall::CallForGetData),
&FrodockLoader::getData);
this->dataOutSlot.SetCallback(megamol::protein_calls::MolecularDataCall::ClassName(),
megamol::protein_calls::MolecularDataCall::FunctionName(
megamol::protein_calls::MolecularDataCall::CallForGetExtent),
&FrodockLoader::getExtent);
this->MakeSlotAvailable(&this->dataOutSlot);
this->strideFlagSlot << new param::BoolParam(true);
this->MakeSlotAvailable(&this->strideFlagSlot);
// receptor
this->receptorDataCallerSlot.SetCompatibleCall<megamol::protein_calls::MolecularDataCallDescription>();
this->MakeSlotAvailable(&this->receptorDataCallerSlot);
// ligand
this->ligandDataCallerSlot.SetCompatibleCall<megamol::protein_calls::MolecularDataCallDescription>();
this->MakeSlotAvailable(&this->ligandDataCallerSlot);
// file server name
this->fileServerNameSlot << new param::StringParam("");
this->MakeSlotAvailable(&this->fileServerNameSlot);
// host
this->hostAddressSlot << new param::StringParam("");
this->MakeSlotAvailable(&this->hostAddressSlot);
// port (default, min, max)
this->portSlot << new param::IntParam(1234, 1024, 32767);
this->MakeSlotAvailable(&this->portSlot);
// set potential-pointer to null
this->frodockInput.potentials = 0;
}
/*
* protein::FrodockLoader::~FrodockLoader
*/
FrodockLoader::~FrodockLoader(void) {
this->Release();
}
/*
* FrodockLoader::create
*/
bool FrodockLoader::create(void) {
// set default values to frodockInput
memset(frodockInput.receptor, 0, NAMESIZE * sizeof(char));
memset(frodockInput.ligand, 0, NAMESIZE * sizeof(char));
memset(frodockInput.vdw, 0, NAMESIZE * sizeof(char));
frodockInput.vdw_weight = 0.0f;
memset(frodockInput.ele, 0, NAMESIZE * sizeof(char));
frodockInput.ele_weight = 0.0f;
memset(frodockInput.desol_rec, 0, NAMESIZE * sizeof(char));
memset(frodockInput.desol_lig, 0, NAMESIZE * sizeof(char));
memset(frodockInput.asa_rec, 0, NAMESIZE * sizeof(char));
memset(frodockInput.asa_lig, 0, NAMESIZE * sizeof(char));
frodockInput.desol_weight = 0.0f;
frodockInput.num_pot = 0;
frodockInput.potentials = 0;
frodockInput.bw = 0;
frodockInput.lmax = 0.0f;
frodockInput.lmin = 0.0f;
frodockInput.th = 0.0f;
frodockInput.lw = 0.0f;
frodockInput.st = 0.0f;
frodockInput.np = 0;
frodockInput.rd = 0.0f;
frodockInput.nt = 0;
frodockInput.td = 0.0f;
frodockInput.use_around = false;
memset(frodockInput.around_point, 0, 3 * sizeof(float));
memset(frodockInput.points, 0, NAMESIZE * sizeof(char));
frodockInput.conv = Rosseta;
// try to start up socket
try {
vislib::net::Socket::Startup();
} catch (vislib::net::SocketException e) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(
megamol::core::utility::log::Log::LEVEL_ERROR, "Socket Exception during startup: %s", e.GetMsgA());
}
return true;
}
/*
* FrodockLoader::getData
*/
bool FrodockLoader::getData(core::Call& call) {
using megamol::core::utility::log::Log;
megamol::protein_calls::MolecularDataCall* dc = dynamic_cast<megamol::protein_calls::MolecularDataCall*>(&call);
if (dc == NULL)
return false;
// try to load the input file
if (this->filenameSlot.IsDirty()) {
this->filenameSlot.ResetDirty();
this->loadFile(this->filenameSlot.Param<core::param::FilePathParam>()->Value().generic_u8string().c_str());
}
// variables for parameter transfer
vislib::StringA paramSlotName;
param::ParamSlot* paramSlot;
//////////////////////////////////////////////////////////////////
// get pointer to receptor MolecularDataCall
//////////////////////////////////////////////////////////////////
megamol::protein_calls::MolecularDataCall* receptor =
this->receptorDataCallerSlot.CallAs<megamol::protein_calls::MolecularDataCall>();
vislib::StringA receptorFilename(frodockInput.receptor);
#ifdef WIN32
// convert linux path for windows, if fileServerName is set
if (!fileServerNameSlot.Param<param::StringParam>()->Value().empty()) {
if (receptorFilename.StartsWith('/')) {
receptorFilename.Replace('/', '\\');
}
receptorFilename.Prepend(fileServerNameSlot.Param<param::StringParam>()->Value().c_str());
receptorFilename.Prepend("\\\\");
}
#endif
// set parameter slots of the receptor
if (receptor && frodockInput.receptor[0] != 0) {
paramSlotName = "";
paramSlot = 0;
// get and set filename param
paramSlotName = receptor->PeekCalleeSlot()->Parent()->FullName();
paramSlotName += "::filename";
paramSlot = dynamic_cast<param::ParamSlot*>(this->FindNamedObject(paramSlotName, true).get());
if (paramSlot) {
paramSlot->Param<param::FilePathParam>()->SetValue(receptorFilename.PeekBuffer());
}
// get and set stride param
paramSlotName = receptor->PeekCalleeSlot()->Parent()->FullName();
paramSlotName += "::strideFlag";
paramSlot = dynamic_cast<param::ParamSlot*>(this->FindNamedObject(paramSlotName, true).get());
if (paramSlot) {
paramSlot->Param<param::BoolParam>()->SetValue(this->strideFlagSlot.Param<param::BoolParam>()->Value());
}
// all parameters set, execute the data call
if (!(*receptor)(megamol::protein_calls::MolecularDataCall::CallForGetData))
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Could not load receptor file."); // DEBUG
//else
// Log::DefaultLog.WriteMsg( Log::LEVEL_INFO, "Successfully load receptor file."); // DEBUG
}
//////////////////////////////////////////////////////////////////
// get pointer to ligand MolecularDataCall
//////////////////////////////////////////////////////////////////
megamol::protein_calls::MolecularDataCall* ligand =
this->ligandDataCallerSlot.CallAs<megamol::protein_calls::MolecularDataCall>();
vislib::StringA ligandFilename(frodockInput.ligand);
#ifdef WIN32
// convert linux path for windows, if fileServerName is set
if (!fileServerNameSlot.Param<param::StringParam>()->Value().empty()) {
if (ligandFilename.StartsWith('/')) {
ligandFilename.Replace('/', '\\');
}
ligandFilename.Prepend(fileServerNameSlot.Param<param::StringParam>()->Value().c_str());
ligandFilename.Prepend("\\\\");
}
#endif
// set parameter slots of the ligand
if (ligand && frodockInput.ligand[0] != 0) {
paramSlotName = "";
paramSlot = 0;
// get and set filename param
paramSlotName = ligand->PeekCalleeSlot()->Parent()->FullName();
paramSlotName += "::filename";
paramSlot = dynamic_cast<param::ParamSlot*>(this->FindNamedObject(paramSlotName, true).get());
if (paramSlot) {
paramSlot->Param<param::FilePathParam>()->SetValue(ligandFilename.PeekBuffer());
}
// get and set stride param
paramSlotName = ligand->PeekCalleeSlot()->Parent()->FullName();
paramSlotName += "::strideFlag";
paramSlot = dynamic_cast<param::ParamSlot*>(this->FindNamedObject(paramSlotName, true).get());
if (paramSlot) {
paramSlot->Param<param::BoolParam>()->SetValue(this->strideFlagSlot.Param<param::BoolParam>()->Value());
}
// all parameters set, execute the data call
if (!(*ligand)(megamol::protein_calls::MolecularDataCall::CallForGetData))
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Could not load ligand file."); // DEBUG
//else
// Log::DefaultLog.WriteMsg( Log::LEVEL_INFO, "Successfully load ligand file."); // DEBUG
}
//if ( dc->FrameID() >= this->data.Count() ) return false;
dc->SetDataHash(this->datahash);
// TODO: assign the data from the loader to the call
if (!(*ligand)(MolecularDataCall::CallForGetData))
return false;
unsigned int currentSolution = 0;
// DEBUG ...
/*
this->ligandCenter[0] = 30.709869f;
this->ligandCenter[1] =-12.022730f;
this->ligandCenter[2] =-11.278584f;
this->numSolutions = 3;
this->solutions.AssertSize( sizeof(float)*this->numSolutions*7);
this->solutions.As<float>()[0] = 177.187607f;
this->solutions.As<float>()[1] = 33.763191f;
this->solutions.As<float>()[2] = 292.083557f;
this->solutions.As<float>()[3] = 32.628811f;
this->solutions.As<float>()[4] =-40.611145f;
this->solutions.As<float>()[5] =-25.521893f;
this->solutions.As<float>()[6] = 423.018768f;
this->solutions.As<float>()[7] = 186.82f;
this->solutions.As<float>()[8] = 46.25f;
this->solutions.As<float>()[9] = 356.14f;
this->solutions.As<float>()[10] = 32.628811f;
this->solutions.As<float>()[11] =-40.611145f;
this->solutions.As<float>()[12] =-25.521893f;
this->solutions.As<float>()[13] = 403.394592f;
this->solutions.As<float>()[14] = 318.10f;
this->solutions.As<float>()[15] = 133.80f;
this->solutions.As<float>()[16] = 95.74f;
this->solutions.As<float>()[17] = 36.63f;
this->solutions.As<float>()[18] =-22.61f;
this->solutions.As<float>()[19] =-21.52f;
this->solutions.As<float>()[20] = 620.939026f;
*/
// ...DEBUG
// apply the solution and set values to data call
if (this->applySolution(ligand, dc->FrameID())) {
dc->SetAtoms(ligand->AtomCount(), ligand->AtomTypeCount(), ligand->AtomTypeIndices(),
this->atomPos.PeekElements(), ligand->AtomTypes(), ligand->AtomResidueIndices(), ligand->AtomBFactors(),
ligand->AtomCharges(), ligand->AtomOccupancies());
} else {
dc->SetAtoms(ligand->AtomCount(), ligand->AtomTypeCount(), ligand->AtomTypeIndices(), ligand->AtomPositions(),
ligand->AtomTypes(), ligand->AtomResidueIndices(), ligand->AtomBFactors(), ligand->AtomCharges(),
ligand->AtomOccupancies());
}
dc->SetBFactorRange(ligand->MaximumBFactor(), ligand->MinimumBFactor());
dc->SetChargeRange(ligand->MaximumCharge(), ligand->MinimumCharge());
dc->SetOccupancyRange(ligand->MaximumOccupancy(), ligand->MinimumOccupancy());
dc->SetConnections(ligand->ConnectionCount(), (unsigned int*)ligand->Connection());
dc->SetResidues(ligand->ResidueCount(), ligand->Residues());
dc->SetResidueTypeNames(ligand->ResidueTypeNameCount(), ligand->ResidueTypeNames());
dc->SetMolecules(ligand->MoleculeCount(), (MolecularDataCall::Molecule*)ligand->Molecules());
dc->SetChains(ligand->ChainCount(), (MolecularDataCall::Chain*)ligand->Chains());
/*
if( !this->secStructAvailable && this->strideFlagSlot.Param<param::BoolParam>()->Value() ) {
time_t t = clock(); // DEBUG
if( this->stride ) delete this->stride;
this->stride = new Stride( dc);
this->stride->WriteToInterface( dc);
this->secStructAvailable = true;
Log::DefaultLog.WriteMsg( Log::LEVEL_INFO, "Secondary Structure computed via STRIDE in %f seconds.", ( double( clock() - t) / double( CLOCKS_PER_SEC))); // DEBUG
}
*/
dc->SetUnlocker(NULL);
return true;
}
/*
* FrodockLoader::getExtent
*/
bool FrodockLoader::getExtent(core::Call& call) {
MolecularDataCall* dc = dynamic_cast<MolecularDataCall*>(&call);
if (dc == NULL)
return false;
if (this->filenameSlot.IsDirty()) {
this->filenameSlot.ResetDirty();
this->loadFile(this->filenameSlot.Param<core::param::FilePathParam>()->Value().generic_u8string().c_str());
}
// get pointer to ligand MolecularDataCall
MolecularDataCall* ligand = this->ligandDataCallerSlot.CallAs<MolecularDataCall>();
if (ligand) {
this->applySolution(ligand, this->currentSolution);
// get extends of ligand
if (!(*ligand)(MolecularDataCall::CallForGetExtent))
return false;
dc->AccessBoundingBoxes().Clear();
dc->AccessBoundingBoxes() = ligand->AccessBoundingBoxes();
dc->AccessBoundingBoxes().SetObjectSpaceClipBox(this->bbox);
}
// set frame count
dc->SetFrameCount(vislib::math::Max(1U, (unsigned int)(this->numSolutions)));
dc->SetDataHash(this->datahash);
return true;
}
/*
* FrodockLoader::release
*/
void FrodockLoader::release(void) {
try {
vislib::net::Socket::Cleanup();
} catch (vislib::net::SocketException e) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(
megamol::core::utility::log::Log::LEVEL_ERROR, "Socket Exception during cleanup: %s", e.GetMsgA());
}
}
/*
* FrodockLoader::loadFile
*/
void FrodockLoader::loadFile(const vislib::TString& filename) {
using megamol::core::utility::log::Log;
// counter variable
int cnt;
this->datahash++;
int around;
FILE* f = fopen(T2A(filename), "rt");
fscanf(f, "%*[^\n]\n"); //#FRODOCK CONFIGURATION INPUT FILE
fscanf(f, "%*[^\n]\n"); //#PDB FILES. MANDATORY
fscanf(f, "%*[^\n]\n"); //#Receptor (Mandatory)
fscanf(f, "%[^\n]\n", frodockInput.receptor); //receptor.pdb
fscanf(f, "%*[^\n]\n"); //#Ligand (Mandatory)
fscanf(f, "%[^\n]\n", frodockInput.ligand); //ligand.pdb
fscanf(f, "%*[^\n]\n"); //#MAIN POTENTIALS. OPTIONALS
fscanf(f, "%*[^\n]\n"); //#Van der Waals potential
fscanf(f, "%[^\n]\n", frodockInput.vdw); //vdw.ccp4
if (strcmp(frodockInput.vdw, "#") == 0)
strcpy(frodockInput.vdw, "");
fscanf(f, "%*[^\n]\n"); //#Van der Waals weight (default 1.0)
fscanf(f, "%f\n", &(frodockInput.vdw_weight)); //1.0
fscanf(f, "%*[^\n]\n"); //#Electrostatic potential
fscanf(f, "%[^\n]\n", frodockInput.ele); //ele.ccp4
if (strcmp(frodockInput.ele, "#") == 0)
strcpy(frodockInput.ele, "");
fscanf(f, "%*[^\n]\n"); //#Electrostatic weight (default 0.0)
fscanf(f, "%f\n", &(frodockInput.ele_weight)); //0.0;
fscanf(f, "%*[^\n]\n"); //#Receptor desolvation potential
fscanf(f, "%[^\n]\n", frodockInput.desol_rec); //desol_rec.ccp4
if (strcmp(frodockInput.desol_rec, "#") == 0)
strcpy(frodockInput.desol_rec, "");
fscanf(f, "%*[^\n]\n"); //#Ligand desolvation potential
fscanf(f, "%[^\n]\n", frodockInput.desol_lig); //desol_lig.ccp4
if (strcmp(frodockInput.desol_lig, "#") == 0)
strcpy(frodockInput.desol_lig, "");
fscanf(f, "%*[^\n]\n"); //#Receptor Accesibility map
fscanf(f, "%[^\n]\n", frodockInput.asa_rec); //asa_rec.ccp4
if (strcmp(frodockInput.asa_rec, "#") == 0)
strcpy(frodockInput.asa_rec, "");
fscanf(f, "%*[^\n]\n"); //#Ligand Accesibility map
fscanf(f, "%[^\n]\n", frodockInput.asa_lig); //asa_lig.ccp4
if (strcmp(frodockInput.asa_lig, "#") == 0)
strcpy(frodockInput.asa_lig, "");
fscanf(f, "%*[^\n]\n"); //#Desolvation weight (default 0.0)
fscanf(f, "%f\n", &(frodockInput.desol_weight));
fscanf(f, "%*[^\n]\n"); //#EXTRA POTENTIALS. OPTIONALS
fscanf(f, "%*[^\n]\n"); //#Number of extra potentials (default 0)
fscanf(f, "%d\n", &(frodockInput.num_pot));
fscanf(f, "%*[^\n]\n"); //#Extra potrential name, weigh and type
// delete potentials if necessary
if (this->frodockInput.potentials)
delete[] this->frodockInput.potentials;
// create new potential array
//frodockInput.potentials = (Potential_FI*)malloc( sizeof( Potential_FI)*frodockInput.num_pot);
this->frodockInput.potentials = new Potential_FI[frodockInput.num_pot];
for (int i = 0; i < frodockInput.num_pot; ++i) {
fscanf(f, "%[^\n]\n", frodockInput.potentials[i].name);
fscanf(f, "%f\n", &(frodockInput.potentials[i].weight));
fscanf(f, "%d\n", &(frodockInput.potentials[i].type));
}
fscanf(f, "%*[^\n]\n"); //#SEARCH PARAMETERS
fscanf(f,
"%*[^\n]\n"); //#Bandwitdh in spherical harmonic representation. Define rotational stepsize (default: 32. Rotational stepsize ~11º)
fscanf(f, "%d\n", &(frodockInput.bw));
fscanf(f, "%*[^\n]\n"); //#External Mask reduction ratio (default: 0.25).
fscanf(f, "%f\n", &(frodockInput.lmax));
fscanf(f, "%*[^\n]\n"); //#Internal Mask reduction ratio (default: 0.26).
fscanf(f, "%f\n", &(frodockInput.lmin));
fscanf(f, "%*[^\n]\n"); //#Electrostatic map threshold (default: 10.0)
fscanf(f, "%f\n", &(frodockInput.th));
fscanf(f, "%*[^\n]\n"); //#Width between spherical layers in amstrongs (default: 1.0).
fscanf(f, "%f\n", &(frodockInput.lw));
fscanf(f, "%*[^\n]\n"); //#Translational search stepsize in amstrongs (default: 2.0).
fscanf(f, "%f\n", &(frodockInput.st));
fscanf(f, "%*[^\n]\n"); //#Number of solutions stored per traslational position. (default: 4)
fscanf(f, "%d\n", &(frodockInput.np));
fscanf(f, "%*[^\n]\n"); //#Minimal rotational distance allowed between close solutions in degrees (default: 12.0)
fscanf(f, "%f\n", &(frodockInput.rd));
fscanf(f, "%*[^\n]\n"); //#Number of solutions stored in the search (default: unlimited -1).
fscanf(f, "%d\n", &(frodockInput.nt));
fscanf(f, "%*[^\n]\n"); //#Maximal translational distance to consider close solutions in grid units. (default: 0)
fscanf(f, "%f\n", &(frodockInput.td));
fscanf(f, "%*[^\n]\n"); //#Limit the translational search to a region (default: false(0))
fscanf(f, "%d\n", &(around));
if (around == 0)
frodockInput.use_around = false;
else
frodockInput.use_around = true;
fscanf(f, "%*[^\n]\n"); //#Coordinates XYZ of the central point of the region
fscanf(f, "%f\n", &(frodockInput.around_point[0])); //#Coordinates XYZ of the central point of the region
fscanf(f, "%f\n", &(frodockInput.around_point[1])); //#Coordinates XYZ of the central point of the region
fscanf(f, "%f\n", &(frodockInput.around_point[2])); //#Coordinates XYZ of the central point of the region
strcpy(frodockInput.points, "");
frodockInput.conv = Rosseta;
fclose(f);
// reset data
this->numSolutions = 0;
// Communication with frodock
try {
// create socket
this->socket.Create(
vislib::net::Socket::FAMILY_INET, vislib::net::Socket::TYPE_STREAM, vislib::net::Socket::PROTOCOL_TCP);
} catch (vislib::net::SocketException e) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Socket Exception during create: %s", e.GetMsgA());
}
try {
// connect to frodock
this->socket.Connect(
vislib::net::IPEndPoint::CreateIPv4(T2A(this->hostAddressSlot.Param<param::StringParam>()->Value().c_str()),
this->portSlot.Param<param::IntParam>()->Value()));
// send input data
this->socket.Send(&(frodockInput), sizeof(FrodockInput), vislib::net::Socket::TIMEOUT_INFINITE, 0, true);
// send extra potentials
if (frodockInput.num_pot > 0) {
for (int i = 0; i < frodockInput.num_pot; ++i) {
if (this->socket.Send(&(frodockInput.potentials[i]), sizeof(Potential_FI),
vislib::net::Socket::TIMEOUT_INFINITE, 0, true) <= 0) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Sending extra potential %i over the socket failed.", i);
return;
}
}
}
// store current time
time_t t = clock();
// receive return value
this->frodockResult = 0;
this->socket.Receive(&this->frodockResult, sizeof(int), vislib::net::Socket::TIMEOUT_INFINITE, 0, true);
Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Received return value after %f seconds.",
(double(clock() - t) / double(CLOCKS_PER_SEC))); // DEBUG
if (this->frodockResult < 0) {
// --- received error value (0 or -1) ---
if (this->frodockResult == 0) {
Log::DefaultLog.WriteMsg(
Log::LEVEL_ERROR, "Execution of Frodock not successful, try to get error message...");
char buffer[NAMESIZE];
this->socket.Receive(buffer, sizeof(char) * NAMESIZE, vislib::net::Socket::TIMEOUT_INFINITE, 0, true);
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Input error comunicated: %s.", buffer);
} else {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR,
"CATASTROPHIC ERROR: Frodock Server has collapsed. Restart the server and check input data.");
}
} else {
// --- received success value ---
Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Successful Execution of Frodock reported.");
// get ligand center
this->socket.Receive(this->ligandCenter, sizeof(float) * 3, vislib::net::Socket::TIMEOUT_INFINITE, 0, true);
Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Ligand center: %f, %f, %f.", this->ligandCenter[0],
this->ligandCenter[1], this->ligandCenter[2]);
// get the number of solutions
this->socket.Receive(&this->numSolutions, sizeof(int), vislib::net::Socket::TIMEOUT_INFINITE, 0, true);
Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Number of solutions: %i.", this->numSolutions);
// get the solutions
if (this->numSolutions > 0) {
this->solutions.AssertSize(sizeof(float) * this->numSolutions * 7);
for (cnt = 0; cnt < this->numSolutions; ++cnt) {
this->socket.Receive(this->solutions.AsAt<float>(sizeof(float) * cnt * 7), sizeof(float) * 7,
vislib::net::Socket::TIMEOUT_INFINITE, 0, true);
}
}
}
} catch (vislib::net::SocketException e) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Socket Exception during connect/send: %s", e.GetMsgA());
}
}
/*
* applies a solution (computes new atom positions)
*/
bool FrodockLoader::applySolution(const MolecularDataCall* ligand, unsigned int solIdx) {
// check if the ligand pointer is null
if (!ligand)
return false;
// check if the requested solution is already applied
if (this->currentSolution == solIdx)
return true;
// check if the requested solution is out of bounds
if (int(solIdx) < 0 || int(solIdx) >= this->numSolutions)
return false;
// transform atom positions
vislib::math::Vector<float, 3> pos;
const vislib::math::Vector<float, 3> center(this->ligandCenter);
const vislib::math::Vector<float, 3> translation(&this->solutions.As<float>()[solIdx * 7 + 3]);
this->atomPos.SetCount(ligand->AtomCount() * 3);
float psi = this->solutions.As<float>()[solIdx * 7 + 0];
float theta = this->solutions.As<float>()[solIdx * 7 + 1];
float phi = this->solutions.As<float>()[solIdx * 7 + 2];
phi *= float(vislib::math::PI_DOUBLE / 180.0);
theta *= float(vislib::math::PI_DOUBLE / 180.0);
psi *= float(vislib::math::PI_DOUBLE / 180.0);
/*
// wikipedia - Benutzer:Garufalo/Spielwiese
vislib::math::Matrix<float, 3, vislib::math::ROW_MAJOR> rotMat(
cos( phi) * cos( psi) - cos( theta) * sin( phi) * sin( psi),
-cos( psi) * sin( phi) - cos( theta) * cos( phi) * sin( psi),
sin( theta) * sin( psi),
//------------------------------------------
cos( theta) * cos( psi) * sin( phi) + cos( phi) * sin( psi),
cos( theta) * cos( phi) * cos( psi) - sin( phi) * sin( psi),
-cos( psi) * sin( theta),
//------------------------------------------
sin( theta) * sin( phi),
cos( phi) * sin( theta),
cos( theta)
);
*/
/*
vislib::math::Matrix<float, 3, vislib::math::ROW_MAJOR> rotMatZ3(
cos( psi),
-sin( psi),
0.0f,
//------------------------------------------
sin( psi),
cos( psi),
0.0f,
//------------------------------------------
0.0f,
0.0f,
1.0f
);
vislib::math::Matrix<float, 3, vislib::math::ROW_MAJOR> rotMatX2(
1.0f,
0.0f,
0.0f,
//------------------------------------------
0.0f,
cos( theta),
-sin( theta),
//------------------------------------------
0.0f,
sin( theta),
cos( theta)
);
vislib::math::Matrix<float, 3, vislib::math::ROW_MAJOR> rotMatY2(
cos( theta),
0.0f,
sin( theta),
//------------------------------------------
0.0f,
1.0f,
0.0f,
//------------------------------------------
-sin( theta),
0.0f,
cos( theta)
);
vislib::math::Matrix<float, 3, vislib::math::ROW_MAJOR> rotMatZ1(
cos( phi),
-sin( phi),
0.0f,
//------------------------------------------
sin( phi),
cos( phi),
0.0f,
//------------------------------------------
0.0f,
0.0f,
1.0f
);
vislib::math::Matrix<float, 3, vislib::math::ROW_MAJOR> rotMat = rotMatZ3 * rotMatX2 * rotMatZ1;
*/
/*
// matheboard
vislib::math::Matrix<float, 3, vislib::math::ROW_MAJOR> rotMat(
cos( psi) * cos( phi) - cos( theta) * sin( phi) * sin( psi),
-sin( psi) * cos( phi) - cos( theta) * sin( phi) * cos( psi),
sin( theta) * sin( phi),
//------------------------------------------
cos( psi) * sin( phi) + cos( theta) * cos( phi) * sin( psi),
-sin( psi) * sin( phi) + cos( theta) * cos( phi) * cos( psi) ,
-sin( theta) * cos( phi),
//------------------------------------------
sin( psi) * sin( theta),
cos( psi) * sin( theta),
cos( theta)
);
*/
// Nacho
vislib::math::Matrix<float, 3, vislib::math::ROW_MAJOR> rotMat(
cos(psi) * cos(phi) - cos(theta) * sin(phi) * sin(psi), cos(psi) * sin(phi) + cos(theta) * cos(phi) * sin(psi),
sin(psi) * sin(theta), -sin(psi) * cos(phi) - cos(theta) * sin(phi) * cos(psi),
-sin(psi) * sin(phi) + cos(theta) * cos(phi) * cos(psi), cos(psi) * sin(theta), sin(theta) * sin(phi),
-sin(theta) * cos(phi), cos(theta));
#pragma omp parallel for private(pos)
for (int cnt = 0; cnt < int(ligand->AtomCount()); ++cnt) {
pos.Set(ligand->AtomPositions()[3 * cnt], ligand->AtomPositions()[3 * cnt + 1],
ligand->AtomPositions()[3 * cnt + 2]);
//pos -= center;
pos = pos - center;
pos = rotMat * pos;
pos += translation;
this->atomPos[3 * cnt] = pos.X();
this->atomPos[3 * cnt + 1] = pos.Y();
this->atomPos[3 * cnt + 2] = pos.Z();
}
// reset bbox
this->bbox.Set(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
for (int cnt = 0; cnt < int(ligand->AtomCount()); ++cnt) {
this->bbox.GrowToPoint(this->atomPos[3 * cnt], this->atomPos[3 * cnt + 1], this->atomPos[3 * cnt + 2]);
}
this->currentSolution = solIdx;
// successfully applied the solution
return true;
}
| 42.675325 | 169 | 0.592818 | [
"vector",
"transform"
] |
ff2f727247a4fbe57adc94f55d6bba7bce8fda3f | 5,610 | hpp | C++ | src/planning/object_collision_estimator_nodes/include/object_collision_estimator_nodes/object_collision_estimator_node.hpp | ruvus/auto | 25ae62d6e575cae40212356eed43ec3e76e9a13e | [
"Apache-2.0"
] | 1 | 2022-02-24T07:36:59.000Z | 2022-02-24T07:36:59.000Z | src/planning/object_collision_estimator_nodes/include/object_collision_estimator_nodes/object_collision_estimator_node.hpp | ruvus/auto | 25ae62d6e575cae40212356eed43ec3e76e9a13e | [
"Apache-2.0"
] | null | null | null | src/planning/object_collision_estimator_nodes/include/object_collision_estimator_nodes/object_collision_estimator_node.hpp | ruvus/auto | 25ae62d6e575cae40212356eed43ec3e76e9a13e | [
"Apache-2.0"
] | 1 | 2021-12-09T15:44:10.000Z | 2021-12-09T15:44:10.000Z | // Copyright 2020-2021 Arm Limited
//
// 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 <autoware_auto_planning_msgs/srv/modify_trajectory.hpp>
#include <autoware_auto_perception_msgs/msg/bounding_box_array.hpp>
#include <visualization_msgs/msg/marker_array.hpp>
#include <visualization_msgs/msg/marker.hpp>
#include <tf2_ros/transform_listener.h>
#include <tf2_ros/buffer.h>
#include <rclcpp/rclcpp.hpp>
#include <memory>
#include <string>
#include "object_collision_estimator/object_collision_estimator.hpp"
#include "object_collision_estimator_nodes/visibility_control.hpp"
#ifndef OBJECT_COLLISION_ESTIMATOR_NODES__OBJECT_COLLISION_ESTIMATOR_NODE_HPP_
#define OBJECT_COLLISION_ESTIMATOR_NODES__OBJECT_COLLISION_ESTIMATOR_NODE_HPP_
namespace motion
{
namespace planning
{
namespace object_collision_estimator_nodes
{
using motion::planning::object_collision_estimator::ObjectCollisionEstimator;
using autoware_auto_perception_msgs::msg::BoundingBoxArray;
using visualization_msgs::msg::MarkerArray;
using visualization_msgs::msg::Marker;
/// \brief ROS2 interface to Object Collision Estimator Library. It has 2 main interfaces:
/// 1. Subscribe to a topic to obtain obstacle bounding boxes from perception stack.
/// 2. Present as a service to other nodes. This service takes a trajectory as an input and
/// outputs a modified trajectory avoiding collisions.
class OBJECT_COLLISION_ESTIMATOR_NODES_PUBLIC ObjectCollisionEstimatorNode : public rclcpp::Node
{
public:
/// \brief Construct a new Object Collision Estimator Node object
/// \param[in] node_options Node options for this node.
explicit ObjectCollisionEstimatorNode(const rclcpp::NodeOptions & node_options);
private:
/// \brief Callback function for the service interface
/// \param[in] request The input to the service. Contains the planned trajectory from the
/// behaviour planner.
/// \param[out] response The output of the service. Contains the trajectory modified by the
/// collision estimator to avoid any collisions.
void estimate_collision(
const std::shared_ptr<autoware_auto_planning_msgs::srv::ModifyTrajectory::Request> request,
std::shared_ptr<autoware_auto_planning_msgs::srv::ModifyTrajectory::Response> response);
/// \brief Pointer to the subscriber listening for a list of obstacles
rclcpp::Subscription<BoundingBoxArray>::SharedPtr m_obstacles_sub{nullptr};
/// \brief Pointer to the publisher for bounding boxes of the target trajectory
rclcpp::Publisher<MarkerArray>::SharedPtr m_trajectory_bbox_pub{nullptr};
/// \brief Helper function to handle modified bounding boxes when updating the obstacles.
/// \param[in] bbox_array An array of bounding boxes representing a list of obstacles
void update_obstacles(const BoundingBoxArray & bbox_array);
/// \brief Callback function for the obstacles topic
/// \param[in] msg ROS2 message from the obstacle topic containing an array of bounding boxes
/// representing obstacles found by the perception pipeline.
void on_bounding_box(const BoundingBoxArray::SharedPtr & msg);
/// \brief Pointer to an instance of object collision estimator. It performs the main task of
/// estimating collisions and modifying the trajectory.
std::unique_ptr<ObjectCollisionEstimator> m_estimator{nullptr};
/// \brief The frame id of the map frame. Trajectories are assumed in this frame. Obstacles are
/// transformed into this frame before storing. Configured through the `target_frame` node
/// parameter.
std::string m_target_frame_id{};
/// \brief Pointer to the service interface of the service that estimates collisions.
rclcpp::Service<autoware_auto_planning_msgs::srv::ModifyTrajectory>::SharedPtr
m_service_interface{nullptr};
/// \brief Pointer to the tf interface used to transform obstacle bounding box coordinates.
std::shared_ptr<tf2_ros::Buffer> m_tf_buffer;
/// \brief Pointer to the tf listener which listens for transforms published in the system and
/// stores them in the node for use.
std::shared_ptr<tf2_ros::TransformListener> m_tf_listener;
/// \brief Pointer to the wall timer used to periodically check if transforms have become
/// available.
rclcpp::TimerBase::SharedPtr m_wall_timer{nullptr};
/// \brief The time stamp of the last obstacle message received by the node
rclcpp::Time m_last_obstacle_msg_time {0, 0, RCL_ROS_TIME};
/// \brief The staleness threshold for objects in milliseconds
std::chrono::milliseconds m_staleness_threshold_ms{};
/// \brief Hard coded node name
static constexpr const char * OBJECT_COLLISION_ESTIMATOR_NODE_NAME =
"object_collision_estimator_node";
/// \brief Hard coded topic name on which obstacle bounding boxes are received.
static constexpr const char * OBSTACLE_TOPIC = "obstacle_topic";
};
} // namespace object_collision_estimator_nodes
} // namespace planning
} // namespace motion
#endif // OBJECT_COLLISION_ESTIMATOR_NODES__OBJECT_COLLISION_ESTIMATOR_NODE_HPP_
| 45.609756 | 99 | 0.772193 | [
"object",
"transform"
] |
ff342f6dc3ca022e6cda3233418ac5869f3fc46e | 91,028 | cpp | C++ | Cpp-C/Ema/Examples/Test/UnitTest/VectorTests.cpp | TransFICC/Elektron-SDK | 4323249c24c8105e41fd8cd9ba5dd9661e1b2b0e | [
"Apache-2.0"
] | null | null | null | Cpp-C/Ema/Examples/Test/UnitTest/VectorTests.cpp | TransFICC/Elektron-SDK | 4323249c24c8105e41fd8cd9ba5dd9661e1b2b0e | [
"Apache-2.0"
] | null | null | null | Cpp-C/Ema/Examples/Test/UnitTest/VectorTests.cpp | TransFICC/Elektron-SDK | 4323249c24c8105e41fd8cd9ba5dd9661e1b2b0e | [
"Apache-2.0"
] | null | null | null | /*|-----------------------------------------------------------------------------
*| This source code is provided under the Apache 2.0 license --
*| and is provided AS IS with no warranty or guarantee of fit for purpose. --
*| See the project's LICENSE.md for details. --
*| Copyright Thomson Reuters 2018. All rights reserved. --
*|-----------------------------------------------------------------------------
*/
#include "Access/Impl/StaticDecoder.h"
#include "TestUtilities.h"
using namespace thomsonreuters::ema::access;
using namespace std;
TEST(VectorTests, testVectorContainsFieldListsDecodeAll)
{
// load dictionary for decoding of the field list
RsslDataDictionary dictionary;
ASSERT_TRUE(loadDictionaryFromFile( &dictionary )) << "Failed to load dictionary";
try
{
// encoding order: SummaryData(with FieldList), Delete, FieldList-Set, FieldList-Set, FieldList-Update
RsslBuffer vectorBuffer;
vectorBuffer.length = 4096;
vectorBuffer.data = ( char* )malloc( sizeof( char ) * 4096 );
RsslVector rsslVector = RSSL_INIT_VECTOR;
RsslEncodeIterator vectorEncodeIter;
rsslClearVector( &rsslVector );
rsslClearEncodeIterator( &vectorEncodeIter );
rsslSetEncodeIteratorRWFVersion( &vectorEncodeIter, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION );
rsslSetEncodeIteratorBuffer( &vectorEncodeIter, &vectorBuffer );
rsslVector.flags = RSSL_VTF_HAS_SUMMARY_DATA | RSSL_VTF_HAS_TOTAL_COUNT_HINT;
rsslVector.containerType = RSSL_DT_FIELD_LIST;
rsslVector.totalCountHint = 5;
// allocate buffer for the field list for SummaryData
RsslBuffer rsslBuf;
rsslBuf.length = 1000;
rsslBuf.data = ( char* )malloc( sizeof( char ) * 1000 );
RsslEncodeFieldListAll( rsslBuf );
rsslVector.encSummaryData = rsslBuf;
rsslEncodeVectorInit( &vectorEncodeIter, &rsslVector, 0, 0 );
RsslVectorEntry vectorEntry;
//first entry //Delete
rsslClearVectorEntry( &vectorEntry );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_DELETE_ENTRY;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
//second entry //Set FieldList
rsslClearVectorEntry( &vectorEntry );
// allocate buffer for the field list for VectorEntries
RsslBuffer rsslBuf1;
rsslBuf1.length = 1000;
rsslBuf1.data = ( char* )malloc( sizeof( char ) * 1000 );
RsslEncodeFieldListAll( rsslBuf1 );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_SET_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
//third entry //Set FieldList
rsslClearVectorEntry( &vectorEntry );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_SET_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
//fourth entry //Update FieldList
rsslClearVectorEntry( &vectorEntry );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_UPDATE_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
vectorBuffer.length = rsslGetEncodedBufferLength( &vectorEncodeIter );
rsslEncodeVectorComplete( &vectorEncodeIter, RSSL_TRUE );
//Now do EMA decoding of Vector
Vector vector;
StaticDecoder::setRsslData( &vector, &vectorBuffer, RSSL_DT_VECTOR, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION, &dictionary );
EXPECT_TRUE( vector.hasTotalCountHint() ) << "Vector contains FieldList - hasTotalCountHint()" ;
EXPECT_EQ( vector.getTotalCountHint(), 5 ) << "Vector contains FieldList - getTotalCountHint()" ;
switch ( vector.getSummaryData().getDataType() )
{
case DataType::FieldListEnum :
{
const FieldList& fl = vector.getSummaryData().getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
break;
default :
EXPECT_FALSE( true ) << "Vector Decode Summary FieldList - vector.getSummaryType() not expected" ;
break;
}
EXPECT_TRUE( vector.forth() ) << "Vector contains FieldList - first vector forth()" ;
const VectorEntry& ve1 = vector.getEntry();
EXPECT_EQ( ve1.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve1.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
vector.reset();
{
EXPECT_TRUE( vector.forth() ) << "Vector contains FieldList - vector forth() after reset()" ;
const VectorEntry& ve = vector.getEntry();
EXPECT_EQ( ve.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
}
EXPECT_TRUE( vector.forth() ) << "Vector contains FieldList - second vector forth()" ;
const VectorEntry& ve2 = vector.getEntry();
EXPECT_EQ( ve2.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve2.getLoad().getDataType(), DataType::FieldListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = ve2.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( vector.forth() ) << "Vector contains FieldList - third vector forth()" ;
const VectorEntry& ve3 = vector.getEntry();
EXPECT_EQ( ve3.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve3.getLoad().getDataType(), DataType::FieldListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
{
const FieldList& fl = ve3.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( vector.forth() ) << "Vector contains FieldList - fourth vector forth()" ;
const VectorEntry& ve4 = vector.getEntry();
EXPECT_EQ( ve4.getAction(), VectorEntry::UpdateEnum ) << "VectorEntry::getAction() == VectorEntry::UpdateEnum" ;
EXPECT_EQ( ve4.getLoad().getDataType(), DataType::FieldListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
EXPECT_FALSE( vector.forth() ) << "Vector contains FieldList - final vector forth()" ;
free( rsslBuf.data );
free( vectorBuffer.data );
EXPECT_TRUE( true ) << "Vector contains FieldList - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector contains FieldList - exception not expectedd" ;
}
rsslDeleteDataDictionary( &dictionary );
}
TEST(VectorTests, testVectorContainsElementListsDecodeAll)
{
try
{
// encoding order: SummaryData(with ElementList), Delete, ElementList-Set, ElementList-Set, ElementList-Update
RsslBuffer vectorBuffer;
vectorBuffer.length = 4096;
vectorBuffer.data = ( char* )malloc( sizeof( char ) * 4096 );
RsslVector rsslVector = RSSL_INIT_VECTOR;
RsslEncodeIterator vectorEncodeIter;
rsslClearVector( &rsslVector );
rsslClearEncodeIterator( &vectorEncodeIter );
rsslSetEncodeIteratorRWFVersion( &vectorEncodeIter, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION );
rsslSetEncodeIteratorBuffer( &vectorEncodeIter, &vectorBuffer );
rsslVector.flags = RSSL_VTF_HAS_SUMMARY_DATA | RSSL_VTF_HAS_TOTAL_COUNT_HINT;
rsslVector.containerType = RSSL_DT_ELEMENT_LIST;
rsslVector.totalCountHint = 5;
// allocate buffer for the element list for SummaryData
RsslBuffer rsslBuf;
rsslBuf.length = 1000;
rsslBuf.data = ( char* )malloc( sizeof( char ) * 1000 );
RsslEncodeElementListAll( rsslBuf );
rsslVector.encSummaryData = rsslBuf;
rsslEncodeVectorInit( &vectorEncodeIter, &rsslVector, 0, 0 );
RsslVectorEntry vectorEntry;
//first entry //Delete
rsslClearVectorEntry( &vectorEntry );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_DELETE_ENTRY;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
//second entry //Set ElementList
rsslClearVectorEntry( &vectorEntry );
// allocate buffer for the element list for VectorEntries
RsslBuffer rsslBuf1;
rsslBuf1.length = 1000;
rsslBuf1.data = ( char* )malloc( sizeof( char ) * 1000 );
RsslEncodeElementListAll( rsslBuf1 );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_SET_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
//third entry //Set ElementList
rsslClearVectorEntry( &vectorEntry );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_SET_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
//fourth entry //Update ElementList
rsslClearVectorEntry( &vectorEntry );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_UPDATE_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
vectorBuffer.length = rsslGetEncodedBufferLength( &vectorEncodeIter );
rsslEncodeVectorComplete( &vectorEncodeIter, RSSL_TRUE );
//Now do EMA decoding of Vector
Vector vector;
StaticDecoder::setRsslData( &vector, &vectorBuffer, RSSL_DT_VECTOR, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION, 0 );
EXPECT_TRUE( vector.hasTotalCountHint() ) << "Vector contains ElementList - hasTotalCountHint()" ;
EXPECT_EQ( vector.getTotalCountHint(), 5 ) << "Vector contains ElementList - getTotalCountHint()" ;
switch ( vector.getSummaryData().getDataType() )
{
case DataType::ElementListEnum :
{
const ElementList& el = vector.getSummaryData().getElementList();
SCOPED_TRACE("calling EmaDecodeElementListAll");
EmaDecodeElementListAll( el );
}
break;
default :
EXPECT_FALSE( true ) << "Vector Decode Summary FieldList - vector.getSummaryType() not expected" ;
break;
}
EXPECT_TRUE( vector.forth() ) << "Vector contains ElementList - first vector forth()" ;
const VectorEntry& ve1 = vector.getEntry();
EXPECT_EQ( ve1.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve1.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
vector.reset();
{
EXPECT_TRUE( vector.forth() ) << "Vector contains ElementList - vector forth() after reset()" ;
const VectorEntry& ve = vector.getEntry();
EXPECT_EQ( ve.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
}
EXPECT_TRUE( vector.forth() ) << "Vector contains ElementList - second vector forth()" ;
const VectorEntry& ve2 = vector.getEntry();
EXPECT_EQ( ve2.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve2.getLoad().getDataType(), DataType::ElementListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::ElementListEnum" ;
{
const ElementList& el = ve2.getElementList();
SCOPED_TRACE("calling EmaDecodeElementListAll");
EmaDecodeElementListAll( el );
}
EXPECT_TRUE( vector.forth() ) << "Vector contains ElementList - third vector forth()" ;
const VectorEntry& ve3 = vector.getEntry();
EXPECT_EQ( ve3.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve3.getLoad().getDataType(), DataType::ElementListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::ElementListEnum" ;
{
const ElementList& el = ve3.getElementList();
SCOPED_TRACE("calling EmaDecodeElementListAll");
EmaDecodeElementListAll( el );
}
EXPECT_TRUE( vector.forth() ) << "Vector contains ElementList - fourth vector forth()" ;
const VectorEntry& ve4 = vector.getEntry();
EXPECT_EQ( ve4.getAction(), VectorEntry::UpdateEnum ) << "VectorEntry::getAction() == VectorEntry::UpdateEnum" ;
EXPECT_EQ( ve4.getLoad().getDataType(), DataType::ElementListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::ElementListEnum" ;
{
const ElementList& el = ve4.getElementList();
SCOPED_TRACE("calling EmaDecodeElementListAll");
EmaDecodeElementListAll( el );
}
EXPECT_FALSE( vector.forth() ) << "Vector contains ElementList - final vector forth()" ;
free( rsslBuf.data );
free( vectorBuffer.data );
EXPECT_TRUE( true ) << "Vector contains ElementList - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector contains ElementList - exception not expectedd" ;
}
}
TEST(VectorTests, testVectorContainsMapsDecodeAll)
{
// load dictionary for decoding of the field list
RsslDataDictionary dictionary;
ASSERT_TRUE(loadDictionaryFromFile( &dictionary )) << "Failed to load dictionary";
try
{
// encoding order: SummaryData(with Map), Delete, Map-Set, Map-Set, Map-Update
RsslBuffer vectorBuffer;
vectorBuffer.length = 4096;
vectorBuffer.data = ( char* )malloc( sizeof( char ) * 4096 );
RsslVector rsslVector = RSSL_INIT_VECTOR;
RsslEncodeIterator vectorEncodeIter;
rsslClearVector( &rsslVector );
rsslClearEncodeIterator( &vectorEncodeIter );
rsslSetEncodeIteratorRWFVersion( &vectorEncodeIter, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION );
rsslSetEncodeIteratorBuffer( &vectorEncodeIter, &vectorBuffer );
rsslVector.flags = RSSL_VTF_HAS_SUMMARY_DATA | RSSL_VTF_HAS_TOTAL_COUNT_HINT;
rsslVector.containerType = RSSL_DT_MAP;
rsslVector.totalCountHint = 5;
// allocate buffer for the map for SummaryData
RsslBuffer rsslBuf;
rsslBuf.length = 1000;
rsslBuf.data = ( char* )malloc( sizeof( char ) * 1000 );
RsslEncodeMapAll( rsslBuf );
rsslVector.encSummaryData = rsslBuf;
rsslEncodeVectorInit( &vectorEncodeIter, &rsslVector, 0, 0 );
RsslVectorEntry vectorEntry;
//first entry //Delete
rsslClearVectorEntry( &vectorEntry );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_DELETE_ENTRY;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
//second entry //Set Map
rsslClearVectorEntry( &vectorEntry );
// allocate buffer for the map for VectorEntries
RsslBuffer rsslBuf1;
rsslBuf1.length = 1000;
rsslBuf1.data = ( char* )malloc( sizeof( char ) * 1000 );
RsslEncodeMapAll( rsslBuf1 );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_SET_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
//third entry //Set Map
rsslClearVectorEntry( &vectorEntry );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_SET_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
//fourth entry //Update Map
rsslClearVectorEntry( &vectorEntry );
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_UPDATE_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
vectorBuffer.length = rsslGetEncodedBufferLength( &vectorEncodeIter );
rsslEncodeVectorComplete( &vectorEncodeIter, RSSL_TRUE );
//Now do EMA decoding of Vector
Vector vector;
StaticDecoder::setRsslData( &vector, &vectorBuffer, RSSL_DT_VECTOR, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION, &dictionary );
EXPECT_TRUE( vector.hasTotalCountHint() ) << "Vector contains Map - hasTotalCountHint()" ;
EXPECT_EQ( vector.getTotalCountHint(), 5 ) << "Vector contains Map - getTotalCountHint()" ;
switch ( vector.getSummaryData().getDataType() )
{
case DataType::MapEnum :
{
const Map& mapS = vector.getSummaryData().getMap();
EXPECT_TRUE( mapS.hasKeyFieldId() ) << "Vector Decode Summary Map - hasKeyFieldId()" ;
EXPECT_EQ( mapS.getKeyFieldId(), 3426 ) << "Vector Decode Summary Map - getKeyFieldId()" ;
EXPECT_TRUE( mapS.forth() ) << "Vector Decode Summary Map - first map forth()" ;
const MapEntry& me1a = mapS.getEntry();
EXPECT_EQ( me1a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me1a.getKey().getBuffer(), EmaBuffer( "ABCD", 4 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me1a.getAction(), MapEntry::DeleteEnum ) << "MapEntry::getAction() == MapEntry::DeleteEnum" ;
EXPECT_EQ( me1a.getLoad().getDataType(), DataType::NoDataEnum ) << "MapEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
EXPECT_TRUE( mapS.forth() ) << "Vector Decode Summary Map - second map forth()" ;
const MapEntry& me2a = mapS.getEntry();
EXPECT_EQ( me2a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
//me2a.getKey().getBuffer() is empty
//..
EXPECT_EQ( me2a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me2a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me2a.getFieldList() );
}
EXPECT_TRUE( mapS.forth() ) << "Vector Decode Summary Map - third map forth()" ;
const MapEntry& me3a = mapS.getEntry();
EXPECT_EQ( me3a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me3a.getKey().getBuffer(), EmaBuffer( "EFGHI", 5 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me3a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me3a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me3a.getFieldList() );
}
EXPECT_TRUE( mapS.forth() ) << "Vector Decode Summary Mapp - fourth map forth()" ;
const MapEntry& me4a = mapS.getEntry();
EXPECT_EQ( me4a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me4a.getKey().getBuffer(), EmaBuffer( "JKLMNOP", 7 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me4a.getAction(), MapEntry::UpdateEnum ) << "MapEntry::getAction() == MapEntry::UpdateEnum" ;
EXPECT_EQ( me4a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me4a.getFieldList() );
}
EXPECT_FALSE( mapS.forth() ) << "Vector Decode Summary Map - fifth map forth()" ;
}
break;
default :
EXPECT_FALSE( true ) << "Vector Decode Summary Map - vector.getSummaryType() not expected" ;
break;
}
EXPECT_TRUE( vector.forth() ) << "Vector contains Map - first vector forth()" ;
const VectorEntry& ve1 = vector.getEntry();
EXPECT_EQ( ve1.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve1.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
vector.reset();
{
EXPECT_TRUE( vector.forth() ) << "Vector contains Map - vector forth() after reset()" ;
const VectorEntry& ve = vector.getEntry();
EXPECT_EQ( ve.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
}
EXPECT_TRUE( vector.forth() ) << "Vector contains Map - second vector forth()" ;
const VectorEntry& ve2 = vector.getEntry();
EXPECT_EQ( ve2.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve2.getLoad().getDataType(), DataType::MapEnum ) << "VectorEntry::getLoad().getDataType() == DataType::MapEnum" ;
{
const Map& map = ve2.getMap();
EXPECT_TRUE( map.hasKeyFieldId() ) << "VectorEntry Map within vector - hasKeyFieldId()" ;
EXPECT_EQ( map.getKeyFieldId(), 3426 ) << "VectorEntry Map within vector - getKeyFieldId()" ;
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within vector - first map forth()" ;
const MapEntry& me1a = map.getEntry();
EXPECT_EQ( me1a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me1a.getKey().getBuffer(), EmaBuffer( "ABCD", 4 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me1a.getAction(), MapEntry::DeleteEnum ) << "MapEntry::getAction() == MapEntry::DeleteEnum" ;
EXPECT_EQ( me1a.getLoad().getDataType(), DataType::NoDataEnum ) << "MapEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within vector - second map forth()" ;
const MapEntry& me2a = map.getEntry();
EXPECT_EQ( me2a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
//me2a.getKey().getBuffer() is empty
//..
EXPECT_EQ( me2a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me2a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me2a.getFieldList() );
}
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within map - third map forth()" ;
const MapEntry& me3a = map.getEntry();
EXPECT_EQ( me3a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me3a.getKey().getBuffer(), EmaBuffer( "EFGHI", 5 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me3a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me3a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me3a.getFieldList() );
}
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within map - fourth map forth()" ;
const MapEntry& me4a = map.getEntry();
EXPECT_EQ( me4a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me4a.getKey().getBuffer(), EmaBuffer( "JKLMNOP", 7 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me4a.getAction(), MapEntry::UpdateEnum ) << "MapEntry::getAction() == MapEntry::UpdateEnum" ;
EXPECT_EQ( me4a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me4a.getFieldList() );
}
EXPECT_FALSE( map.forth() ) << "VectorEntry Map within map - fifth map forth()" ;
}
EXPECT_TRUE( vector.forth() ) << "Vector contains Map - third vector forth()" ;
const VectorEntry& ve3 = vector.getEntry();
EXPECT_EQ( ve3.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve3.getLoad().getDataType(), DataType::MapEnum ) << "VectorEntry::getLoad().getDataType() == DataType::MapEnum" ;
{
const Map& map = ve3.getMap();
EXPECT_TRUE( map.hasKeyFieldId() ) << "VectorEntry Map within vector - hasKeyFieldId()" ;
EXPECT_EQ( map.getKeyFieldId(), 3426 ) << "VectorEntry Map within vector - getKeyFieldId()" ;
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within vector - first map forth()" ;
const MapEntry& me1a = map.getEntry();
EXPECT_EQ( me1a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me1a.getKey().getBuffer(), EmaBuffer( "ABCD", 4 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me1a.getAction(), MapEntry::DeleteEnum ) << "MapEntry::getAction() == MapEntry::DeleteEnum" ;
EXPECT_EQ( me1a.getLoad().getDataType(), DataType::NoDataEnum ) << "MapEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within vector - second map forth()" ;
const MapEntry& me2a = map.getEntry();
EXPECT_EQ( me2a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
//me2a.getKey().getBuffer() is empty
//..
EXPECT_EQ( me2a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me2a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me2a.getFieldList() );
}
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within vector - third map forth()" ;
const MapEntry& me3a = map.getEntry();
EXPECT_EQ( me3a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me3a.getKey().getBuffer(), EmaBuffer( "EFGHI", 5 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me3a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me3a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me3a.getFieldList() );
}
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within vector - fourth map forth()" ;
const MapEntry& me4a = map.getEntry();
EXPECT_EQ( me4a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me4a.getKey().getBuffer(), EmaBuffer( "JKLMNOP", 7 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me4a.getAction(), MapEntry::UpdateEnum ) << "MapEntry::getAction() == MapEntry::UpdateEnum" ;
EXPECT_EQ( me4a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me4a.getFieldList() );
}
EXPECT_FALSE( map.forth() ) << "VectorEntry Map within vector - fifth map forth()" ;
}
EXPECT_TRUE( vector.forth() ) << "Vector contains Map - fourth vector forth()" ;
const VectorEntry& ve4 = vector.getEntry();
EXPECT_EQ( ve4.getAction(), VectorEntry::UpdateEnum ) << "VectorEntry::getAction() == VectorEntry::UpdateEnum" ;
EXPECT_EQ( ve4.getLoad().getDataType(), DataType::MapEnum ) << "VectorEntry::getLoad().getDataType() == DataType::MapEnum" ;
{
const Map& map = ve4.getMap();
EXPECT_TRUE( map.hasKeyFieldId() ) << "VectorEntry Map within vector - hasKeyFieldId()" ;
EXPECT_EQ( map.getKeyFieldId(), 3426 ) << "MapEntry Map within vector - getKeyFieldId()" ;
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within vector - first map forth()" ;
const MapEntry& me1a = map.getEntry();
EXPECT_EQ( me1a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me1a.getKey().getBuffer(), EmaBuffer( "ABCD", 4 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me1a.getAction(), MapEntry::DeleteEnum ) << "MapEntry::getAction() == MapEntry::DeleteEnum" ;
EXPECT_EQ( me1a.getLoad().getDataType(), DataType::NoDataEnum ) << "MapEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within vector - second map forth()" ;
const MapEntry& me2a = map.getEntry();
EXPECT_EQ( me2a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
//me2a.getKey().getBuffer() is empty
//..
EXPECT_EQ( me2a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me2a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me2a.getFieldList() );
}
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within vector - third map forth()" ;
const MapEntry& me3a = map.getEntry();
EXPECT_EQ( me3a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me3a.getKey().getBuffer(), EmaBuffer( "EFGHI", 5 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me3a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me3a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me3a.getFieldList() );
}
EXPECT_TRUE( map.forth() ) << "VectorEntry Map within vector - fourth map forth()" ;
const MapEntry& me4a = map.getEntry();
EXPECT_EQ( me4a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
EXPECT_STREQ( me4a.getKey().getBuffer(), EmaBuffer( "JKLMNOP", 7 ) ) << "MapEntry::getKey().getBuffer()" ;
EXPECT_EQ( me4a.getAction(), MapEntry::UpdateEnum ) << "MapEntry::getAction() == MapEntry::UpdateEnum" ;
EXPECT_EQ( me4a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( me4a.getFieldList() );
}
EXPECT_FALSE( map.forth() ) << "VectorEntry Map within vector - fifth map forth()" ;
}
EXPECT_FALSE( vector.forth() ) << "Vector contains Map - final vector forth()" ;
free( rsslBuf.data );
free( vectorBuffer.data );
EXPECT_TRUE( true ) << "Vector contains Map - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector contains Map - exception not expectedd" ;
}
rsslDeleteDataDictionary( &dictionary );
}
TEST(VectorTests, testVectorContainsOpaqueDecodeAll)
{
try
{
RsslBuffer vectorBuffer;
vectorBuffer.length = 4096;
vectorBuffer.data = ( char* )malloc( sizeof( char ) * 4096 );
RsslVector rsslVector = RSSL_INIT_VECTOR;
RsslEncodeIterator vectorEncodeIter;
rsslClearVector( &rsslVector );
rsslClearEncodeIterator( &vectorEncodeIter );
rsslSetEncodeIteratorRWFVersion( &vectorEncodeIter, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION );
rsslSetEncodeIteratorBuffer( &vectorEncodeIter, &vectorBuffer );
rsslVector.flags = RSSL_VTF_HAS_TOTAL_COUNT_HINT;
rsslVector.containerType = RSSL_DT_OPAQUE;
rsslVector.totalCountHint = 1;
rsslEncodeVectorInit( &vectorEncodeIter, &rsslVector, 0, 0 );
RsslVectorEntry vectorEntry;
rsslClearVectorEntry( &vectorEntry );
char buffer[100];
RsslBuffer rsslBuf1;
rsslBuf1.data = buffer;
rsslBuf1.length = 100;
RsslBuffer opaqueValue;
opaqueValue.data = ( char* )"482wfshfsrf2";
opaqueValue.length = static_cast<rtrUInt32>( strlen( opaqueValue.data ) );
encodeNonRWFData( &rsslBuf1, &opaqueValue );
vectorEntry.index = 0;
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_SET_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
//Now do EMA decoding of Vector
Vector vector;
StaticDecoder::setRsslData( &vector, &vectorBuffer, RSSL_DT_VECTOR, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION, 0 );
EXPECT_TRUE( vector.forth() ) << "Vector contains Opaque - first map forth()" ;
const VectorEntry& ve = vector.getEntry();
EXPECT_EQ( ve.getPosition(), 0 ) << "ve.getPosition()" ;
EXPECT_EQ( ve.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve.getLoad().getDataType(), DataType::OpaqueEnum ) << "VectorEntry::getLoad().getDataType() == DataType::OpaqueEnum" ;
EmaBuffer compareTo( opaqueValue.data, opaqueValue.length );
EXPECT_STREQ( ve.getOpaque().getBuffer(), compareTo ) << "VectorEntry::getOpaque().getBuffer()" ;
free( vectorBuffer.data );
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector Decode with Opaque payload - exception not expected" ;
}
}
TEST(VectorTests, testVectorContainsXmlDecodeAll)
{
try
{
RsslBuffer vectorBuffer;
vectorBuffer.length = 4096;
vectorBuffer.data = ( char* )malloc( sizeof( char ) * 4096 );
RsslVector rsslVector = RSSL_INIT_VECTOR;
RsslEncodeIterator vectorEncodeIter;
rsslClearVector( &rsslVector );
rsslClearEncodeIterator( &vectorEncodeIter );
rsslSetEncodeIteratorRWFVersion( &vectorEncodeIter, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION );
rsslSetEncodeIteratorBuffer( &vectorEncodeIter, &vectorBuffer );
rsslVector.flags = RSSL_VTF_HAS_TOTAL_COUNT_HINT;
rsslVector.containerType = RSSL_DT_XML;
rsslVector.totalCountHint = 1;
rsslEncodeVectorInit( &vectorEncodeIter, &rsslVector, 0, 0 );
RsslVectorEntry vectorEntry;
rsslClearVectorEntry( &vectorEntry );
char buffer[200];
RsslBuffer rsslBuf1;
rsslBuf1.data = buffer;
rsslBuf1.length = 200;
RsslBuffer xmlValue;
xmlValue.data = ( char* )"<consumerList><consumer><name dataType=\"Ascii\" value=\"Consumer_1\"/></consumer></consumerList>";
xmlValue.length = static_cast<rtrUInt32>( strlen( xmlValue.data ) );
encodeNonRWFData( &rsslBuf1, &xmlValue );
vectorEntry.index = 0;
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_SET_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
rsslEncodeVectorComplete( &vectorEncodeIter, RSSL_TRUE );
vectorBuffer.length = rsslGetEncodedBufferLength( &vectorEncodeIter );
Vector vector;
StaticDecoder::setRsslData( &vector, &vectorBuffer, RSSL_DT_VECTOR, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION, 0 );
EXPECT_TRUE( vector.forth() ) << "Vector contains Xml - first vector forth()" ;
const VectorEntry& ve = vector.getEntry();
EXPECT_EQ( ve.getPosition(), 0 ) << "ve.getPosition()" ;
EXPECT_EQ( ve.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve.getLoad().getDataType(), DataType::XmlEnum ) << "VectorEntry::getLoad().getDataType() == DataType::XmlEnum" ;
EmaBuffer compareTo( xmlValue.data, xmlValue.length );
EXPECT_STREQ( ve.getXml().getBuffer(), compareTo ) << "VectorEntry::getXml().getBuffer()" ;
free( vectorBuffer.data );
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector Decode with Xml payload - exception not expected" ;
}
}
TEST(VectorTests, testVectorContainsAnsiPageDecodeAll)
{
try
{
RsslBuffer vectorBuffer;
vectorBuffer.length = 4096;
vectorBuffer.data = ( char* )malloc( sizeof( char ) * 4096 );
RsslVector rsslVector = RSSL_INIT_VECTOR;
RsslEncodeIterator vectorEncodeIter;
rsslClearVector( &rsslVector );
rsslClearEncodeIterator( &vectorEncodeIter );
rsslSetEncodeIteratorRWFVersion( &vectorEncodeIter, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION );
rsslSetEncodeIteratorBuffer( &vectorEncodeIter, &vectorBuffer );
rsslVector.flags = RSSL_VTF_HAS_TOTAL_COUNT_HINT;
rsslVector.containerType = RSSL_DT_ANSI_PAGE;
rsslVector.totalCountHint = 1;
rsslEncodeVectorInit( &vectorEncodeIter, &rsslVector, 0, 0 );
RsslVectorEntry vectorEntry;
rsslClearVectorEntry( &vectorEntry );
char buffer[100];
RsslBuffer rsslBuf1;
rsslBuf1.data = buffer;
rsslBuf1.length = 100;
RsslBuffer ansiPageValue;
ansiPageValue.data = (char* )"$&@^@FRHFSORFEQ(*YQ)(E#QRY";
ansiPageValue.length = static_cast<rtrUInt32>( strlen( ansiPageValue.data ) );
encodeNonRWFData( &rsslBuf1, &ansiPageValue );
vectorEntry.index = 0;
vectorEntry.flags = RSSL_VTEF_NONE;
vectorEntry.action = RSSL_VTEA_SET_ENTRY;
vectorEntry.encData = rsslBuf1;
rsslEncodeVectorEntry( &vectorEncodeIter, &vectorEntry );
rsslEncodeVectorComplete( &vectorEncodeIter, RSSL_TRUE );
vectorBuffer.length = rsslGetEncodedBufferLength( &vectorEncodeIter );
Vector vector;
StaticDecoder::setRsslData( &vector, &vectorBuffer, RSSL_DT_VECTOR, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION, 0 );
EXPECT_TRUE( vector.forth() ) << "Vector contains AnsiPage - first vector forth()" ;
const VectorEntry& ve = vector.getEntry();
EXPECT_EQ( ve.getPosition(), 0 ) << "ve.getPosition()" ;
EXPECT_EQ( ve.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve.getLoad().getDataType(), DataType::AnsiPageEnum ) << "VectorEntry::getLoad().getDataType() == DataType::AnsiPageEnum" ;
EmaBuffer compareTo( ansiPageValue.data, ansiPageValue.length );
EXPECT_STREQ( ve.getAnsiPage().getBuffer(), compareTo ) << "VectorEntry::getAnsiPage().getBuffer()" ;
free( vectorBuffer.data );
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector Decode with AnsiPage payload - exception not expected" ;
}
}
void vectorOfFieldList_RsslEncodeEmaDecode( bool useSetDefinitions, std::string& decodedMsg )
{
// load dictionary for decoding of the field list
RsslDataDictionary dictionary;
try
{
ASSERT_TRUE(loadDictionaryFromFile( &dictionary )) << "Failed to load dictionary";
RsslEncodeIterator encodeIter;
rsslClearEncodeIterator( &encodeIter );
rsslSetEncodeIteratorRWFVersion( &encodeIter, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION );
RsslBuffer buffer;
buffer.length = 2048;
buffer.data = ( char* )malloc( sizeof( char ) * 2048 );
rsslSetEncodeIteratorBuffer( &encodeIter, &buffer );
RsslVector rsslVector;
rsslClearVector( &rsslVector );
if ( useSetDefinitions )
{
rsslVector.flags = RSSL_MPF_HAS_SET_DEFS;
}
rsslVector.containerType = RSSL_DT_FIELD_LIST;
rsslEncodeVectorInit( &encodeIter, &rsslVector, 0, 0 );
RsslLocalFieldSetDefDb fieldSetDefDb;
RsslFieldSetDefEntry fieldSetDefEntries[3] =
{
{ 22, RSSL_DT_REAL },
{ 25, RSSL_DT_REAL_8RB },
{ 18, RSSL_DT_TIME_3 }
};
if ( useSetDefinitions )
{
RsslFieldSetDef fieldSetDef;
fieldSetDef.setId = 5;
fieldSetDef.count = 3;
fieldSetDef.pEntries = fieldSetDefEntries;
rsslClearLocalFieldSetDefDb( &fieldSetDefDb );
fieldSetDefDb.definitions[5] = fieldSetDef;
rsslEncodeLocalFieldSetDefDb( &encodeIter, &fieldSetDefDb );
rsslEncodeVectorSetDefsComplete( &encodeIter, RSSL_TRUE );
}
RsslVectorEntry entry;
rsslClearVectorEntry( &entry );
entry.action = RSSL_MPEA_ADD_ENTRY;
entry.flags = RSSL_MPEF_NONE;
const RsslUInt rsslUInt = 100212;
rsslEncodeVectorEntryInit( &encodeIter, &entry, 0 );
RsslFieldList fieldList;
rsslClearFieldList( &fieldList );
if ( useSetDefinitions )
{
fieldList.setId = 5;
fieldList.flags = RSSL_FLF_HAS_SET_ID | RSSL_ELF_HAS_SET_DATA;
rsslEncodeFieldListInit( &encodeIter, &fieldList, &fieldSetDefDb, 0 );
}
else
{
fieldList.flags = RSSL_FLF_HAS_STANDARD_DATA;
rsslEncodeFieldListInit( &encodeIter, &fieldList, 0, 0 );
}
RsslFieldEntry fieldEntry;
rsslClearFieldEntry( &fieldEntry );
fieldEntry.fieldId = 22;
fieldEntry.dataType = RSSL_DT_REAL;
RsslReal rsslReal;
rsslClearReal( &rsslReal );
rsslReal.hint = RSSL_RH_EXPONENT_2;
rsslReal.value = 227;
rsslEncodeFieldEntry( &encodeIter, &fieldEntry, &rsslReal );
rsslClearFieldEntry( &fieldEntry );
fieldEntry.fieldId = 25;
fieldEntry.dataType = RSSL_DT_REAL;
rsslClearReal( &rsslReal );
rsslReal.hint = RSSL_RH_EXPONENT_4;
rsslReal.value = 22801;
rsslEncodeFieldEntry( &encodeIter, &fieldEntry, &rsslReal );
rsslClearFieldEntry( &fieldEntry );
fieldEntry.fieldId = 18;
fieldEntry.dataType = RSSL_DT_TIME;
RsslTime rsslTime;
rsslClearTime( &rsslTime );
rsslTime.hour = 8;
rsslTime.minute = 39;
rsslTime.second = 24;
rsslEncodeFieldEntry( &encodeIter, &fieldEntry, &rsslTime );
rsslEncodeFieldListComplete( &encodeIter, RSSL_TRUE );
rsslEncodeVectorEntryComplete( &encodeIter, RSSL_TRUE );
rsslEncodeVectorComplete( &encodeIter, RSSL_TRUE );
Vector vector;
StaticDecoder::setRsslData( &vector, &buffer, RSSL_DT_VECTOR, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION, &dictionary );
decodedMsg = vector;
}
catch ( const OmmException& )
{
EXPECT_FALSE(true) << "Decoding of Vector of FieldList, encoded from rssl set defs - exception not expected" ;
}
rsslDeleteDataDictionary( &dictionary );
}
TEST(VectorTests, testVectorContainsFieldListSetDefinitionsDecode)
{
std::string msgFromStandardData;
vectorOfFieldList_RsslEncodeEmaDecode( false, msgFromStandardData );
std::string msgFromSetDef;
vectorOfFieldList_RsslEncodeEmaDecode( true, msgFromSetDef );
EXPECT_EQ( msgFromSetDef, msgFromStandardData ) << "Encoding from set definitions results in same decoded message." ;
}
void vectorOfElementList_RsslEncodeEmaDecode( bool useSetDefinitions, std::string& decodedMsg )
{
try
{
RsslEncodeIterator encodeIter;
rsslClearEncodeIterator( &encodeIter );
rsslSetEncodeIteratorRWFVersion( &encodeIter, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION );
RsslBuffer buffer;
buffer.length = 2048;
buffer.data = ( char* )malloc( sizeof( char ) * 2048 );
rsslSetEncodeIteratorBuffer( &encodeIter, &buffer );
RsslVector rsslVector;
rsslClearVector( &rsslVector );
if ( useSetDefinitions )
{
rsslVector.flags = RSSL_MPF_HAS_SET_DEFS;
}
rsslVector.containerType = RSSL_DT_ELEMENT_LIST;
rsslEncodeVectorInit( &encodeIter, &rsslVector, 0, 0 );
RsslLocalElementSetDefDb elementSetDefDb;
RsslElementSetDefEntry elementSetDefEntries[3] =
{
{ {3, const_cast<char*>( "BID" )}, RSSL_DT_REAL },
{ {3, const_cast<char*>( "ASK")}, RSSL_DT_REAL_8RB },
{ {10, const_cast<char*>( "TRADE_TIME")}, RSSL_DT_TIME_3 }
};
if ( useSetDefinitions )
{
RsslElementSetDef elementSetDef;
elementSetDef.setId = 5;
elementSetDef.count = 3;
elementSetDef.pEntries = elementSetDefEntries;
rsslClearLocalElementSetDefDb( &elementSetDefDb );
elementSetDefDb.definitions[5] = elementSetDef;
rsslEncodeLocalElementSetDefDb( &encodeIter, &elementSetDefDb );
rsslEncodeVectorSetDefsComplete( &encodeIter, RSSL_TRUE );
}
RsslVectorEntry vectorEntry;
rsslClearVectorEntry( &vectorEntry );
vectorEntry.action = RSSL_MPEA_ADD_ENTRY;
vectorEntry.flags = RSSL_MPEF_NONE;
const RsslUInt rsslUInt = 100212;
rsslEncodeVectorEntryInit( &encodeIter, &vectorEntry, 0 );
RsslElementList elementList;
rsslClearElementList( &elementList );
if ( useSetDefinitions )
{
elementList.setId = 5;
elementList.flags = RSSL_FLF_HAS_SET_ID | RSSL_ELF_HAS_SET_DATA;
rsslEncodeElementListInit( &encodeIter, &elementList, &elementSetDefDb, 0 );
}
else
{
elementList.flags = RSSL_FLF_HAS_STANDARD_DATA;
rsslEncodeElementListInit( &encodeIter, &elementList, 0, 0 );
}
RsslElementEntry elementEntry;
rsslClearElementEntry( &elementEntry );
elementEntry.name = elementSetDefEntries[0].name;
elementEntry.dataType = RSSL_DT_REAL;
RsslReal rsslReal;
rsslClearReal( &rsslReal );
rsslReal.hint = RSSL_RH_EXPONENT_2;
rsslReal.value = 227;
rsslEncodeElementEntry( &encodeIter, &elementEntry, &rsslReal );
rsslClearElementEntry( &elementEntry );
elementEntry.name = elementSetDefEntries[1].name;
elementEntry.dataType = RSSL_DT_REAL;
rsslClearReal( &rsslReal );
rsslReal.hint = RSSL_RH_EXPONENT_4;
rsslReal.value = 22801;
rsslEncodeElementEntry( &encodeIter, &elementEntry, &rsslReal );
rsslClearElementEntry( &elementEntry );
elementEntry.name = elementSetDefEntries[2].name;
elementEntry.dataType = RSSL_DT_TIME;
RsslTime rsslTime;
rsslClearTime( &rsslTime );
rsslTime.hour = 8;
rsslTime.minute = 39;
rsslTime.second = 24;
rsslEncodeElementEntry( &encodeIter, &elementEntry, &rsslTime );
rsslEncodeElementListComplete( &encodeIter, RSSL_TRUE );
rsslEncodeVectorEntryComplete( &encodeIter, RSSL_TRUE );
rsslEncodeVectorComplete( &encodeIter, RSSL_TRUE );
Vector vector;
StaticDecoder::setRsslData( &vector, &buffer, RSSL_DT_VECTOR, RSSL_RWF_MAJOR_VERSION, RSSL_RWF_MINOR_VERSION, 0 );
decodedMsg = vector;
}
catch ( const OmmException& )
{
EXPECT_FALSE(true) << "Decoding of Vector of ElementList, encoded from rssl set defs - exception not expected" ;
}
}
TEST(VectorTests, testVectorContainsElementListSetDefinitionsDecode)
{
std::string msgFromStandardData;
vectorOfElementList_RsslEncodeEmaDecode( false, msgFromStandardData );
std::string msgFromSetDef;
vectorOfElementList_RsslEncodeEmaDecode( true, msgFromSetDef );
EXPECT_EQ( msgFromSetDef, msgFromStandardData ) << "Encoding from set definitions results in same decoded message." ;
}
TEST(VectorTests, testVectorContainsFieldListsEncodeDecodeAll)
{
// load dictionary for decoding of the field list
RsslDataDictionary dictionary;
ASSERT_TRUE(loadDictionaryFromFile( &dictionary )) << "Failed to load dictionary";
Vector vectorEnc;
vectorEnc.totalCountHint( 5 );
try
{
//EMA Encoding
// encoding order: SummaryData(with FieldList), Delete, FieldList-Set, FieldList-Set, FieldList-Update
FieldList flEnc;
EmaEncodeFieldListAll( flEnc );
vectorEnc.summaryData( flEnc );
FieldList flEnc1;
EmaEncodeFieldListAll( flEnc1 );
char* permS = const_cast<char*>( "PERMISSION DATA" );
EmaBuffer permissionData1( permS, 15 );
//first entry //Delete
vectorEnc.add( 1, VectorEntry::DeleteEnum, flEnc1, permissionData1 );
//second entry //Set FieldList
vectorEnc.add( 1, VectorEntry::SetEnum, flEnc1, permissionData1 );
//third entry //Set FieldList
vectorEnc.add( 2, VectorEntry::SetEnum, flEnc1, permissionData1 );
//fpurth entry //Update FieldList
vectorEnc.add( 3, VectorEntry::UpdateEnum, flEnc1, permissionData1 );
vectorEnc.complete();
//Now do EMA decoding of Vector
StaticDecoder::setData( &vectorEnc, &dictionary );
EXPECT_TRUE( vectorEnc.hasTotalCountHint() ) << "Vector contains FieldLists - hasTotalCountHint()" ;
EXPECT_EQ( vectorEnc.getTotalCountHint(), 5 ) << "Vector contains FieldLists - getTotalCountHint()" ;
switch ( vectorEnc.getSummaryData().getDataType() )
{
case DataType::FieldListEnum :
{
const FieldList& fl = vectorEnc.getSummaryData().getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
break;
default :
EXPECT_FALSE( true ) << "Vector Decode Summary FieldList - vector.getSummaryType() not expected" ;
break;
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains FieldLists - first vector forth()" ;
const VectorEntry& ve1 = vectorEnc.getEntry();
EXPECT_EQ( ve1.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve1.getPosition(), 1 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve1.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
vectorEnc.reset();
{
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains FieldLists - vector forth() after reset()" ;
const VectorEntry& ve = vectorEnc.getEntry();
EXPECT_EQ( ve.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains FieldLists - second vector forth()" ;
const VectorEntry& ve2 = vectorEnc.getEntry();
EXPECT_EQ( ve2.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve2.getPosition(), 1 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve2.getLoad().getDataType(), DataType::FieldListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = ve2.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains FieldLists - third vector forth()" ;
const VectorEntry& ve3 = vectorEnc.getEntry();
EXPECT_EQ( ve3.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve3.getPosition(), 2 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve3.getLoad().getDataType(), DataType::FieldListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
{
const FieldList& fl = ve3.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains FieldLists - fourth vector forth()" ;
const VectorEntry& ve4 = vectorEnc.getEntry();
EXPECT_EQ( ve4.getAction(), VectorEntry::UpdateEnum ) << "VectorEntry::getAction() == VectorEntry::UpdateEnum" ;
EXPECT_EQ( ve4.getPosition(), 3 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve4.getLoad().getDataType(), DataType::FieldListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
EXPECT_FALSE( vectorEnc.forth() ) << "Vector contains FieldLists - final vector forth()" ;
EXPECT_TRUE( true ) << "Vector contains FieldLists - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector contains FieldLists - exception not expectedd" ;
}
}
TEST(VectorTests, testVectorContainsElementListsEncodeDecodeAll)
{
// load dictionary for decoding of the field list
RsslDataDictionary dictionary;
ASSERT_TRUE(loadDictionaryFromFile( &dictionary )) << "Failed to load dictionary";
Vector vectorEnc;
vectorEnc.totalCountHint( 5 );
try
{
//EMA Encoding
// encoding order: SummaryData(with ElementList), Delete, ElementList-Set, ElementList-Set, ElementList-Update
ElementList elEnc;
EmaEncodeElementListAll( elEnc );
vectorEnc.summaryData( elEnc );
ElementList elEnc1;
EmaEncodeElementListAll( elEnc1 );
char* permS = const_cast<char*>( "PERMISSION DATA" );
EmaBuffer permissionData1( permS, 15 );
//first entry //Delete
vectorEnc.add( 1, VectorEntry::DeleteEnum, elEnc1, permissionData1 );
//second entry //Set ElementList
vectorEnc.add( 1, VectorEntry::SetEnum, elEnc1, permissionData1 );
//third entry //Set ElementList
vectorEnc.add( 2, VectorEntry::SetEnum, elEnc1, permissionData1 );
//fourth entry //Update ElementList
vectorEnc.add( 3, VectorEntry::UpdateEnum, elEnc1, permissionData1 );
vectorEnc.complete();
//Now do EMA decoding of Vector
StaticDecoder::setData( &vectorEnc, &dictionary );
EXPECT_TRUE( vectorEnc.hasTotalCountHint() ) << "Vector contains ElementLists - hasTotalCountHint()" ;
EXPECT_EQ( vectorEnc.getTotalCountHint(), 5 ) << "Vector contains ElementLists - getTotalCountHint()" ;
switch ( vectorEnc.getSummaryData().getDataType() )
{
case DataType::ElementListEnum :
{
const ElementList& el = vectorEnc.getSummaryData().getElementList();
SCOPED_TRACE("calling EmaDecodeElementListAll");
EmaDecodeElementListAll( el );
}
break;
default :
EXPECT_FALSE( true ) << "Vector Decode Summary FieldList - vector.getSummaryType() not expected" ;
break;
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains ElementLists - first vector forth()" ;
const VectorEntry& ve1 = vectorEnc.getEntry();
EXPECT_EQ( ve1.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve1.getPosition(), 1 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve1.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
vectorEnc.reset();
{
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains ElementLists - vector forth() after reset()" ;
const VectorEntry& ve = vectorEnc.getEntry();
EXPECT_EQ( ve.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains ElementLists - second vector forth()" ;
const VectorEntry& ve2 = vectorEnc.getEntry();
EXPECT_EQ( ve2.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve2.getPosition(), 1 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve2.getLoad().getDataType(), DataType::ElementListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::ElementListEnum" ;
{
const ElementList& el = ve2.getElementList();
SCOPED_TRACE("calling EmaDecodeElementListAll");
EmaDecodeElementListAll( el );
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains ElementLists - third vector forth()" ;
const VectorEntry& ve3 = vectorEnc.getEntry();
EXPECT_EQ( ve3.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve3.getPosition(), 2 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve3.getLoad().getDataType(), DataType::ElementListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::ElementListEnum" ;
{
const ElementList& el = ve3.getElementList();
SCOPED_TRACE("calling EmaDecodeElementListAll");
EmaDecodeElementListAll( el );
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains ElementLists - fourth vector forth()" ;
const VectorEntry& ve4 = vectorEnc.getEntry();
EXPECT_EQ( ve4.getAction(), VectorEntry::UpdateEnum ) << "VectorEntry::getAction() == VectorEntry::UpdateEnum" ;
EXPECT_EQ( ve4.getPosition(), 3 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve4.getLoad().getDataType(), DataType::ElementListEnum ) << "VectorEntry::getLoad().getDataType() == DataType::ElementListEnum" ;
{
const ElementList& el = ve4.getElementList();
SCOPED_TRACE("calling EmaDecodeElementListAll");
EmaDecodeElementListAll( el );
}
EXPECT_FALSE( vectorEnc.forth() ) << "Vector contains ElementLists - final vector forth()" ;
EXPECT_TRUE( true ) << "Vector contains ElementLists - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector contains ElementLists - exception not expectedd" ;
}
}
TEST(VectorTests, testVectorContainsMapsEncodeDecodeAll)
{
// load dictionary for decoding of the field list
RsslDataDictionary dictionary;
ASSERT_TRUE(loadDictionaryFromFile( &dictionary )) << "Failed to load dictionary";
Vector vectorEnc;
vectorEnc.totalCountHint( 5 );
try
{
//EMA Encoding
// encoding order: SummaryData(with Map), Delete, Map-Set, Map-Set, Map-Update
Map mapEncS;
EmaEncodeMapAll( mapEncS );
vectorEnc.summaryData( mapEncS );
Map mapEnc1;
EmaEncodeMapAll( mapEnc1 );
char* permS = const_cast<char*>( "PERMISSION DATA" );
EmaBuffer permissionData1( permS, 15 );
//first entry //Delete
vectorEnc.add( 1, VectorEntry::DeleteEnum, mapEnc1, permissionData1 );
//second entry //Set Map
vectorEnc.add( 1, VectorEntry::SetEnum, mapEnc1, permissionData1 );
//third entry //Set Map
vectorEnc.add( 2, VectorEntry::SetEnum, mapEnc1, permissionData1 );
//fourth entry //Update Map
vectorEnc.add( 3, VectorEntry::UpdateEnum, mapEnc1, permissionData1 );
vectorEnc.complete();
//Now do EMA decoding of Vector
StaticDecoder::setData( &vectorEnc, &dictionary );
EXPECT_TRUE( vectorEnc.hasTotalCountHint() ) << "Vector contains Maps - hasTotalCountHint()" ;
EXPECT_EQ( vectorEnc.getTotalCountHint(), 5 ) << "Vector contains Maps - getTotalCountHint()" ;
switch ( vectorEnc.getSummaryData().getDataType() )
{
case DataType::MapEnum :
{
const Map& mapS = vectorEnc.getSummaryData().getMap();
EXPECT_TRUE( mapS.hasKeyFieldId() ) << "Vector Decode Summary Map - hasKeyFieldId()" ;
EXPECT_EQ( mapS.getKeyFieldId(), 3426 ) << "Vector Decode Summary Map - getKeyFieldId()" ;
EXPECT_TRUE( mapS.forth() ) << "Vector Decode Summary Map - first map forth()" ;
const MapEntry& me1a = mapS.getEntry();
EXPECT_EQ( me1a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "ABCD", 4 );
EXPECT_STREQ( me1a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me1a.getAction(), MapEntry::DeleteEnum ) << "MapEntry::getAction() == MapEntry::DeleteEnum" ;
EXPECT_EQ( me1a.getLoad().getDataType(), DataType::NoDataEnum ) << "MapEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
EXPECT_TRUE( mapS.forth() ) << "Vector Decode Summary Map - second map forth()" ;
const MapEntry& me2a = mapS.getEntry();
EXPECT_EQ( me2a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
//me2a.getKey().getBuffer() is empty
//..
EXPECT_EQ( me2a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me2a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me2a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( mapS.forth() ) << "Vector Decode Summary Map - third map forth()" ;
const MapEntry& me3a = mapS.getEntry();
EXPECT_EQ( me3a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "EFGHI", 5 );
EXPECT_STREQ( me3a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me3a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me3a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me3a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( mapS.forth() ) << "Vector Decode Summary Mapp - fourth map forth()" ;
const MapEntry& me4a = mapS.getEntry();
EXPECT_EQ( me4a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "JKLMNOP", 7 );
EXPECT_STREQ( me4a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me4a.getAction(), MapEntry::UpdateEnum ) << "MapEntry::getAction() == MapEntry::UpdateEnum" ;
EXPECT_EQ( me4a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me4a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_FALSE( mapS.forth() ) << "Vector Decode Summary Map - fifth map forth()" ;
}
break;
default :
EXPECT_FALSE( true ) << "Vector Decode Summary Map - vector.getSummaryType() not expected" ;
break;
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains Map - first vector forth()" ;
const VectorEntry& ve1 = vectorEnc.getEntry();
EXPECT_EQ( ve1.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve1.getPosition(), 1 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve1.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
vectorEnc.reset();
{
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains Maps - vector forth() after reset()" ;
const VectorEntry& ve = vectorEnc.getEntry();
EXPECT_EQ( ve.getAction(), VectorEntry::DeleteEnum ) << "VectorEntry::getAction() == VectorEntry::DeleteEnum" ;
EXPECT_EQ( ve.getLoad().getDataType(), DataType::NoDataEnum ) << "VectorEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains Map - second vector forth()" ;
const VectorEntry& ve2 = vectorEnc.getEntry();
EXPECT_EQ( ve2.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve2.getPosition(), 1 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve2.getLoad().getDataType(), DataType::MapEnum ) << "VectorEntry::getLoad().getDataType() == DataType::MapEnum" ;
{
const Map& mapNested = ve2.getMap();
EXPECT_TRUE( mapNested.hasKeyFieldId() ) << "VectorEntry Map within series - hasKeyFieldId()" ;
EXPECT_EQ( mapNested.getKeyFieldId(), 3426 ) << "SeriesEntry Map within series - getKeyFieldId()" ;
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within series - first map forth()" ;
const MapEntry& me1a = mapNested.getEntry();
EXPECT_EQ( me1a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "ABCD", 4 );
EXPECT_STREQ( me1a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me1a.getAction(), MapEntry::DeleteEnum ) << "MapEntry::getAction() == MapEntry::DeleteEnum" ;
EXPECT_EQ( me1a.getLoad().getDataType(), DataType::NoDataEnum ) << "MapEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within map - second map forth()" ;
const MapEntry& me2a = mapNested.getEntry();
EXPECT_EQ( me2a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "ABCD", 4 );
EXPECT_STREQ( me2a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me2a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me2a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me2a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within series - third map forth()" ;
const MapEntry& me3a = mapNested.getEntry();
EXPECT_EQ( me3a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "EFGHI", 5 );
EXPECT_STREQ( me3a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me3a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me3a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me3a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within series - fourth map forth()" ;
const MapEntry& me4a = mapNested.getEntry();
EXPECT_EQ( me4a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "JKLMNOP", 7 );
EXPECT_STREQ( me4a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me4a.getAction(), MapEntry::UpdateEnum ) << "MapEntry::getAction() == MapEntry::UpdateEnum" ;
EXPECT_EQ( me4a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me4a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_FALSE( mapNested.forth() ) << "VectorEntry Map within series - fifth map forth()" ;
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains Map - third vector forth()" ;
const VectorEntry& ve3 = vectorEnc.getEntry();
EXPECT_EQ( ve3.getAction(), VectorEntry::SetEnum ) << "VectorEntry::getAction() == VectorEntry::SetEnum" ;
EXPECT_EQ( ve3.getPosition(), 2 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve3.getLoad().getDataType(), DataType::MapEnum ) << "VectorEntry::getLoad().getDataType() == DataType::MapEnum" ;
{
const Map& mapNested = ve3.getMap();
EXPECT_TRUE( mapNested.hasKeyFieldId() ) << "VectorEntry Map within series - hasKeyFieldId()" ;
EXPECT_EQ( mapNested.getKeyFieldId(), 3426 ) << "SeriesEntry Map within series - getKeyFieldId()" ;
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within series - first map forth()" ;
const MapEntry& me1a = mapNested.getEntry();
EXPECT_EQ( me1a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "ABCD", 4 );
EXPECT_STREQ( me1a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me1a.getAction(), MapEntry::DeleteEnum ) << "MapEntry::getAction() == MapEntry::DeleteEnum" ;
EXPECT_EQ( me1a.getLoad().getDataType(), DataType::NoDataEnum ) << "MapEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within map - second map forth()" ;
const MapEntry& me2a = mapNested.getEntry();
EXPECT_EQ( me2a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "ABCD", 4 );
EXPECT_STREQ( me2a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me2a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me2a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me2a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within series - third map forth()" ;
const MapEntry& me3a = mapNested.getEntry();
EXPECT_EQ( me3a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "EFGHI", 5 );
EXPECT_STREQ( me3a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me3a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me3a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me3a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within series - fourth map forth()" ;
const MapEntry& me4a = mapNested.getEntry();
EXPECT_EQ( me4a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "JKLMNOP", 7 );
EXPECT_STREQ( me4a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me4a.getAction(), MapEntry::UpdateEnum ) << "MapEntry::getAction() == MapEntry::UpdateEnum" ;
EXPECT_EQ( me4a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me4a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_FALSE( mapNested.forth() ) << "VectorEntry Map within series - fifth map forth()" ;
}
EXPECT_TRUE( vectorEnc.forth() ) << "Vector contains Map - fourth vector forth()" ;
const VectorEntry& ve4 = vectorEnc.getEntry();
EXPECT_EQ( ve4.getAction(), VectorEntry::UpdateEnum ) << "VectorEntry::getAction() == VectorEntry::UpdateEnum" ;
EXPECT_EQ( ve4.getPosition(), 3 ) << "VectorEntry::getPostion()" ;
EXPECT_EQ( ve4.getLoad().getDataType(), DataType::MapEnum ) << "VectorEntry::getLoad().getDataType() == DataType::MapEnum" ;
{
const Map& mapNested = ve4.getMap();
EXPECT_TRUE( mapNested.hasKeyFieldId() ) << "VectorEntry Map within series - hasKeyFieldId()" ;
EXPECT_EQ( mapNested.getKeyFieldId(), 3426 ) << "SeriesEntry Map within series - getKeyFieldId()" ;
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within series - first map forth()" ;
const MapEntry& me1a = mapNested.getEntry();
EXPECT_EQ( me1a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "ABCD", 4 );
EXPECT_STREQ( me1a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me1a.getAction(), MapEntry::DeleteEnum ) << "MapEntry::getAction() == MapEntry::DeleteEnum" ;
EXPECT_EQ( me1a.getLoad().getDataType(), DataType::NoDataEnum ) << "MapEntry::getLoad().getDataType() == DataType::NoDataEnum" ;
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within map - second map forth()" ;
const MapEntry& me2a = mapNested.getEntry();
EXPECT_EQ( me2a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "ABCD", 4 );
EXPECT_STREQ( me2a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me2a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me2a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me2a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within series - third map forth()" ;
const MapEntry& me3a = mapNested.getEntry();
EXPECT_EQ( me3a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "EFGHI", 5 );
EXPECT_STREQ( me3a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me3a.getAction(), MapEntry::AddEnum ) << "MapEntry::getAction() == MapEntry::AddEnum" ;
EXPECT_EQ( me3a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me3a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_TRUE( mapNested.forth() ) << "VectorEntry Map within series - fourth map forth()" ;
const MapEntry& me4a = mapNested.getEntry();
EXPECT_EQ( me4a.getKey().getDataType(), DataType::BufferEnum ) << "MapEntry::getKey().getDataType() == DataType::BufferEnum" ;
{
EmaBuffer Buf( "JKLMNOP", 7 );
EXPECT_STREQ( me4a.getKey().getBuffer(), Buf ) << "MapEntry::getKey().getBuffer()" ;
}
EXPECT_EQ( me4a.getAction(), MapEntry::UpdateEnum ) << "MapEntry::getAction() == MapEntry::UpdateEnum" ;
EXPECT_EQ( me4a.getLoad().getDataType(), DataType::FieldListEnum ) << "MapEntry::getLoad().getDataType() == DataType::FieldListEnum" ;
{
const FieldList& fl = me4a.getFieldList();
SCOPED_TRACE("calling EmaDecodeFieldListAll");
EmaDecodeFieldListAll( fl );
}
EXPECT_FALSE( mapNested.forth() ) << "VectorEntry Map within series - fifth map forth()" ;
}
EXPECT_FALSE( vectorEnc.forth() ) << "Vector contains Map - fourth vector forth()" ;
EXPECT_TRUE( true ) << "Vector contains Map - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector contains Map - exception not expectedd" ;
}
}
TEST(VectorTests, testVectorError)
{
{
try
{
Vector vec;
ElementList el;
el.addAscii( "entry", "value" ).complete();
vec.summaryData( el );
vec.totalCountHint( 2 );
vec.complete();
EXPECT_TRUE( true ) << "Vector::complete() on empty vector with summary - exception not expected" ;
StaticDecoder::setData( &vec, 0 );
EXPECT_TRUE( vec.hasTotalCountHint() ) << "Vector::hasTotalCountHint()" ;
EXPECT_EQ( vec.getTotalCountHint(), 2 ) << "Vector::getTotalCountHint()" ;
EXPECT_EQ( vec.getSummaryData().getDataType(), DataType::ElementListEnum ) << "Vector::getSummaryData()::getDataType()" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector::complete() on empty vector with summary - exception not expected" ;
}
}
{
try
{
Vector vec;
ElementList el;
el.addAscii( "entry", "value" ).complete();
vec.summaryData( el );
vec.totalCountHint( 2 );
FieldList fl;
fl.addUInt( 1, 1 ).complete();
vec.add( 1, VectorEntry::SetEnum, fl );
vec.complete();
EXPECT_FALSE( true ) << "Vector::summaryData( ElementList ).add( FieldList ) - exception expected" ;
}
catch ( const OmmException& )
{
EXPECT_TRUE( true ) << "Vector::summaryData( ElementList ).add( FieldList ) - exception expected" ;
}
}
{
try
{
Vector vec;
ElementList el;
el.addAscii( "entry", "value" ).complete();
vec.add( 1, VectorEntry::SetEnum, el );
FieldList fl;
fl.addUInt( 1, 1 ).complete();
vec.add( 2, VectorEntry::SetEnum, fl );
vec.complete();
EXPECT_FALSE( true ) << "Vector::add( ElementList ).add( FieldList ) - exception expected" ;
}
catch ( const OmmException& )
{
EXPECT_TRUE( true ) << "Vector::add( ElementList ).add( FieldList ) - exception expected" ;
}
}
{
try
{
Vector vec;
ElementList el;
el.addAscii( "entry", "value" ).complete();
vec.add( 1, VectorEntry::SetEnum, el );
vec.complete();
vec.add( 2, VectorEntry::SetEnum, el );
EXPECT_FALSE( true ) << "Vector add after complete - exception expected" ;
}
catch ( const OmmException& )
{
EXPECT_TRUE( true ) << "Vector add after complete - exception expected" ;
}
}
{
try
{
Vector vec;
ElementList el;
el.addAscii( "entry", "value" ).complete();
vec.add( 1, VectorEntry::SetEnum, el );
vec.complete();
vec.clear();
vec.add( 2, VectorEntry::SetEnum, el );
vec.complete();
StaticDecoder::setData( &vec, 0 );
EXPECT_TRUE( vec.forth() ) << "Vector::forth()" ;
EXPECT_FALSE( vec.forth() ) << "Vector::forth()" ;
EXPECT_TRUE( true ) << "Vector add after complete - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector add after complete - exception not expected" ;
}
}
{
try
{
Vector vec;
ElementList el;
el.addAscii( "entry", "value" );
vec.add( 1, VectorEntry::SetEnum, el );
vec.complete();
EXPECT_FALSE( true ) << "Vector add element list while element list is not complete - exception expected" ;
}
catch ( const OmmException& )
{
EXPECT_TRUE( true ) << "Vector add element list while element list is not complete - exception expected" ;
}
}
try
{
Vector container;
RefreshMsg msg;
container.add( 1, VectorEntry::SetEnum, msg );
EXPECT_FALSE( true ) << "Vector::add( RefreshMsg ) while RefreshMsg is empty - exception expected" ;
}
catch ( const OmmException& )
{
EXPECT_TRUE( true ) << "Vector::add( RefreshMsg ) while RefreshMsg is empty - exception expected" ;
}
try
{
Vector container;
RefreshMsg msg;
msg.serviceId( 1 );
container.add( 1, VectorEntry::SetEnum, msg );
container.complete();
StaticDecoder::setData( &container, 0 );
EXPECT_TRUE( container.forth() ) << "Vector::forht()" ;
EXPECT_EQ( container.getEntry().getLoadType(), DataType::RefreshMsgEnum ) << "VectorEntry::getLoadType()" ;
EXPECT_TRUE( true ) << "Vector::add( RefreshMsg ) while RefreshMsg is populated - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector::add( RefreshMsg ) while RefreshMsg is populated - exception not expected" ;
}
try
{
Vector container;
RefreshMsg msg;
container.summaryData( msg );
container.complete();
EXPECT_FALSE( true ) << "Vector::summaryData( RefreshMsg ) while RefreshMsg is empty - exception expected" ;
}
catch ( const OmmException& )
{
EXPECT_TRUE( true ) << "Vector::summaryData( RefreshMsg ) while RefreshMsg is empty - exception expected" ;
}
try
{
Vector container;
RefreshMsg msg;
msg.streamId( 10 );
container.summaryData( msg );
container.complete();
StaticDecoder::setData( &container, 0 );
EXPECT_TRUE( true ) << "Vector::summaryData( RefreshMsg ) while RefreshMsg is populated - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector::summaryData( RefreshMsg ) while RefreshMsg is populated - exception not expected" ;
}
try
{
Vector container;
GenericMsg msg;
container.add( 1, VectorEntry::SetEnum, msg );
EXPECT_FALSE( true ) << "Vector::add( GenericMsg ) while GenericMsg is empty - exception expected" ;
}
catch ( const OmmException& )
{
EXPECT_TRUE( true ) << "Vector::add( GenericMsg ) while GenericMsg is empty - exception expected" ;
}
try
{
Vector container;
GenericMsg msg;
msg.serviceId( 1 );
container.add( 1, VectorEntry::SetEnum, msg );
container.complete();
StaticDecoder::setData( &container, 0 );
EXPECT_TRUE( container.forth() ) << "Vector::forht()" ;
EXPECT_EQ( container.getEntry().getLoadType(), DataType::GenericMsgEnum ) << "VectorEntry::getLoadType()" ;
EXPECT_TRUE( true ) << "Vector::add( GenericMsg ) while GenericMsg is populated - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector::add( GenericMsg ) while GenericMsg is populated - exception not expected" ;
}
try
{
Vector container;
GenericMsg msg;
container.summaryData( msg );
container.complete();
EXPECT_FALSE( true ) << "Vector::summaryData( GenericMsg ) while GenericMsg is empty - exception expected" ;
}
catch ( const OmmException& )
{
EXPECT_TRUE( true ) << "Vector::summaryData( GenericMsg ) while GenericMsg is empty - exception expected" ;
}
try
{
Vector container;
GenericMsg msg;
msg.streamId( 10 );
container.summaryData( msg );
container.complete();
StaticDecoder::setData( &container, 0 );
EXPECT_TRUE( true ) << "Vector::summaryData( GenericMsg ) while GenericMsg is populated - exception not expected" ;
}
catch ( const OmmException& )
{
EXPECT_FALSE( true ) << "Vector::summaryData( GenericMsg ) while GenericMsg is populated - exception not expected" ;
}
}
TEST(VectorTests, testVectorEmpty_Encode_Decode)
{
try
{
ElementList elementList;
elementList.info(1);
Vector vector;
vector.sortable(true).totalCountHint(0).complete();
elementList.info(5).addVector("1", vector).complete();
StaticDecoder::setData(&elementList, NULL);
EXPECT_TRUE(elementList.forth()) << "Check the first element list";
EXPECT_TRUE(elementList.getEntry().getName() == "1") << "Check the key name of the first element entry";
const Vector& vectorDec = elementList.getEntry().getVector();
EXPECT_TRUE(vectorDec.hasTotalCountHint()) << "Check has total count hint attribute";
EXPECT_TRUE(vectorDec.getSortable()) << "Check the sortable attribute";
EXPECT_TRUE(vectorDec.getTotalCountHint() == 0) << "Check the total count hint attribute";
EXPECT_FALSE(vectorDec.forth()) << "Check to make sure that there is no enty in Vector";
}
catch (const OmmException& exp)
{
EXPECT_FALSE(true) << "Fails to encode and decode empty Vector - exception not expected with text" << exp.getText().c_str();
}
}
TEST(VectorTests, testVectorEntryWithNoPayload_Encode_Decode)
{
try
{
EmaBuffer permissionData;
permissionData.setFrom("12345", 5);
EmaBuffer permissionData2;
permissionData2.setFrom("54321", 5);
Vector vector;
vector.totalCountHint(5)
.add(3, VectorEntry::InsertEnum)
.add(2, VectorEntry::SetEnum, permissionData)
.add(4, VectorEntry::UpdateEnum)
.add(0, VectorEntry::ClearEnum, permissionData2)
.add(1, VectorEntry::DeleteEnum)
.complete();
StaticDecoder::setData(&vector, NULL);
EXPECT_FALSE(vector.getSortable()) << "Check the sortable attribute";
EXPECT_TRUE(vector.hasTotalCountHint()) << "Check has total count hint attribute";
EXPECT_TRUE(vector.getTotalCountHint() == 5) << "Check the total count hint attribute";
EXPECT_TRUE(vector.forth()) << "Get the first Vector entry";
EXPECT_TRUE(vector.getEntry().getPosition() == 3) << "Check the position of the first entry";
EXPECT_TRUE(vector.getEntry().getAction() == VectorEntry::InsertEnum) << "Check the action of the first entry";
EXPECT_FALSE(vector.getEntry().hasPermissionData()) << "Check the has permission data of the first entry";
EXPECT_TRUE(vector.getEntry().getLoadType() == DataType::NoDataEnum) << "Check the load type of the first entry";
EXPECT_TRUE(vector.forth()) << "Get the second Vector entry";
EXPECT_TRUE(vector.getEntry().getPosition() == 2) << "Check the position of the second entry";
EXPECT_TRUE(vector.getEntry().getAction() == VectorEntry::SetEnum) << "Check the action of the second entry";
EXPECT_TRUE(vector.getEntry().hasPermissionData()) << "Check the has permission data of the second entry";
EXPECT_TRUE(vector.getEntry().getPermissionData() == permissionData) << "Check the permission data of the second entry";
EXPECT_TRUE(vector.getEntry().getLoadType() == DataType::NoDataEnum) << "Check the load type of the second entry";
EXPECT_TRUE(vector.forth()) << "Get the third Vector entry";
EXPECT_TRUE(vector.getEntry().getPosition() == 4) << "Check the position of the third entry";
EXPECT_TRUE(vector.getEntry().getAction() == VectorEntry::UpdateEnum) << "Check the action of the third entry";
EXPECT_FALSE(vector.getEntry().hasPermissionData()) << "Check the has permission data of the third entry";
EXPECT_TRUE(vector.getEntry().getLoadType() == DataType::NoDataEnum) << "Check the load type of the third entry";
EXPECT_TRUE(vector.forth()) << "Get the fourth Vector entry";
EXPECT_TRUE(vector.getEntry().getPosition() == 0) << "Check the position of the fourth entry";
EXPECT_TRUE(vector.getEntry().getAction() == VectorEntry::ClearEnum) << "Check the action of the fourth entry";
EXPECT_TRUE(vector.getEntry().hasPermissionData()) << "Check the has permission data of the fourth entry";
EXPECT_TRUE(vector.getEntry().getPermissionData() == permissionData2) << "Check the permission data of the fourth entry";
EXPECT_TRUE(vector.getEntry().getLoadType() == DataType::NoDataEnum) << "Check the load type of the fourth entry";
EXPECT_TRUE(vector.forth()) << "Get the fifth Vector entry";
EXPECT_TRUE(vector.getEntry().getPosition() == 1) << "Check the position of the fifth entry";
EXPECT_TRUE(vector.getEntry().getAction() == VectorEntry::DeleteEnum) << "Check the action of the fifth entry";
EXPECT_FALSE(vector.getEntry().hasPermissionData()) << "Check the has permission data of the fifth entry";
EXPECT_TRUE(vector.getEntry().getLoadType() == DataType::NoDataEnum) << "Check the load type of the fifth entry";
EXPECT_FALSE(vector.forth()) << "Check to make sure that there is no more enty in Vector";
}
catch (const OmmException& exp)
{
EXPECT_FALSE(true) << "Fails to encode and decode Vector - exception not expected with text" << exp.getText().c_str();
}
}
TEST(VectorTests, testVectorAddTotalCountAfterInitialized)
{
try
{
Vector vector;
vector.add(3, VectorEntry::InsertEnum).totalCountHint(5).complete();
}
catch (const OmmException& exp)
{
EXPECT_FALSE(false) << "Encode total count hint after Vector is initialized - exception expected with text" << exp.getText().c_str();
EXPECT_STREQ("Invalid attempt to call totalCountHint() when container is initialized.", exp.getText().c_str());
return;
}
EXPECT_TRUE(false) << "Encode total count hint after Vector is initialized - exception expected";
}
TEST(VectorTests, testVectorAddSummaryDataAfterInitialized)
{
try
{
FieldList summaryData;
summaryData.addUInt(1, 3056).complete();
Vector vector;
vector.add(2, VectorEntry::InsertEnum).summaryData(summaryData).complete();
}
catch (const OmmException& exp)
{
EXPECT_FALSE(false) << "Encode summary data after Vector is initialized - exception expected with text" << exp.getText().c_str();
EXPECT_STREQ("Invalid attempt to call summaryData() when container is initialized.", exp.getText().c_str());
return;
}
EXPECT_TRUE(false) << "Encode summary data after Vector is initialized - exception expected";
}
TEST(VectorTests, testVectorSetSortableAfterInitialized)
{
try
{
Vector vector;
vector.add(3, VectorEntry::UpdateEnum).sortable(true).complete();
}
catch (const OmmException& exp)
{
EXPECT_FALSE(false) << "Encode the sortable flag after Vector is initialized - exception expected with text" << exp.getText().c_str();
EXPECT_STREQ("Invalid attempt to call sortable() when container is initialized.", exp.getText().c_str());
return;
}
EXPECT_TRUE(false) << "Encode the sortable flag after Vector is initialized - exception expected";
}
TEST(VectorTests, testVectorAddMismatchEntryDataType_Encode)
{
try
{
FieldList fieldList;
fieldList.addUInt(1, 3056).complete();
Vector vector;
vector.totalCountHint(2).sortable(false)
.add(1, VectorEntry::InsertEnum, fieldList)
.add(2, VectorEntry::DeleteEnum)
.complete();
}
catch (const OmmException& exp)
{
EXPECT_FALSE(false) << "Fails to encode Vector with mistmatch entry type - exception expected with text" << exp.getText().c_str();
EXPECT_STREQ("Attempt to add an entry with a different DataType. Encode DataType as NoData while the expected DataType is FieldList", exp.getText().c_str());
}
}
TEST(VectorTests, testVectorAddEntryAfterCallingComplete_Encode)
{
try
{
FieldList fieldList;
fieldList.addUInt(1, 3056).complete();
Vector vector;
vector.totalCountHint(1).sortable(false).complete();
vector.add(1, VectorEntry::InsertEnum, fieldList);
}
catch (const OmmException& exp)
{
EXPECT_FALSE(false) << "Fails to encode Vector after the complete() is called - exception expected with text" << exp.getText().c_str();
EXPECT_STREQ("Attempt to add an entry after complete() was called.", exp.getText().c_str());
}
}
TEST(VectorTests, testVectorClear_Encode_Decode)
{
try
{
FieldList fieldList;
fieldList.addUInt(1, 3056).complete();
Vector vector;
EXPECT_EQ( vector.toString(), "\nDecoding of just encoded object in the same application is not supported\n") << "Vector.toString() == Decoding of just encoded object in the same application is not supported";
vector.totalCountHint(1).sortable(false)
.add(1, VectorEntry::InsertEnum, fieldList)
.clear().sortable(true)
.add(2, VectorEntry::DeleteEnum)
.add(3, VectorEntry::ClearEnum)
.complete();
EXPECT_EQ( vector.toString(), "\nDecoding of just encoded object in the same application is not supported\n") << "Vector.toString() == Decoding of just encoded object in the same application is not supported";
StaticDecoder::setData(&vector, NULL);
EXPECT_NE( vector.toString(), "\nDecoding of just encoded object in the same application is not supported\n") << "Vector.toString() != Decoding of just encoded object in the same application is not supported";
EXPECT_FALSE(vector.hasTotalCountHint()) << "Check has total count hint attribute";
EXPECT_TRUE(vector.getSortable()) << "Check the sortable attribute";
EXPECT_TRUE(vector.forth()) << "Get the first Vector entry";
EXPECT_TRUE(vector.getEntry().getPosition() == 2) << "Check the position of the first entry";
EXPECT_TRUE(vector.getEntry().getAction() == VectorEntry::DeleteEnum) << "Check the action of the first entry";
EXPECT_FALSE(vector.getEntry().hasPermissionData()) << "Check the has permission data of the first entry";
EXPECT_TRUE(vector.getEntry().getLoadType() == DataType::NoDataEnum) << "Check the load type of the first entry";
EXPECT_TRUE(vector.forth()) << "Get the second Vector entry";
EXPECT_TRUE(vector.getEntry().getPosition() == 3) << "Check the position of the second entry";
EXPECT_TRUE(vector.getEntry().getAction() == VectorEntry::ClearEnum) << "Check the action of the second entry";
EXPECT_FALSE(vector.getEntry().hasPermissionData()) << "Check the has permission data of the second entry";
EXPECT_TRUE(vector.getEntry().getLoadType() == DataType::NoDataEnum) << "Check the load type of the second entry";
EXPECT_FALSE(vector.forth()) << "Check to make sure that there is no more enty in Vector";
}
catch (const OmmException& exp)
{
EXPECT_FALSE(true) << "Fails to encode and decode Vector - exception not expected with text" << exp.getText().c_str();
}
}
TEST(VectorTests, testVectorWithSummaryDataButNoEntry_Encode_Decode)
{
// load dictionary for decoding of the field list
RsslDataDictionary dictionary;
ASSERT_TRUE(loadDictionaryFromFile(&dictionary)) << "Failed to load dictionary";
try
{
FieldList summaryData;
summaryData.addUInt(1, 3056).addEnum(15, 840).addDate(3386, 2018, 2, 28).complete();
Vector vector;
vector.totalCountHint(0).summaryData(summaryData).complete();
ElementList elementList;
elementList.info(1);
elementList.addVector("1", vector).complete();
StaticDecoder::setData(&elementList, &dictionary);
EXPECT_TRUE(elementList.forth());
EXPECT_TRUE(elementList.getEntry().getVector().getTotalCountHint() == 0) << "Check key total count hint from Vector";
const FieldList& decodeFieldList = elementList.getEntry().getVector().getSummaryData().getFieldList();
EXPECT_TRUE(decodeFieldList.forth());
EXPECT_TRUE(decodeFieldList.getEntry().getFieldId() == 1) << "Check the field ID of the first field entry";
EXPECT_TRUE(decodeFieldList.getEntry().getUInt() == 3056) << "Check the value of the first field entry";
EXPECT_TRUE(decodeFieldList.forth());
EXPECT_TRUE(decodeFieldList.getEntry().getFieldId() == 15) << "Check the field ID of the second field entry";
EXPECT_TRUE(decodeFieldList.getEntry().getEnum() == 840) << "Check the value of the second field entry";
EXPECT_TRUE(decodeFieldList.forth());
EXPECT_TRUE(decodeFieldList.getEntry().getFieldId() == 3386) << "Check the field ID of the third field entry";
EXPECT_TRUE(decodeFieldList.getEntry().getDate().getYear() == 2018) << "Check the year value of the third field entry";
EXPECT_TRUE(decodeFieldList.getEntry().getDate().getMonth() == 2) << "Check the month value of the third field entry";
EXPECT_TRUE(decodeFieldList.getEntry().getDate().getDay() == 28) << "Check the day value of the third field entry";
EXPECT_FALSE(decodeFieldList.forth()) << "Check whether this is an entry from FieldList";
EXPECT_FALSE(elementList.getEntry().getVector().forth()) << "Check whether this is an entry from Vector";
EXPECT_FALSE(elementList.forth()) << "Check whether this is an entry from ElementList";
}
catch (const OmmException& exp)
{
EXPECT_TRUE(false) << "Fails to encode summary data but no entry - exception not expected with text : " << exp.getText().c_str();
return;
}
}
| 38.735319 | 211 | 0.709331 | [
"object",
"vector"
] |
ff35c176b845b6ee9380a69684215db3103924a6 | 3,280 | cpp | C++ | Modules/TArc/Sources/TArc/Controls/Private/ReflectedButton.cpp | reven86/dava.engine | ca47540c8694668f79774669b67d874a30188c20 | [
"BSD-3-Clause"
] | 5 | 2020-02-11T12:04:17.000Z | 2022-01-30T10:18:29.000Z | Modules/TArc/Sources/TArc/Controls/Private/ReflectedButton.cpp | reven86/dava.engine | ca47540c8694668f79774669b67d874a30188c20 | [
"BSD-3-Clause"
] | null | null | null | Modules/TArc/Sources/TArc/Controls/Private/ReflectedButton.cpp | reven86/dava.engine | ca47540c8694668f79774669b67d874a30188c20 | [
"BSD-3-Clause"
] | 4 | 2019-11-28T19:24:34.000Z | 2021-08-24T19:12:50.000Z | #include "TArc/Controls/ReflectedButton.h"
#include <Base/FastName.h>
#include <Reflection/ReflectedMeta.h>
namespace DAVA
{
namespace TArc
{
ReflectedButton::ReflectedButton(const Params& params, DataWrappersProcessor* wrappersProcessor, Reflection model, QWidget* parent)
: ControlProxyImpl<QToolButton>(params, params.fields, wrappersProcessor, model, parent)
{
SetupControl();
}
ReflectedButton::ReflectedButton(const Params& params, ContextAccessor* accessor, Reflection model, QWidget* parent)
: ControlProxyImpl<QToolButton>(params, params.fields, accessor, model, parent)
{
SetupControl();
}
void ReflectedButton::SetupControl()
{
setToolButtonStyle(Qt::ToolButtonIconOnly);
setAutoRaise(autoRaise);
setEnabled(true);
connections.AddConnection(this, &QToolButton::released, MakeFunction(this, &ReflectedButton::ButtonReleased));
}
void ReflectedButton::UpdateControl(const ControlDescriptor& changedFields)
{
if (changedFields.IsChanged(Fields::Visible) == true)
{
setVisible(GetFieldValue<bool>(Fields::Visible, false));
}
if (changedFields.IsChanged(Fields::Icon) == true)
{
icon = GetFieldValue<QIcon>(Fields::Icon, QIcon());
}
if (changedFields.IsChanged(Fields::Text) == true)
{
text = GetFieldValue<QString>(Fields::Text, QString());
}
setIcon(icon);
setText(text);
if (changedFields.IsChanged(Fields::Tooltip) == true)
{
QString tooltip = GetFieldValue<QString>(Fields::Tooltip, QString());
setToolTip(tooltip);
}
if (changedFields.IsChanged(Fields::IconSize) == true)
{
QSize iconSize = GetFieldValue<QSize>(Fields::IconSize, QSize(16, 16));
setIconSize(iconSize);
}
if (icon.isNull() == false && text.isEmpty() == false)
{
setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
}
else if (icon.isNull() == false)
{
setToolButtonStyle(Qt::ToolButtonIconOnly);
}
else if (text.isEmpty() == false)
{
setToolButtonStyle(Qt::ToolButtonTextOnly);
}
else
{
DVASSERT(false);
}
if (changedFields.IsChanged(Fields::AutoRaise) == true)
{
autoRaise = GetFieldValue<bool>(Fields::AutoRaise, true);
}
setAutoRaise(autoRaise);
if (changedFields.IsChanged(Fields::Enabled) == true)
{
bool enabled = GetFieldValue<bool>(Fields::Enabled, true);
setEnabled(enabled);
}
}
void ReflectedButton::ButtonReleased()
{
AnyFn method = model.GetMethod(GetFieldName(Fields::Clicked).c_str());
DVASSERT(method.IsValid());
const AnyFn::Params& params = method.GetInvokeParams();
const Type* retType = params.retType;
Vector<const Type*> argsType = params.argsType;
if (argsType.empty())
{
Reflection resultValue = model.GetField(GetFieldName(Fields::Result));
if (retType != nullptr && resultValue.IsValid())
{
Any result = method.Invoke();
wrapper.SetFieldValue(GetFieldName(Fields::Result), result);
}
else
{
method.Invoke();
}
}
else
{
DVASSERT(false, "We could invoke only methods without arguments");
}
}
} // namespace TArc
} // namespace DAVA
| 26.885246 | 131 | 0.657317 | [
"vector",
"model"
] |
ff37d01a4ee5254eb12eb1fe1b38191c64c6aeff | 42,111 | cpp | C++ | src/ngraph/runtime/cpu/builder/quantized_conv.cpp | magrawal128/ngraph | ca911487d1eadfe6ec66dbe3da6f05cee3645b24 | [
"Apache-2.0"
] | 1 | 2019-12-27T05:47:23.000Z | 2019-12-27T05:47:23.000Z | src/ngraph/runtime/cpu/builder/quantized_conv.cpp | biswajitcsecu/ngraph | d6bff37d7968922ef81f3bed63379e849fcf3b45 | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/cpu/builder/quantized_conv.cpp | biswajitcsecu/ngraph | d6bff37d7968922ef81f3bed63379e849fcf3b45 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "ngraph/op/constant.hpp"
#include "ngraph/op/experimental/quantized_conv_bias.hpp"
#include "ngraph/op/experimental/quantized_conv_relu.hpp"
#include "ngraph/op/quantized_convolution.hpp"
#include "ngraph/runtime/cpu/cpu_builder.hpp"
#include "ngraph/runtime/cpu/cpu_executor.hpp"
#include "ngraph/runtime/cpu/kernel/convolution.hpp"
#include "ngraph/runtime/cpu/mkldnn_invoke.hpp"
#include "ngraph/runtime/cpu/mkldnn_utils.hpp"
using namespace std;
using namespace ngraph;
namespace ngraph
{
namespace runtime
{
namespace cpu
{
template <>
void Builder::BUILDER_DECL(ngraph::op::QuantizedConvolution)
{
auto qconvolution = static_cast<const ngraph::op::QuantizedConvolution*>(node);
auto& functors = external_function->get_functors();
auto arg0_shape = args[0].get_shape();
auto arg1_shape = args[1].get_shape();
auto result_shape = out[0].get_shape();
auto arg0_buffer_index = external_function->get_buffer_index(args[0].get_name());
auto arg1_buffer_index = external_function->get_buffer_index(args[1].get_name());
auto arg2_buffer_index =
external_function->get_buffer_index(args[2].get_name()); // input scale
auto arg4_buffer_index =
external_function->get_buffer_index(args[4].get_name()); // filter scale
auto arg6_buffer_index =
external_function->get_buffer_index(args[6].get_name()); // output scale
auto out0_buffer_index = external_function->get_buffer_index(out[0].get_name());
auto scales_size = shape_size(args[2].get_shape());
if (runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node))
{
auto& mkldnn_emitter = external_function->get_mkldnn_emitter();
auto conv_desc =
mkldnn_emitter
->get_convolution_forward_desc<ngraph::op::QuantizedConvolution>(node);
auto conv_attr =
mkldnn_emitter
->get_convolution_forward_attr<ngraph::op::QuantizedConvolution>(node);
size_t scratchpad_size =
QUERY_SCRATCHPAD_2ARGS(convolution_forward, conv_desc, conv_attr);
size_t conv_index = mkldnn_emitter->convolution_forward_init();
auto& deps = mkldnn_emitter->get_primitive_deps(conv_index);
auto functor = [&,
conv_desc,
conv_attr,
deps,
conv_index,
scratchpad_size,
arg0_buffer_index,
arg1_buffer_index,
arg2_buffer_index,
arg4_buffer_index,
arg6_buffer_index,
out0_buffer_index](CPURuntimeContext* ctx,
CPUExecutionContext* /* ectx */) mutable {
// Create MKLDNN convolution primitive during the first iteration.
// Assumes the scales dont change for the duration of the graph
if (ctx->first_iteration)
{
vector<float> dyn_scales;
// Calculate the requantization scale
dyn_scales.push_back(
*(static_cast<float*>(ctx->buffer_data[arg2_buffer_index])) *
*(static_cast<float*>(ctx->buffer_data[arg4_buffer_index])) /
*(static_cast<float*>(ctx->buffer_data[arg6_buffer_index])));
// use conv channelwise (dim 1, mask=2^1) if dyn_scales is a vector
conv_attr.set_output_scales(0, dyn_scales);
mkldnn_emitter->build_convolution_forward<false>(
ctx->mkldnn_memories,
ctx->mkldnn_primitives,
ctx->mkldnn_scratchpad_mds,
conv_desc,
conv_attr,
executor::global_cpu_engine,
deps,
conv_index);
}
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[0], ctx->buffer_data[arg0_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[1], ctx->buffer_data[arg1_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[2], ctx->buffer_data[out0_buffer_index]);
cpu::mkldnn_utils::mkldnn_invoke_primitive(
ctx,
conv_index,
deps,
cpu::mkldnn_utils::OpType::QUANTIZEDCONVOLUTION,
scratchpad_size);
};
functors.emplace_back(functor);
}
else if (args[0].get_element_type() == element::u8 &&
args[1].get_element_type() == element::u8 &&
out[0].get_element_type() == element::u8)
{
std::function<decltype(
runtime::cpu::kernel::convolution<uint8_t, uint8_t, uint8_t, int32_t>)>
kernel;
kernel = runtime::cpu::kernel::convolution<uint8_t, uint8_t, uint8_t, int32_t>;
auto arg3_buffer_index =
external_function->get_buffer_index(args[3].get_name()); // input scale
auto arg5_buffer_index =
external_function->get_buffer_index(args[5].get_name()); // filter scale
auto arg7_buffer_index =
external_function->get_buffer_index(args[7].get_name()); // output scale
auto window_movement_strides = qconvolution->get_window_movement_strides();
auto window_dilation_strides = qconvolution->get_window_dilation_strides();
auto padding_below = qconvolution->get_padding_below();
auto padding_above = qconvolution->get_padding_above();
auto data_dilation_strides = qconvolution->get_data_dilation_strides();
auto functor = [&,
kernel,
arg0_shape,
arg1_shape,
arg0_buffer_index,
arg1_buffer_index,
arg2_buffer_index,
arg3_buffer_index,
arg4_buffer_index,
arg5_buffer_index,
arg6_buffer_index,
arg7_buffer_index,
out0_buffer_index,
result_shape,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides,
scales_size](CPURuntimeContext* ctx,
CPUExecutionContext* /* ectx */) {
vector<float> dyn_scales;
dyn_scales.assign(static_cast<float*>(ctx->buffer_data[arg2_buffer_index]),
static_cast<float*>(ctx->buffer_data[arg2_buffer_index]) +
scales_size);
kernel(ctx->buffer_data[arg0_buffer_index],
ctx->buffer_data[arg1_buffer_index],
ctx->buffer_data[out0_buffer_index],
arg0_shape,
arg1_shape,
result_shape,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides,
ctx->buffer_data[arg2_buffer_index],
ctx->buffer_data[arg3_buffer_index],
ctx->buffer_data[arg4_buffer_index],
ctx->buffer_data[arg5_buffer_index],
ctx->buffer_data[arg6_buffer_index],
ctx->buffer_data[arg7_buffer_index]);
};
functors.emplace_back(functor);
}
else if (args[0].get_element_type() == element::u8 &&
args[1].get_element_type() == element::u8 &&
out[0].get_element_type() == element::i32)
{
std::function<decltype(
runtime::cpu::kernel::convolution<uint8_t, uint8_t, int32_t, int32_t>)>
kernel;
kernel = runtime::cpu::kernel::convolution<uint8_t, uint8_t, int32_t, int32_t>;
auto arg3_buffer_index =
external_function->get_buffer_index(args[3].get_name()); // input scale
auto arg5_buffer_index =
external_function->get_buffer_index(args[5].get_name()); // filter scale
auto arg7_buffer_index =
external_function->get_buffer_index(args[7].get_name()); // output scale
auto window_movement_strides = qconvolution->get_window_movement_strides();
auto window_dilation_strides = qconvolution->get_window_dilation_strides();
auto padding_below = qconvolution->get_padding_below();
auto padding_above = qconvolution->get_padding_above();
auto data_dilation_strides = qconvolution->get_data_dilation_strides();
auto functor = [&,
kernel,
arg0_shape,
arg1_shape,
arg0_buffer_index,
arg1_buffer_index,
arg2_buffer_index,
arg3_buffer_index,
arg4_buffer_index,
arg5_buffer_index,
arg6_buffer_index,
arg7_buffer_index,
out0_buffer_index,
result_shape,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides,
scales_size](CPURuntimeContext* ctx,
CPUExecutionContext* /* ectx */) {
vector<float> dyn_scales;
dyn_scales.assign(static_cast<float*>(ctx->buffer_data[arg2_buffer_index]),
static_cast<float*>(ctx->buffer_data[arg2_buffer_index]) +
scales_size);
kernel(ctx->buffer_data[arg0_buffer_index],
ctx->buffer_data[arg1_buffer_index],
ctx->buffer_data[out0_buffer_index],
arg0_shape,
arg1_shape,
result_shape,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides,
ctx->buffer_data[arg2_buffer_index],
ctx->buffer_data[arg3_buffer_index],
ctx->buffer_data[arg4_buffer_index],
ctx->buffer_data[arg5_buffer_index],
ctx->buffer_data[arg6_buffer_index],
ctx->buffer_data[arg7_buffer_index]);
};
functors.emplace_back(functor);
}
else if (args[0].get_element_type() == element::u8 &&
args[1].get_element_type() == element::i8 &&
out[0].get_element_type() == element::i32)
{
std::function<decltype(
runtime::cpu::kernel::convolution<uint8_t, int8_t, int32_t, int32_t>)>
kernel;
kernel = runtime::cpu::kernel::convolution<uint8_t, int8_t, int32_t, int32_t>;
auto arg3_buffer_index =
external_function->get_buffer_index(args[3].get_name()); // input scale
auto arg5_buffer_index =
external_function->get_buffer_index(args[5].get_name()); // filter scale
auto arg7_buffer_index =
external_function->get_buffer_index(args[7].get_name()); // output scale
auto window_movement_strides = qconvolution->get_window_movement_strides();
auto window_dilation_strides = qconvolution->get_window_dilation_strides();
auto padding_below = qconvolution->get_padding_below();
auto padding_above = qconvolution->get_padding_above();
auto data_dilation_strides = qconvolution->get_data_dilation_strides();
auto functor = [&,
kernel,
arg0_shape,
arg1_shape,
arg0_buffer_index,
arg1_buffer_index,
arg2_buffer_index,
arg3_buffer_index,
arg4_buffer_index,
arg5_buffer_index,
arg6_buffer_index,
arg7_buffer_index,
out0_buffer_index,
result_shape,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides,
scales_size](CPURuntimeContext* ctx,
CPUExecutionContext* /* ectx */) {
vector<float> dyn_scales;
dyn_scales.assign(static_cast<float*>(ctx->buffer_data[arg2_buffer_index]),
static_cast<float*>(ctx->buffer_data[arg2_buffer_index]) +
scales_size);
kernel(ctx->buffer_data[arg0_buffer_index],
ctx->buffer_data[arg1_buffer_index],
ctx->buffer_data[out0_buffer_index],
arg0_shape,
arg1_shape,
result_shape,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides,
ctx->buffer_data[arg2_buffer_index],
ctx->buffer_data[arg3_buffer_index],
ctx->buffer_data[arg4_buffer_index],
ctx->buffer_data[arg5_buffer_index],
ctx->buffer_data[arg6_buffer_index],
ctx->buffer_data[arg7_buffer_index]);
};
functors.emplace_back(functor);
}
}
template <>
void Builder::BUILDER_DECL(ngraph::op::QuantizedConvolutionRelu)
{
if (runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node))
{
auto& functors = external_function->get_functors();
auto arg0_buffer_index =
external_function->get_buffer_index(args[0].get_name());
auto arg1_buffer_index =
external_function->get_buffer_index(args[1].get_name());
auto arg2_buffer_index =
external_function->get_buffer_index(args[2].get_name());
auto out0_buffer_index = external_function->get_buffer_index(out[0].get_name());
auto& mkldnn_emitter = external_function->get_mkldnn_emitter();
auto scales_size = shape_size(args[2].get_shape());
auto conv_desc =
mkldnn_emitter
->get_convolution_forward_desc<ngraph::op::QuantizedConvolutionRelu>(
node);
auto conv_attr =
mkldnn_emitter
->get_convolution_forward_attr<ngraph::op::QuantizedConvolutionRelu>(
node);
size_t scratchpad_size =
QUERY_SCRATCHPAD_2ARGS(convolution_forward, conv_desc, conv_attr);
size_t conv_index = mkldnn_emitter->convolution_forward_init();
auto& deps = mkldnn_emitter->get_primitive_deps(conv_index);
auto functor = [&,
scales_size,
conv_desc,
conv_attr,
deps,
conv_index,
scratchpad_size,
arg0_buffer_index,
arg1_buffer_index,
arg2_buffer_index,
out0_buffer_index](CPURuntimeContext* ctx,
CPUExecutionContext* /* ectx */) mutable {
if (ctx->first_iteration)
{
vector<float> dyn_scales;
dyn_scales.assign(
static_cast<float*>(ctx->buffer_data[arg2_buffer_index]),
static_cast<float*>(ctx->buffer_data[arg2_buffer_index]) +
scales_size);
// use conv channelwise (dim 1, mask=2^1) if dyn_scales is a vector
const int mask = scales_size == 1 ? 0 : 2;
conv_attr.set_output_scales(mask, dyn_scales);
mkldnn_emitter->build_convolution_forward<false>(
ctx->mkldnn_memories,
ctx->mkldnn_primitives,
ctx->mkldnn_scratchpad_mds,
conv_desc,
conv_attr,
executor::global_cpu_engine,
deps,
conv_index);
}
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[0], ctx->buffer_data[arg0_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[1], ctx->buffer_data[arg1_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[2], ctx->buffer_data[out0_buffer_index]);
cpu::mkldnn_utils::mkldnn_invoke_primitive(
ctx,
conv_index,
deps,
cpu::mkldnn_utils::OpType::QUANTIZEDCONVOLUTIONRELU,
scratchpad_size);
};
functors.emplace_back(functor);
}
else
{
throw ngraph_error(
"unsupported parameters for QuantizedConvolutionRelu via DEX");
}
}
template <>
void Builder::BUILDER_DECL(ngraph::op::QuantizedConvolutionBias)
{
if (runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node))
{
auto& functors = external_function->get_functors();
auto arg0_buffer_index =
external_function->get_buffer_index(args[0].get_name());
auto arg1_buffer_index =
external_function->get_buffer_index(args[1].get_name());
auto arg2_buffer_index =
external_function->get_buffer_index(args[2].get_name());
auto arg3_buffer_index =
external_function->get_buffer_index(args[3].get_name());
auto out0_buffer_index = external_function->get_buffer_index(out[0].get_name());
auto& mkldnn_emitter = external_function->get_mkldnn_emitter();
auto scales_size = shape_size(args[3].get_shape());
auto conv_desc =
mkldnn_emitter
->get_convolution_forward_desc<ngraph::op::QuantizedConvolutionBias>(
node);
auto conv_attr =
mkldnn_emitter
->get_convolution_forward_attr<ngraph::op::QuantizedConvolutionBias>(
node);
size_t scratchpad_size =
QUERY_SCRATCHPAD_2ARGS(convolution_forward, conv_desc, conv_attr);
size_t conv_index = mkldnn_emitter->convolution_forward_init(true);
auto& deps = mkldnn_emitter->get_primitive_deps(conv_index);
auto functor = [&,
scales_size,
conv_desc,
conv_attr,
deps,
conv_index,
scratchpad_size,
arg0_buffer_index,
arg1_buffer_index,
arg2_buffer_index,
arg3_buffer_index,
out0_buffer_index](CPURuntimeContext* ctx,
CPUExecutionContext* /* ectx */) mutable {
if (ctx->first_iteration)
{
vector<float> dyn_scales;
dyn_scales.assign(
static_cast<float*>(ctx->buffer_data[arg3_buffer_index]),
static_cast<float*>(ctx->buffer_data[arg3_buffer_index]) +
scales_size);
// use conv channelwise (dim 1, mask=2^1) if dyn_scales is a vector
const int mask = scales_size == 1 ? 0 : 2;
conv_attr.set_output_scales(mask, dyn_scales);
mkldnn_emitter->build_convolution_forward<true>(
ctx->mkldnn_memories,
ctx->mkldnn_primitives,
ctx->mkldnn_scratchpad_mds,
conv_desc,
conv_attr,
executor::global_cpu_engine,
deps,
conv_index);
}
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[0], ctx->buffer_data[arg0_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[1], ctx->buffer_data[arg1_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[2], ctx->buffer_data[arg2_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[3], ctx->buffer_data[out0_buffer_index]);
cpu::mkldnn_utils::mkldnn_invoke_primitive(
ctx,
conv_index,
deps,
cpu::mkldnn_utils::OpType::QUANTIZEDCONVOLUTIONBIAS,
scratchpad_size);
};
functors.emplace_back(functor);
}
else
{
throw ngraph_error(
"unsupported parameters for QuantizedConvolutionBias via DEX");
}
}
template <>
void Builder::BUILDER_DECL(ngraph::op::QuantizedConvolutionBiasAdd)
{
if (runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node))
{
auto& functors = external_function->get_functors();
auto arg0_buffer_index =
external_function->get_buffer_index(args[0].get_name());
auto arg1_buffer_index =
external_function->get_buffer_index(args[1].get_name());
auto arg2_buffer_index =
external_function->get_buffer_index(args[2].get_name());
auto arg3_buffer_index =
external_function->get_buffer_index(args[3].get_name());
auto arg4_buffer_index =
external_function->get_buffer_index(args[4].get_name());
auto arg5_buffer_index =
external_function->get_buffer_index(args[5].get_name());
auto out0_buffer_index = external_function->get_buffer_index(out[0].get_name());
size_t arg3_size = node->input(3).get_tensor().size();
auto scales_size = shape_size(args[4].get_shape());
auto sum_scales_size = shape_size(args[5].get_shape());
auto& mkldnn_emitter = external_function->get_mkldnn_emitter();
auto conv_desc =
mkldnn_emitter
->get_convolution_forward_desc<ngraph::op::QuantizedConvolutionBiasAdd>(
node);
auto conv_attr =
mkldnn_emitter
->get_convolution_forward_attr<ngraph::op::QuantizedConvolutionBiasAdd>(
node);
size_t scratchpad_size =
QUERY_SCRATCHPAD_2ARGS(convolution_forward, conv_desc, conv_attr);
size_t conv_index = mkldnn_emitter->convolution_forward_init(true);
auto& deps = mkldnn_emitter->get_primitive_deps(conv_index);
auto functor = [&,
scales_size,
sum_scales_size,
conv_desc,
conv_attr,
deps,
conv_index,
scratchpad_size,
arg3_size,
arg0_buffer_index,
arg1_buffer_index,
arg2_buffer_index,
arg3_buffer_index,
arg4_buffer_index,
arg5_buffer_index,
out0_buffer_index](CPURuntimeContext* ctx,
CPUExecutionContext* /* ectx */) mutable {
if (ctx->first_iteration)
{
vector<float> dyn_scales;
vector<float> dyn_post_op_scales;
dyn_scales.assign(
static_cast<float*>(ctx->buffer_data[arg4_buffer_index]),
static_cast<float*>(ctx->buffer_data[arg4_buffer_index]) +
scales_size);
dyn_post_op_scales.assign(
static_cast<float*>(ctx->buffer_data[arg5_buffer_index]),
static_cast<float*>(ctx->buffer_data[arg5_buffer_index]) +
sum_scales_size);
auto old_pops = conv_attr.get_post_ops();
mkldnn::post_ops new_pops;
for (int i = 0; i < old_pops.len(); i++)
{
if (old_pops.kind(i) == mkldnn::primitive::kind::eltwise)
{
mkldnn::algorithm alg;
float scale, alpha, beta;
old_pops.get_params_eltwise(i, scale, alg, alpha, beta);
new_pops.append_eltwise(scale, alg, alpha, beta);
}
if (old_pops.kind(i) == mkldnn::primitive::kind::sum)
{
new_pops.append_sum(dyn_post_op_scales[0]);
}
}
// use conv channelwise (dim 1, mask=2^1) if dyn_scales is a vector
const int mask = scales_size == 1 ? 0 : 2;
conv_attr.set_output_scales(mask, dyn_scales);
conv_attr.set_post_ops(new_pops);
mkldnn_emitter->build_convolution_forward<true>(
ctx->mkldnn_memories,
ctx->mkldnn_primitives,
ctx->mkldnn_scratchpad_mds,
conv_desc,
conv_attr,
executor::global_cpu_engine,
deps,
conv_index);
}
if (ctx->buffer_data[out0_buffer_index] !=
ctx->buffer_data[arg3_buffer_index])
{
memcpy(static_cast<char*>(ctx->buffer_data[out0_buffer_index]),
static_cast<char*>(ctx->buffer_data[arg3_buffer_index]),
arg3_size);
}
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[0], ctx->buffer_data[arg0_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[1], ctx->buffer_data[arg1_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[2], ctx->buffer_data[arg2_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[3], ctx->buffer_data[out0_buffer_index]);
cpu::mkldnn_utils::mkldnn_invoke_primitive(
ctx,
conv_index,
deps,
cpu::mkldnn_utils::OpType::QUANTIZEDCONVOLUTIONBIASADD,
scratchpad_size);
};
functors.emplace_back(functor);
}
else
{
throw ngraph_error(
"unsupported parameters for QuantizedConvolutionBiasAdd via DEX");
}
}
template <>
void Builder::BUILDER_DECL(ngraph::op::QuantizedConvolutionBiasSignedAdd)
{
if (runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node))
{
auto& functors = external_function->get_functors();
auto arg0_buffer_index =
external_function->get_buffer_index(args[0].get_name());
auto arg1_buffer_index =
external_function->get_buffer_index(args[1].get_name());
auto arg2_buffer_index =
external_function->get_buffer_index(args[2].get_name());
auto arg3_buffer_index =
external_function->get_buffer_index(args[3].get_name());
auto arg4_buffer_index =
external_function->get_buffer_index(args[4].get_name());
auto arg5_buffer_index =
external_function->get_buffer_index(args[5].get_name());
auto out0_buffer_index = external_function->get_buffer_index(out[0].get_name());
size_t arg3_size = node->input(3).get_tensor().size();
auto scales_size = shape_size(args[4].get_shape());
auto sum_scales_size = shape_size(args[5].get_shape());
auto& mkldnn_emitter = external_function->get_mkldnn_emitter();
auto conv_desc = mkldnn_emitter->get_convolution_forward_desc<
ngraph::op::QuantizedConvolutionBiasSignedAdd>(node);
auto conv_attr = mkldnn_emitter->get_convolution_forward_attr<
ngraph::op::QuantizedConvolutionBiasSignedAdd>(node);
size_t scratchpad_size =
QUERY_SCRATCHPAD_2ARGS(convolution_forward, conv_desc, conv_attr);
size_t conv_index = mkldnn_emitter->convolution_forward_init(true);
auto& deps = mkldnn_emitter->get_primitive_deps(conv_index);
auto functor = [&,
scales_size,
sum_scales_size,
conv_desc,
conv_attr,
deps,
conv_index,
scratchpad_size,
arg3_size,
arg0_buffer_index,
arg1_buffer_index,
arg2_buffer_index,
arg3_buffer_index,
arg4_buffer_index,
arg5_buffer_index,
out0_buffer_index](CPURuntimeContext* ctx,
CPUExecutionContext* /* ectx */) mutable {
if (ctx->first_iteration)
{
vector<float> dyn_scales;
vector<float> dyn_post_op_scales;
dyn_scales.assign(
static_cast<float*>(ctx->buffer_data[arg4_buffer_index]),
static_cast<float*>(ctx->buffer_data[arg4_buffer_index]) +
scales_size);
dyn_post_op_scales.assign(
static_cast<float*>(ctx->buffer_data[arg5_buffer_index]),
static_cast<float*>(ctx->buffer_data[arg5_buffer_index]) +
sum_scales_size);
auto old_pops = conv_attr.get_post_ops();
mkldnn::post_ops new_pops;
for (int i = 0; i < old_pops.len(); i++)
{
if (old_pops.kind(i) == mkldnn::primitive::kind::eltwise)
{
mkldnn::algorithm alg;
float scale, alpha, beta;
old_pops.get_params_eltwise(i, scale, alg, alpha, beta);
new_pops.append_eltwise(scale, alg, alpha, beta);
}
if (old_pops.kind(i) == mkldnn::primitive::kind::sum)
{
new_pops.append_sum(dyn_post_op_scales[0]);
}
}
conv_attr.set_post_ops(new_pops);
// use conv channelwise (dim 1, mask=2^1) if dyn_scales is a vector
const int mask = scales_size == 1 ? 0 : 2;
conv_attr.set_output_scales(mask, dyn_scales);
mkldnn_emitter->build_convolution_forward<true>(
ctx->mkldnn_memories,
ctx->mkldnn_primitives,
ctx->mkldnn_scratchpad_mds,
conv_desc,
conv_attr,
executor::global_cpu_engine,
deps,
conv_index);
}
if (ctx->buffer_data[out0_buffer_index] !=
ctx->buffer_data[arg3_buffer_index])
{
memcpy(static_cast<char*>(ctx->buffer_data[out0_buffer_index]),
static_cast<char*>(ctx->buffer_data[arg3_buffer_index]),
arg3_size);
}
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[0], ctx->buffer_data[arg0_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[1], ctx->buffer_data[arg1_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[2], ctx->buffer_data[arg2_buffer_index]);
cpu::mkldnn_utils::set_memory_ptr(
ctx, deps[3], ctx->buffer_data[out0_buffer_index]);
cpu::mkldnn_utils::mkldnn_invoke_primitive(
ctx,
conv_index,
deps,
cpu::mkldnn_utils::OpType::QUANTIZEDCONVOLUTIONBIASSIGNEDADD,
scratchpad_size);
};
functors.emplace_back(functor);
}
else
{
throw ngraph_error(
"unsupported parameters for QuantizedConvolutionBiasSignedAdd via DEX");
}
}
void register_builders_quantized_conv_cpp()
{
REGISTER_OP_BUILDER(QuantizedConvolution);
REGISTER_OP_BUILDER(QuantizedConvolutionRelu);
REGISTER_OP_BUILDER(QuantizedConvolutionBias);
REGISTER_OP_BUILDER(QuantizedConvolutionBiasAdd);
REGISTER_OP_BUILDER(QuantizedConvolutionBiasSignedAdd);
}
}
}
}
| 54.196911 | 100 | 0.442189 | [
"vector"
] |
ff3814e969b8c390cb18642c2474a072f3dbf2dc | 52,376 | cpp | C++ | Engine/Platforms/Vulkan/110/Vk1Device.cpp | azhirnov/GraphicsGenFramework-modular | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | 12 | 2017-12-23T14:24:57.000Z | 2020-10-02T19:52:12.000Z | Engine/Platforms/Vulkan/110/Vk1Device.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | Engine/Platforms/Vulkan/110/Vk1Device.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt'
#include "Core/Config/Engine.Config.h"
#ifdef GRAPHICS_API_VULKAN
#include "Engine/Platforms/Vulkan/110/Vk1Device.h"
#include "Engine/Platforms/Vulkan/110/vulkan1_utils.h"
#include "Engine/Platforms/Public/GPU/Framebuffer.h"
#include "Engine/Platforms/Public/GPU/RenderPass.h"
#include "Engine/Platforms/Public/GPU/CommandBuffer.h"
#include "Engine/Platforms/Vulkan/VulkanObjectsConstructor.h"
#include "Engine/Platforms/Vulkan/110/Vk1SwapchainImage.h"
namespace Engine
{
namespace PlatformVK
{
using namespace vk;
/*
=================================================
constructor
=================================================
*/
Vk1Device::Vk1Device (GlobalSystemsRef gs) :
BaseObject( gs ),
_logicalDevice( VK_NULL_HANDLE ),
_physicalDevice( VK_NULL_HANDLE ),
_instance( VK_NULL_HANDLE ),
_surface( VK_NULL_HANDLE ),
_swapchain( VK_NULL_HANDLE ),
_vsync( false ),
_depthStencilView( VK_NULL_HANDLE ),
_colorPixelFormat( EPixelFormat::Unknown ),
_depthStencilPixelFormat( EPixelFormat::Unknown ),
_colorFormat( VK_FORMAT_UNDEFINED ),
_colorSpace( VK_COLOR_SPACE_MAX_ENUM_KHR ),
_depthStencilFormat( VK_FORMAT_UNDEFINED ),
_queueFamilyIndex( UMax ),
_queueFamily(),
_currentImageIndex( UMax ),
_debugCallback( VK_NULL_HANDLE ),
_enableDebugMarkers( false ),
_primiryFunctionsLoaded( false ),
_isInstanceFunctionsLoaded( false ),
_isDeviceFunctionsLoaded( false ),
_debugReportCounter( 0 )
{
SetDebugName( "Vk1Device" );
_imageBuffers.Reserve( 8 );
}
/*
=================================================
destructor
=================================================
*/
Vk1Device::~Vk1Device ()
{
CHECK( not IsInstanceCreated() );
CHECK( not HasPhyiscalDevice() );
CHECK( not IsDeviceCreated() );
CHECK( not IsSurfaceCreated() );
CHECK( not IsSwapchainCreated() );
CHECK( not IsDebugCallbackCreated() );
if ( _debugReportCounter > 0 )
{
WARNING( "Threre are a few warnings, check debug output!" );
}
}
/*
=================================================
_LoadFunctions
=================================================
*/
bool Vk1Device::_LoadFunctions () const
{
bool load = (_isDeviceFunctionsLoaded != IsDeviceCreated() or
_isInstanceFunctionsLoaded != IsInstanceCreated() or
not _primiryFunctionsLoaded);
if ( load ) {
CHECK_ERR( Vk1_Init( _instance, _logicalDevice ) );
}
_primiryFunctionsLoaded = true;
_isInstanceFunctionsLoaded = IsInstanceCreated();
_isDeviceFunctionsLoaded = IsDeviceCreated();
return true;
}
/*
=================================================
_LoadInstanceLayers
=================================================
*/
bool Vk1Device::_LoadInstanceLayers () const
{
if ( not _instanceLayers.Empty() )
return true;
_LoadFunctions();
uint32_t count = 0;
VK_CALL( vkEnumerateInstanceLayerProperties( OUT &count, null ) );
if ( count == 0 ) {
_instanceLayers << VkLayerProperties{};
return true;
}
_instanceLayers.Resize( count );
VK_CALL( vkEnumerateInstanceLayerProperties( OUT &count, OUT _instanceLayers.ptr() ) );
return true;
}
/*
=================================================
_LoadInstanceExtensions
=================================================
*/
bool Vk1Device::_LoadInstanceExtensions () const
{
if ( not _instanceExtensions.Empty() )
return true;
_LoadFunctions();
uint32_t count = 0;
VK_CALL( vkEnumerateInstanceExtensionProperties( null, OUT &count, null ) );
if ( count == 0 ) {
_instanceExtensions << "";
return true;
}
Array< VkExtensionProperties > inst_ext;
inst_ext.Resize( count );
VK_CALL( vkEnumerateInstanceExtensionProperties( null, OUT &count, OUT inst_ext.ptr() ) );
for (auto& ext : inst_ext) {
_instanceExtensions.Add( StringCRef(ext.extensionName) );
}
return true;
}
/*
=================================================
CreateInstance
=================================================
*/
bool Vk1Device::CreateInstance (StringCRef applicationName, uint32_t applicationVersion,
uint32_t vulkanVersion, ExtensionNames_t ext, ValidationLayers_t layers)
{
CHECK_ERR( not IsInstanceCreated() );
_LoadFunctions();
VkApplicationInfo app_info = {};
VkInstanceCreateInfo instance_create_info = {};
Array< const char* > instance_layers = layers;
Array< const char* > instance_extensions = { VK_KHR_SURFACE_EXTENSION_NAME };
instance_extensions << ext;
CHECK_ERR( _CheckLayers( INOUT instance_layers ) );
CHECK_ERR( _CheckExtensions( INOUT instance_extensions ) );
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.apiVersion = vulkanVersion;
app_info.pApplicationName = applicationName.cstr();
app_info.applicationVersion = applicationVersion;
app_info.pEngineName = Engine::ENGINE_NAME;
app_info.engineVersion = Engine::ENGINE_VERSION;
instance_create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instance_create_info.pApplicationInfo = &app_info;
instance_create_info.enabledExtensionCount = uint32_t(instance_extensions.Count());
instance_create_info.ppEnabledExtensionNames = instance_extensions.RawPtr();
//instance_create_info.enabledLayerCount = uint32_t(instance_layers.Count());
//instance_create_info.ppEnabledLayerNames = instance_layers.RawPtr();
VK_CHECK( vkCreateInstance( &instance_create_info, null, OUT &_instance ) );
// update instance extensions
{
_instanceExtensions.Clear();
for (auto& ie : instance_extensions) {
_instanceExtensions << ie;
}
if ( _instanceExtensions.Empty() )
_instanceExtensions << "";
}
return true;
}
/*
=================================================
DestroyInstance
=================================================
*/
bool Vk1Device::DestroyInstance ()
{
if ( _instance == VK_NULL_HANDLE )
return true;
CHECK_ERR( not IsDeviceCreated() );
CHECK_ERR( not IsSurfaceCreated() );
CHECK_ERR( not IsSwapchainCreated() );
CHECK_ERR( not IsDebugCallbackCreated() );
vkDestroyInstance( _instance, null );
_physicalDevice = VK_NULL_HANDLE;
_instance = VK_NULL_HANDLE;
_isDeviceFunctionsLoaded = false;
_isInstanceFunctionsLoaded = false;
_primiryFunctionsLoaded = false;
_instanceLayers.Clear();
_instanceExtensions.Clear();
Vk1_Delete();
return true;
}
/*
=================================================
HasLayer
=================================================
*/
bool Vk1Device::HasLayer (StringCRef name) const
{
_LoadInstanceLayers();
// TODO: optimize search
FOR( i, _instanceLayers )
{
if ( name.EqualsIC( _instanceLayers[i].layerName ) )
return true;
}
return false;
}
/*
=================================================
HasExtension
=================================================
*/
bool Vk1Device::HasExtension (StringCRef name) const
{
_LoadInstanceExtensions();
return _instanceExtensions.IsExist( name );
}
/*
=================================================
CreateDebugCallback
=================================================
*/
bool Vk1Device::CreateDebugCallback (VkDebugReportFlagBitsEXT flags)
{
CHECK_ERR( IsInstanceCreated() );
CHECK_ERR( not IsDebugCallbackCreated() );
_LoadFunctions();
VkDebugReportCallbackCreateInfoEXT dbg_callback_info = {};
dbg_callback_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
dbg_callback_info.flags = flags;
dbg_callback_info.pfnCallback = &_DebugReportCallback;
dbg_callback_info.pUserData = this;
VK_CHECK( vkCreateDebugReportCallbackEXT( _instance, &dbg_callback_info, null, OUT &_debugCallback ) );
return true;
}
/*
=================================================
DestroyDebugCallback
=================================================
*/
bool Vk1Device::DestroyDebugCallback ()
{
if ( _debugCallback == VK_NULL_HANDLE )
return true;
CHECK_ERR( IsInstanceCreated() );
vkDestroyDebugReportCallbackEXT( _instance, _debugCallback, null );
_debugCallback = VK_NULL_HANDLE;
return true;
}
/*
=================================================
GetPhysicalDeviceInfo
=================================================
*/
bool Vk1Device::GetPhysicalDeviceInfo (OUT AppendableAdaptor<DeviceInfo> deviceInfo) const
{
CHECK_ERR( IsInstanceCreated() );
_LoadFunctions();
uint32_t count = 0;
Array< VkPhysicalDevice > devices;
Array< VkDisplayPropertiesKHR > display_props; display_props.Reserve( 8 );
VK_CALL( vkEnumeratePhysicalDevices( _instance, OUT &count, null ) );
CHECK_ERR( count > 0 );
devices.Resize( count );
VK_CALL( vkEnumeratePhysicalDevices( _instance, OUT &count, OUT devices.ptr() ) );
FOR( i, devices )
{
VkPhysicalDeviceProperties prop = {};
VkPhysicalDeviceFeatures feat = {};
VkPhysicalDeviceMemoryProperties mem_prop = {};
DeviceInfo info;
vkGetPhysicalDeviceProperties( devices[i], OUT &prop );
vkGetPhysicalDeviceFeatures( devices[i], OUT &feat );
vkGetPhysicalDeviceMemoryProperties( devices[i], OUT &mem_prop );
// vkGetPhysicalDeviceQueueFamilyProperties
// vkGetPhysicalDeviceSparseImageFormatProperties
// vkGetPhysicalDeviceDisplayPlanePropertiesKHR
// vkGetPhysicalDeviceFeatures2KHR
// vkGetPhysicalDeviceProperties2KHR
// vkGetPhysicalDeviceMemoryProperties2KHR
// vkGetPhysicalDeviceSparseImageFormatProperties2KHR
/*uint32_t prop_count = 0;
VK_CALL( vkGetPhysicalDeviceDisplayPropertiesKHR( devices[i], OUT &prop_count, null ) );
if ( prop_count > 0 )
{
display_props.Resize( prop_count );
VK_CALL( vkGetPhysicalDeviceDisplayPropertiesKHR( devices[i], OUT &prop_count, OUT display_props.ptr() ) );
FOR( j, display_props )
{
}
}*/
info.id = devices[i];
info.device = prop.deviceName;
info.version = prop.apiVersion;
info.integratedGPU = prop.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
info.isGPU = (prop.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU or
prop.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU);
info.isCPU = prop.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU;
info.maxInvocations = prop.limits.maxComputeWorkGroupInvocations;
info.supportsTesselation = feat.tessellationShader;
info.supportsGeometryShader = feat.geometryShader;
info.globalMemory = _CalcTotalMemory( mem_prop );
info.computeSharedMem = BytesU(prop.limits.maxComputeSharedMemorySize);
deviceInfo.PushBack( RVREF(info) );
}
return true;
}
/*
=================================================
CreatePhysicalDevice
=================================================
*/
bool Vk1Device::CreatePhysicalDevice (VkPhysicalDevice id)
{
CHECK_ERR( IsInstanceCreated() );
_LoadFunctions();
_physicalDevice = id;
vkGetPhysicalDeviceProperties( _physicalDevice, OUT &_deviceProperties );
vkGetPhysicalDeviceFeatures( _physicalDevice, OUT &_deviceFeatures );
vkGetPhysicalDeviceMemoryProperties( _physicalDevice, OUT &_deviceMemoryProperties );
_UpdateProperties();
return true;
}
/*
=================================================
_DeviceTypeToString
=================================================
*/
StringCRef Vk1Device::_DeviceTypeToString (VkPhysicalDeviceType value)
{
switch ( value )
{
case VK_PHYSICAL_DEVICE_TYPE_OTHER : return "Other";
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU : return "Intergrated GPU";
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU : return "Discrete GPU";
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU : return "Virtual GPU";
case VK_PHYSICAL_DEVICE_TYPE_CPU : return "CPU";
}
RETURN_ERR( "unknown physical device type!" );
}
/*
=================================================
_CalcTotalMemory
=================================================
*/
BytesU Vk1Device::_CalcTotalMemory (VkPhysicalDeviceMemoryProperties memProps)
{
BytesU total;
for (uint32_t j = 0; j < memProps.memoryTypeCount; ++j)
{
if ( EnumEq( memProps.memoryTypes[j].propertyFlags, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT ) )
{
const uint32_t idx = memProps.memoryTypes[j].heapIndex;
if ( EnumEq( memProps.memoryHeaps[idx].flags, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT ) )
{
total += BytesU( memProps.memoryHeaps[idx].size );
memProps.memoryHeaps[idx].size = 0;
}
}
}
return total;
}
/*
=================================================
_UpdateProperties
=================================================
*/
void Vk1Device::_UpdateProperties ()
{
_properties.maxComputeWorkGroupInvocations = _deviceProperties.limits.maxComputeWorkGroupInvocations;
_properties.maxComputeWorkGroupSize = ReferenceCast<uint3>(_deviceProperties.limits.maxComputeWorkGroupSize);
_properties.maxComputeWorkGroupCount = ReferenceCast<uint3>(_deviceProperties.limits.maxComputeWorkGroupCount);
_properties.explicitMemoryObjects = true;
}
/*
=================================================
WritePhysicalDeviceInfo
=================================================
*/
void Vk1Device::WritePhysicalDeviceInfo () const
{
CHECK_ERR( HasPhyiscalDevice(), void() );
struct ApiVersionBits {
uint patch : 12;
uint minor : 10;
uint major : 10;
};
const ApiVersionBits api_ver = ReferenceCast<ApiVersionBits>(_deviceProperties.apiVersion);
String str;
str << "Vulkan info\n---------------------";
str << "\nversion: " << api_ver.major <<'.'<< api_ver.minor <<'.'<< api_ver.patch;
str << "\ndevice name: " << _deviceProperties.deviceName;
str << "\ndevice type: " << _DeviceTypeToString( _deviceProperties.deviceType );
str << "\nglobal memory: " << ToString( _CalcTotalMemory( _deviceMemoryProperties ) );
str << "\npush constants: " << ToString( BytesU(_deviceProperties.limits.maxPushConstantsSize) );
str << "\nuniform buf size: " << ToString( BytesU(_deviceProperties.limits.maxUniformBufferRange) );
str << "\nstorage buf size: " << ToString( BytesU(_deviceProperties.limits.maxStorageBufferRange) );
str << "\nmax mem allocations: " << _deviceProperties.limits.maxMemoryAllocationCount;
str << "\nmax sampler allocations: " << _deviceProperties.limits.maxSamplerAllocationCount;
str << "\nper stage resources: " << _deviceProperties.limits.maxPerStageResources;
str << "\nmax color attachments: " << _deviceProperties.limits.maxColorAttachments;
str << "\nmax viewports: " << _deviceProperties.limits.maxViewports;
str << "\nmax anisotropy: " << _deviceProperties.limits.maxSamplerAnisotropy;
str << "\nmax tess gen level: " << _deviceProperties.limits.maxTessellationGenerationLevel;
str << "\nmax patch vertices: " << _deviceProperties.limits.maxTessellationPatchSize;
str << "\nmax attribs: " << _deviceProperties.limits.maxVertexInputAttributes;
str << "\nmax vb bindings: " << _deviceProperties.limits.maxVertexInputBindings;
// compute
str << "\ncompute shared mem: " << ToString( BytesU(_deviceProperties.limits.maxComputeSharedMemorySize) );
str << "\ncompute invocations: " << _deviceProperties.limits.maxComputeWorkGroupInvocations;
str << "\ncompute local size: " << ToString( ReferenceCast<uint3>(_deviceProperties.limits.maxComputeWorkGroupSize) );
str << "\ncompute work groups: " << ToString( ReferenceCast<uint3>(_deviceProperties.limits.maxComputeWorkGroupCount) );
str << "\n---------------------";
LOG( str, ELog::Info | ELog::SpoilerFlag );
}
/*
=================================================
CreateDevice
=================================================
*/
bool Vk1Device::CreateDevice (const VkPhysicalDeviceFeatures &enabledFeatures,
EQueueFamily::bits queueFamilies,
ExtensionNames_t enabledExtensions)
{
const bool useSwapchain = queueFamilies[ EQueueFamily::Present ];
CHECK_ERR( HasPhyiscalDevice() );
CHECK_ERR( useSwapchain == IsSurfaceCreated() );
CHECK_ERR( not IsDeviceCreated() );
Array< VkDeviceQueueCreateInfo > queue_infos;
Array< const char * > device_extensions = enabledExtensions;
VkDeviceCreateInfo device_info = {};
queue_infos.PushBack({});
CHECK_ERR( _GetQueueCreateInfo( OUT queue_infos.Back(), queueFamilies ) );
_queueFamily = queueFamilies;
_queueFamilyIndex = queue_infos.Back().queueFamilyIndex;
if ( _queueFamily[ EQueueFamily::Present ] )
device_extensions << VK_KHR_SWAPCHAIN_EXTENSION_NAME;
CHECK_ERR( _CheckDeviceExtensions( INOUT device_extensions ) );
_enableDebugMarkers = HasExtension( VK_EXT_DEBUG_MARKER_EXTENSION_NAME );
device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_info.queueCreateInfoCount = uint32_t(queue_infos.Count());
device_info.pQueueCreateInfos = queue_infos.ptr();
device_info.pEnabledFeatures = &enabledFeatures;
if ( not device_extensions.Empty() )
{
device_info.enabledExtensionCount = uint32_t(device_extensions.Count());
device_info.ppEnabledExtensionNames = device_extensions.RawPtr();
}
VK_CHECK( vkCreateDevice( _physicalDevice, &device_info, null, OUT &_logicalDevice ) );
if ( &_deviceFeatures != &enabledFeatures )
_deviceFeatures = enabledFeatures;
// reload function pointers for current device
_LoadFunctions();
// update device extensions
{
_deviceExtensions.Clear();
for (auto& de : device_extensions) {
_deviceExtensions << de;
}
if ( _deviceExtensions.Empty() )
_deviceExtensions << "";
}
// write extensions to log
{
String log = "Vulkan layers:";
FOR( i, _instanceLayers ) {
log << _instanceLayers[i].layerName << " (" << _instanceLayers[i].description << ")\n";
}
log << "\nVulkan instance extensions:";
FOR( i, _instanceExtensions ) {
log << (i ? ", " : "") << ((i&3) ? "" : "\n") << _instanceExtensions[i];
}
log << "\nVulkan device extensions:";
FOR( i, _deviceExtensions ) {
log << (i ? ", " : "") << ((i&3) ? "" : "\n") << _deviceExtensions[i];
}
log << "\n------------------------";
LOG( log, ELog::Info | ELog::SpoilerFlag );
}
return true;
}
/*
=================================================
DestroyDevice
=================================================
*/
bool Vk1Device::DestroyDevice ()
{
if ( _logicalDevice == VK_NULL_HANDLE )
return true;
CHECK_ERR( IsInstanceCreated() );
CHECK_ERR( not IsSwapchainCreated() );
vkDestroyDevice( _logicalDevice, null );
_logicalDevice = VK_NULL_HANDLE;
_queueFamilyIndex = UMax;
_queueFamily = EQueueFamily::bits();
// unload function pointers that spcified for destroyed device
_LoadFunctions();
_deviceExtensions.Clear();
return true;
}
/*
=================================================
DeviceWaitIdle
=================================================
*/
void Vk1Device::DeviceWaitIdle ()
{
ASSERT( IsDeviceCreated() );
// TODO: check device lost error
VK_CALL( vkDeviceWaitIdle( _logicalDevice ) );
}
/*
=================================================
CreateSwapchain
=================================================
*/
bool Vk1Device::CreateSwapchain (const uint2 &size, bool vsync, uint32_t imageArrayLayers, EPixelFormat::type depthStencilFormat, MultiSamples samples,
EImageUsage::bits colorImageUsage, EImageUsage::bits depthStencilImageUsage)
{
CHECK_ERR( HasPhyiscalDevice() );
CHECK_ERR( IsDeviceCreated() );
CHECK_ERR( IsSurfaceCreated() );
//CHECK_ERR( not IsSwapchainCreated() );
VkSurfaceCapabilitiesKHR surf_caps;
VK_CHECK( vkGetPhysicalDeviceSurfaceCapabilitiesKHR( _physicalDevice, _surface, OUT &surf_caps ) );
VkSwapchainKHR old_swapchain = _swapchain;
VkSwapchainCreateInfoKHR swapchain_info = {};
swapchain_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchain_info.pNext = null;
swapchain_info.surface = _surface;
swapchain_info.imageFormat = _colorFormat;
swapchain_info.imageColorSpace = _colorSpace;
swapchain_info.imageExtent = { size.x, size.y };
swapchain_info.imageArrayLayers = imageArrayLayers;
swapchain_info.queueFamilyIndexCount = 0;
swapchain_info.pQueueFamilyIndices = null;
swapchain_info.oldSwapchain = old_swapchain;
swapchain_info.clipped = VK_TRUE;
_GetSurfaceImageCount( OUT swapchain_info.minImageCount, surf_caps );
_GetSurfaceTransform( OUT swapchain_info.preTransform, surf_caps );
_GetSwapChainExtent( INOUT swapchain_info.imageExtent, surf_caps );
_GetPresentMode( OUT swapchain_info.presentMode, vsync );
_GetSharingMode( OUT swapchain_info.imageSharingMode );
CHECK_ERR( _GetImageUsage( OUT swapchain_info.imageUsage, swapchain_info.presentMode, colorImageUsage, surf_caps ) );
CHECK_ERR( _GetCompositeAlpha( OUT swapchain_info.compositeAlpha, surf_caps ) );
VK_CHECK( vkCreateSwapchainKHR( _logicalDevice, &swapchain_info, null, OUT &_swapchain ) );
_surfaceSize.x = swapchain_info.imageExtent.width;
_surfaceSize.y = swapchain_info.imageExtent.height;
_vsync = vsync;
// destroy obsolete resources
_DeleteSwapchain( old_swapchain );
_DeleteFramebuffers();
// create dependent resources
CHECK_ERR( _CreateColorAttachment( samples, Vk1EnumRevert( swapchain_info.imageUsage ) ) );
CHECK_ERR( _CreateDepthStencilAttachment( depthStencilFormat, depthStencilImageUsage ) );
CHECK_ERR( _CreateRenderPass() );
CHECK_ERR( _CreateFramebuffers() );
return true;
}
/*
=================================================
_GetCompositeAlpha
=================================================
*/
bool Vk1Device::_GetCompositeAlpha (OUT VkCompositeAlphaFlagBitsKHR &compositeAlpha, const VkSurfaceCapabilitiesKHR &surfaceCaps) const
{
const VkCompositeAlphaFlagBitsKHR composite_alpha_flags[] = {
VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
};
compositeAlpha = VK_COMPOSITE_ALPHA_FLAG_BITS_MAX_ENUM_KHR;
for (auto& flag : composite_alpha_flags)
{
if ( EnumEq( surfaceCaps.supportedCompositeAlpha, flag ) )
{
compositeAlpha = flag;
return true;
}
}
RETURN_ERR( "no suitable composite alpha flags found!" );
}
/*
=================================================
RecreateSwapchain
=================================================
*/
bool Vk1Device::RecreateSwapchain (const uint2 &size)
{
CHECK_ERR( IsSwapchainCreated() );
// TODO: check device lost error
VK_CALL( vkDeviceWaitIdle( _logicalDevice ) );
CHECK_ERR( CreateSwapchain( size, _vsync ) ); // TODO imageArrayLayers
// TODO: check device lost error
VK_CALL( vkDeviceWaitIdle( _logicalDevice ) );
return true;
}
bool Vk1Device::RecreateSwapchain ()
{
return RecreateSwapchain( _surfaceSize );
}
/*
=================================================
DestroySwapchain
=================================================
*/
bool Vk1Device::DestroySwapchain ()
{
if ( _swapchain == VK_NULL_HANDLE )
return true;
CHECK_ERR( IsDeviceCreated() );
_DeleteSwapchain( _swapchain );
_framebuffers.Clear();
_renderPass = null;
_DeleteDepthStencilAttachment();
_surfaceSize = uint2();
return true;
}
/*
=================================================
SetSurface
=================================================
*/
bool Vk1Device::SetSurface (VkSurfaceKHR surface, EPixelFormat::type colorFmt)
{
CHECK_ERR( surface != VK_NULL_HANDLE );
CHECK_ERR( HasPhyiscalDevice() );
CHECK_ERR( not IsSurfaceCreated() );
const VkFormat required_format = Vk1Enum( colorFmt );
const VkColorSpaceKHR required_color_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; // EPixelFormat::IsNonLinear( _settings.format );
_surface = surface;
CHECK_ERR( _ChooseColorFormat( OUT _colorFormat, OUT _colorSpace, required_format, required_color_space ) );
_colorPixelFormat = Vk1Enum( _colorFormat );
return true;
}
/*
=================================================
DestroySurface
=================================================
*/
bool Vk1Device::DestroySurface ()
{
if ( _surface == VK_NULL_HANDLE )
return true;
CHECK_ERR( IsInstanceCreated() );
CHECK_ERR( not IsSwapchainCreated() );
vkDestroySurfaceKHR( _instance, _surface, null );
_surface = VK_NULL_HANDLE;
_colorFormat = VK_FORMAT_UNDEFINED;
_colorSpace = VK_COLOR_SPACE_MAX_ENUM_KHR;
_colorPixelFormat = EPixelFormat::Unknown;
return true;
}
/*
=================================================
_ChooseQueueIndex
=================================================
*/
bool Vk1Device::_ChooseQueueIndex (INOUT EQueueFamily::bits &family, OUT uint32_t &index) const
{
Array< VkQueueFamilyProperties > queue_family_props;
CHECK_ERR( _GetQueueFamilyProperties( OUT queue_family_props ) );
FOR( i, queue_family_props )
{
EQueueFamily::bits flags;
VkBool32 supports_present = false;
if ( _surface )
{
VK_CALL( vkGetPhysicalDeviceSurfaceSupportKHR( _physicalDevice, uint32_t(i), _surface, OUT &supports_present ) );
}
if ( supports_present )
{
flags |= EQueueFamily::Present;
}
if ( queue_family_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT )
{
flags |= EQueueFamily::Graphics | EQueueFamily::Transfer;
}
if ( queue_family_props[i].queueFlags & VK_QUEUE_COMPUTE_BIT )
{
flags |= EQueueFamily::Compute | EQueueFamily::Transfer;
}
if ( queue_family_props[i].queueFlags & VK_QUEUE_TRANSFER_BIT )
{
flags |= EQueueFamily::Transfer;
}
if ( queue_family_props[i].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT )
{
flags |= EQueueFamily::SparseBinding;
}
if ( queue_family_props[i].queueFlags & VK_QUEUE_PROTECTED_BIT )
{
flags |= EQueueFamily::Protected;
}
if ( (flags & family) == family )
{
index = uint32_t(i);
return true;
}
}
// TODO: find nearest queue family
RETURN_ERR( "no suitable queue family found!" );
}
/*
=================================================
_GetQueueCreateInfo
=================================================
*/
bool Vk1Device::_GetQueueCreateInfo (OUT VkDeviceQueueCreateInfo &queueCreateInfo, EQueueFamily::bits queueFamily) const
{
uint32_t queue_index = 0;
CHECK_ERR( _ChooseQueueIndex( INOUT queueFamily, OUT queue_index ) );
ZeroMem( queueCreateInfo );
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queue_index;
queueCreateInfo.queueCount = 2;
queueCreateInfo.pQueuePriorities = &DEFAULT_QUEUE_PRIORITY;
return true;
}
/*
=================================================
CreateQueue
=================================================
*
bool Vk1Device::CreateQueue ()
{
CHECK_ERR( IsDeviceCreated() );
CHECK_ERR( not IsQueueCreated() );
vkGetDeviceQueue( _logicalDevice, _queueIndex, 0, OUT &_queue );
return true;
}
/*
=================================================
DestroyQueue
=================================================
*
void Vk1Device::DestroyQueue ()
{
_queue = VK_NULL_HANDLE;
_queueIndex = UMax;
_queueFamily = EQueueFamily::bits();
}
/*
=================================================
BeginFrame
=================================================
*/
bool Vk1Device::BeginFrame (VkSemaphore imageAvailable)
{
CHECK_ERR( IsSwapchainCreated() );
CHECK_ERR( not IsFrameStarted() );
_currentImageIndex = UMax;
uint32_t image_index = UMax;
VkResult result = vkAcquireNextImageKHR( _logicalDevice, _swapchain, UMax, imageAvailable,
VK_NULL_HANDLE, OUT &image_index );
if ( result == VK_SUCCESS )
{}
else
if ( result == VK_ERROR_OUT_OF_DATE_KHR or
result == VK_SUBOPTIMAL_KHR )
{
CHECK_ERR( RecreateSwapchain() );
return false;
}
else
{
if ( not Vk1_CheckErrors( result, "vkAcquireNextImageKHR", GX_FUNCTION_NAME, __FILE__, __LINE__ ) )
return false;
}
_currentImageIndex = image_index;
return true;
}
/*
=================================================
EndFrame
=================================================
*/
bool Vk1Device::EndFrame (vk::VkQueue queue, VkSemaphore renderFinished)
{
CHECK_ERR( IsSwapchainCreated() );
CHECK_ERR( IsFrameStarted() );
VkSwapchainKHR swap_chains[] = { _swapchain };
VkSemaphore wait_semaphores[] = { renderFinished };
VkPresentInfoKHR present_info = {};
present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
present_info.swapchainCount = uint32_t(CountOf( swap_chains ));
present_info.pSwapchains = swap_chains;
present_info.pImageIndices = &_currentImageIndex;
if ( renderFinished != VK_NULL_HANDLE )
{
present_info.waitSemaphoreCount = uint32_t(CountOf( wait_semaphores ));
present_info.pWaitSemaphores = wait_semaphores;
}
VK_CHECK( vkQueuePresentKHR( queue, &present_info ) );
_currentImageIndex = UMax;
return true;
}
/*
=================================================
IsFrameStarted
=================================================
*/
bool Vk1Device::IsFrameStarted () const
{
return _currentImageIndex < _framebuffers.Count();
}
/*
=================================================
_GetSwapChainExtent
=================================================
*/
void Vk1Device::_GetSwapChainExtent (INOUT VkExtent2D &extent, const VkSurfaceCapabilitiesKHR &surfaceCaps) const
{
if ( surfaceCaps.currentExtent.width == UMax and
surfaceCaps.currentExtent.height == UMax )
{
// keep window size
}
else
{
extent.width = surfaceCaps.currentExtent.width;
extent.height = surfaceCaps.currentExtent.height;
}
}
/*
=================================================
_GetPresentMode
=================================================
*/
void Vk1Device::_GetPresentMode (OUT VkPresentModeKHR &presentMode, bool vsync) const
{
uint32_t count = 0;
Array< VkPresentModeKHR > present_modes;
presentMode = VK_PRESENT_MODE_FIFO_KHR;
VK_CALL( vkGetPhysicalDeviceSurfacePresentModesKHR( _physicalDevice, _surface, OUT &count, null ) );
CHECK_ERR( count > 0, void() );
present_modes.Resize( count );
VK_CALL( vkGetPhysicalDeviceSurfacePresentModesKHR( _physicalDevice, _surface, OUT &count, OUT present_modes.ptr() ) );
if ( not vsync )
{
FOR( i, present_modes )
{
if ( present_modes[i] == VK_PRESENT_MODE_MAILBOX_KHR )
{
presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
break;
}
/*if ( presentMode != VK_PRESENT_MODE_MAILBOX_KHR and
present_modes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR )
{
presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
}*/
}
}
}
/*
=================================================
_GetSurfaceImageCount
=================================================
*/
void Vk1Device::_GetSurfaceImageCount (OUT uint32_t &minImageCount, const VkSurfaceCapabilitiesKHR &surfaceCaps) const
{
minImageCount = surfaceCaps.minImageCount + 1;
if ( surfaceCaps.maxImageCount > 0 and minImageCount > surfaceCaps.maxImageCount )
{
minImageCount = surfaceCaps.maxImageCount;
}
}
/*
=================================================
_GetSurfaceTransform
=================================================
*/
void Vk1Device::_GetSurfaceTransform (OUT VkSurfaceTransformFlagBitsKHR &transform,
const VkSurfaceCapabilitiesKHR &surfaceCaps) const
{
if ( surfaceCaps.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR )
{
transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
}
else
{
transform = surfaceCaps.currentTransform;
}
}
/*
=================================================
_GetImageUsage
=================================================
*/
bool Vk1Device::_GetImageUsage (OUT VkImageUsageFlags &imageUsage, VkPresentModeKHR presentMode,
EImageUsage::bits requiredUsage, const VkSurfaceCapabilitiesKHR &surfaceCaps) const
{
if ( presentMode == VK_PRESENT_MODE_IMMEDIATE_KHR or
presentMode == VK_PRESENT_MODE_MAILBOX_KHR or
presentMode == VK_PRESENT_MODE_FIFO_KHR or
presentMode == VK_PRESENT_MODE_FIFO_RELAXED_KHR )
{
imageUsage = surfaceCaps.supportedUsageFlags & Vk1Enum( requiredUsage );
}
else
if ( presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR or
presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR )
{
VkPhysicalDeviceSurfaceInfo2KHR surf_info = {};
surf_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR;
surf_info.surface = _surface;
VkSurfaceCapabilities2KHR surf_caps2;
VK_CALL( vkGetPhysicalDeviceSurfaceCapabilities2KHR( _physicalDevice, &surf_info, OUT &surf_caps2 ) );
for (VkBaseInStructure const *iter = reinterpret_cast<VkBaseInStructure const *>(&surf_caps2);
iter != null;)
{
if ( iter->sType == VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR )
{
imageUsage = reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR const*>(iter)->sharedPresentSupportedUsageFlags & Vk1Enum( requiredUsage );
break;
}
}
}
else
{
RETURN_ERR( "unsupported presentMode, can't choose imageUsage!" );
}
ASSERT( EnumEq( imageUsage, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT ) );
imageUsage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
// validation:
VkFormatProperties format_props;
vkGetPhysicalDeviceFormatProperties( _physicalDevice, _colorFormat, OUT &format_props );
CHECK_ERR( EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT ) );
ASSERT( EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT ) );
if ( EnumEq( imageUsage, VK_IMAGE_USAGE_TRANSFER_SRC_BIT ) and
(not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_TRANSFER_SRC_BIT ) or
not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_BLIT_DST_BIT )) )
{
imageUsage &= ~VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
}
if ( EnumEq( imageUsage, VK_IMAGE_USAGE_TRANSFER_DST_BIT ) and
not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_TRANSFER_DST_BIT ) )
{
imageUsage &= ~VK_IMAGE_USAGE_TRANSFER_DST_BIT;
}
if ( EnumEq( imageUsage, VK_IMAGE_USAGE_STORAGE_BIT ) and
not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT ) )
{
imageUsage &= ~VK_IMAGE_USAGE_STORAGE_BIT;
}
if ( EnumEq( imageUsage, VK_IMAGE_USAGE_SAMPLED_BIT ) and
not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT ) )
{
imageUsage &= ~VK_IMAGE_USAGE_SAMPLED_BIT;
}
if ( EnumEq( imageUsage, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT ) and
not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT ) )
{
imageUsage &= ~VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
}
return true;
}
/*
=================================================
_GetSharingMode
=================================================
*/
void Vk1Device::_GetSharingMode (OUT VkSharingMode &sharingMode) const
{
sharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
/*
=================================================
_DeleteSwapchain
=================================================
*/
void Vk1Device::_DeleteSwapchain (VkSwapchainKHR &swapchain)
{
FOR( i, _imageBuffers )
{
if ( _imageBuffers[i].module ) {
_imageBuffers[i].module->Send( ModuleMsg::Delete{} );
}
}
if ( swapchain != VK_NULL_HANDLE )
{
vkDestroySwapchainKHR( _logicalDevice, swapchain, null );
}
swapchain = VK_NULL_HANDLE;
_imageBuffers.Clear();
}
/*
=================================================
_CreateColorAttachment
=================================================
*/
bool Vk1Device::_CreateColorAttachment (MultiSamples samples, EImageUsage::bits usage)
{
using VkImages_t = FixedSizeArray< VkImage, MAX_SWAPCHAIN_SIZE >;
uint32_t count = 0;
VkImages_t images;
VK_CHECK( vkGetSwapchainImagesKHR( _logicalDevice, _swapchain, OUT &count, null ) );
CHECK_ERR( count > 0 );
images.Resize( count );
VK_CHECK( vkGetSwapchainImagesKHR( _logicalDevice, _swapchain, OUT &count, OUT images.ptr() ) );
CHECK_ERR( count > 0 );
_imageBuffers.Resize( count );
ImageDescription descr;
descr.dimension = uint4( _surfaceSize, 0, 0 );
descr.format = _colorPixelFormat;
descr.imageType = EImage::Tex2D;
descr.samples = samples;
descr.usage = usage;
FOR( i, _imageBuffers )
{
auto& buf = _imageBuffers[i];
buf.module = New< Vk1SwapchainImage >( GlobalSystems(), CreateInfo::GpuImage{ descr } );
ModuleUtils::Initialize({ buf.module });
buf.view = buf.module->Request( GpuMsg::SetVkSwapchainImage{ images[i] });
}
return true;
}
/*
=================================================
_CreateDepthStencilAttachment
=================================================
*/
bool Vk1Device::_CreateDepthStencilAttachment (EPixelFormat::type depthStencilFormat, EImageUsage::bits usage)
{
if ( depthStencilFormat == EPixelFormat::Unknown )
{
_DeleteDepthStencilAttachment();
return true;
}
CHECK_ERR( GlobalSystems()->modulesFactory->Create(
VkImageModuleID,
GlobalSystems(),
CreateInfo::GpuImage{
ImageDescription{
EImage::Tex2D,
uint4( _surfaceSize, 0, 0 ),
depthStencilFormat,
EImageUsage::DepthStencilAttachment | usage
},
EGpuMemory::LocalInGPU,
EMemoryAccess::GpuReadWrite
},
OUT _depthStencilImage ) );
ModuleUtils::Initialize({ _depthStencilImage });
GpuMsg::GetVkImageID req_id;
_depthStencilImage->Send( req_id );
_depthStencilView = req_id.result->defaultView;
return true;
}
/*
=================================================
_DeleteDepthStencilAttachment
=================================================
*/
void Vk1Device::_DeleteDepthStencilAttachment ()
{
if ( _depthStencilImage ) {
_depthStencilImage->Send( ModuleMsg::Delete{} );
}
_depthStencilImage = null;
_depthStencilFormat = VK_FORMAT_UNDEFINED;
_depthStencilPixelFormat = EPixelFormat::Unknown;
_depthStencilView = VK_NULL_HANDLE;
}
/*
=================================================
GetMemoryTypeIndex
=================================================
*/
bool Vk1Device::GetMemoryTypeIndex (const uint32_t memoryTypeBits, const VkMemoryPropertyFlags flags, OUT uint32_t &index) const
{
index = UMax;
for (uint32_t i = 0; i < _deviceMemoryProperties.memoryTypeCount; ++i)
{
const auto& mem_type = _deviceMemoryProperties.memoryTypes[i];
if ( ((memoryTypeBits >> i) & 1) == 1 and
EnumEq( mem_type.propertyFlags, flags ) )
{
index = i;
return true;
}
}
return false;
}
/*
=================================================
CompareMemoryTypes
=================================================
*/
bool Vk1Device::CompareMemoryTypes (const uint32_t memoryTypeBits, const VkMemoryPropertyFlags flags, const uint32_t index) const
{
CHECK_ERR( index < _deviceMemoryProperties.memoryTypeCount );
const auto& mem_type = _deviceMemoryProperties.memoryTypes[ index ];
if ( ((memoryTypeBits >> index) & 1) == 1 and
EnumEq( mem_type.propertyFlags, flags ) )
{
return true;
}
return false;
}
/*
=================================================
SetObjectName
=================================================
*/
bool Vk1Device::SetObjectName (uint64_t id, StringCRef name, EGpuObject::type type) const
{
if ( name.Empty() or id == VK_NULL_HANDLE or not _enableDebugMarkers )
return false;
VkDebugMarkerObjectNameInfoEXT info = {};
info.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT;
info.objectType = Vk1Enum( type );
info.object = id;
info.pObjectName = name.cstr();
VK_CALL( vkDebugMarkerSetObjectNameEXT( GetLogicalDevice(), &info ) );
return true;
}
/*
=================================================
_CreateRenderPass
=================================================
*/
bool Vk1Device::_CreateRenderPass ()
{
if ( _renderPass )
return true;
ASSERT( _depthStencilView != VK_NULL_HANDLE ?
_depthStencilPixelFormat != EPixelFormat::Unknown :
_depthStencilPixelFormat == EPixelFormat::Unknown );
ModulePtr module;
CHECK_ERR( GlobalSystems()->modulesFactory->Create(
VkRenderPassModuleID,
GlobalSystems(),
CreateInfo::GpuRenderPass{
null,
RenderPassDescrBuilder::CreateForSurface( _colorPixelFormat, _depthStencilPixelFormat )
},
OUT module ) );
_renderPass = module;
return true;
}
/*
=================================================
_CreateFramebuffers
=================================================
*/
bool Vk1Device::_CreateFramebuffers ()
{
CHECK_ERR( not _imageBuffers.Empty() );
CHECK_ERR( _framebuffers.Empty() );
CHECK_ERR( _renderPass );
_framebuffers.Resize( _imageBuffers.Count() );
FOR( i, _framebuffers )
{
ModulePtr fb;
CHECK_ERR( GlobalSystems()->modulesFactory->Create(
VkFramebufferModuleID,
GlobalSystems(),
CreateInfo::GpuFramebuffer{ _surfaceSize },
OUT fb ) );
fb->Send( ModuleMsg::AttachModule{ _renderPass });
fb->Send( ModuleMsg::AttachModule{ "Color0", _imageBuffers[i].module });
if ( _depthStencilImage ) {
fb->Send( ModuleMsg::AttachModule{ "Depth", _depthStencilImage });
}
_framebuffers[i] = fb;
}
ModuleUtils::Initialize( _framebuffers );
return true;
}
/*
=================================================
_DeleteFramebuffers
=================================================
*/
void Vk1Device::_DeleteFramebuffers ()
{
for (auto& fbo : _framebuffers) {
fbo->Send( ModuleMsg::Delete{} );
}
_framebuffers.Clear();
}
/*
=================================================
_ChooseColorFormat
=================================================
*/
bool Vk1Device::_ChooseColorFormat (OUT VkFormat &colorFormat, OUT VkColorSpaceKHR &colorSpace,
const VkFormat requiredFormat, const VkColorSpaceKHR requiredColorSpace) const
{
uint32_t count = 0;
Array< VkSurfaceFormatKHR > surf_formats;
const VkFormat def_format = VK_FORMAT_B8G8R8A8_UNORM;
const VkColorSpaceKHR def_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
VK_CHECK( vkGetPhysicalDeviceSurfaceFormatsKHR( _physicalDevice, _surface, OUT &count, null ) );
CHECK_ERR( count > 0 );
surf_formats.Resize( count );
VK_CHECK( vkGetPhysicalDeviceSurfaceFormatsKHR( _physicalDevice, _surface, OUT &count, OUT surf_formats.ptr() ) );
if ( count == 1 and
surf_formats[0].format == VK_FORMAT_UNDEFINED )
{
colorFormat = requiredFormat;
colorSpace = surf_formats[0].colorSpace;
}
else
{
usize both_match_idx = UMax;
usize format_match_idx = UMax;
usize space_match_idx = UMax;
usize def_format_idx = 0;
usize def_space_idx = 0;
FOR( i, surf_formats )
{
if ( surf_formats[i].format == requiredFormat and
surf_formats[i].colorSpace == requiredColorSpace )
{
both_match_idx = i;
}
else
// separate check
if ( surf_formats[i].format == requiredFormat )
format_match_idx = i;
else
if ( surf_formats[i].colorSpace == requiredColorSpace )
space_match_idx = i;
// check with default
if ( surf_formats[i].format == def_format )
def_format_idx = i;
if ( surf_formats[i].colorSpace == def_space )
def_space_idx = i;
}
usize idx = 0;
if ( both_match_idx != UMax )
idx = both_match_idx;
else
if ( format_match_idx != UMax )
idx = format_match_idx;
else
if ( def_format_idx != UMax )
idx = def_format_idx;
// TODO: space_match_idx and def_space_idx are unused yet
colorFormat = surf_formats[ idx ].format;
colorSpace = surf_formats[ idx ].colorSpace;
}
return true;
}
/*
=================================================
_GetQueueFamilyProperties
=================================================
*/
bool Vk1Device::_GetQueueFamilyProperties (OUT Array<VkQueueFamilyProperties> &properties) const
{
uint32_t count = 0;
vkGetPhysicalDeviceQueueFamilyProperties( _physicalDevice, OUT &count, null );
CHECK_ERR( count > 0 );
properties.Resize( count );
vkGetPhysicalDeviceQueueFamilyProperties( _physicalDevice, OUT &count, OUT properties.ptr() );
return true;
}
/*
=================================================
_LoadDeviceExtensions
=================================================
*/
bool Vk1Device::_LoadDeviceExtensions () const
{
CHECK_ERR( HasPhyiscalDevice() );
if ( not _deviceExtensions.Empty() )
return true;
uint32_t count = 0;
VK_CALL( vkEnumerateDeviceExtensionProperties( _physicalDevice, null, OUT &count, null ) );
if ( count == 0 ) {
_deviceExtensions << "";
return true;
}
Array< VkExtensionProperties > dev_ext;
dev_ext.Resize( count );
VK_CHECK( vkEnumerateDeviceExtensionProperties( _physicalDevice, null, OUT &count, OUT dev_ext.ptr() ) );
for (auto& ext : dev_ext) {
_deviceExtensions.Add( StringCRef(ext.extensionName) );
}
return true;
}
/*
=================================================
HasDeviceExtension
=================================================
*/
bool Vk1Device::HasDeviceExtension (StringCRef name) const
{
_LoadDeviceExtensions();
return _deviceExtensions.IsExist( name );
}
/*
=================================================
_CheckDeviceExtensions
=================================================
*/
bool Vk1Device::_CheckDeviceExtensions (INOUT Array<const char*> &extensions) const
{
CHECK_ERR( HasPhyiscalDevice() );
FOR( i, extensions )
{
StringCRef name = extensions[i];
if ( not HasDeviceExtension( name ) )
{
LOG( "Vulkan device extension \""_str << name << "\" not supported and will be removed", ELog::Info );
extensions.Erase( i );
--i;
}
}
return true;
}
/*
=================================================
_CheckLayers
=================================================
*/
bool Vk1Device::_CheckLayers (INOUT Array<const char*> &layers) const
{
FOR( i, layers )
{
StringCRef name = layers[i];
if ( not HasLayer( name ) )
{
LOG( "Vulkan layer \""_str << name << "\" not supported and will be removed", ELog::Info );
layers.Erase( i );
--i;
}
}
return true;
}
/*
=================================================
_CheckExtensions
=================================================
*/
bool Vk1Device::_CheckExtensions (INOUT Array<const char*> &extensions) const
{
FOR( i, extensions )
{
StringCRef name = extensions[i];
if ( not HasExtension( name ) )
{
LOG( "Vulkan extension \""_str << name << "\" not supported and will be removed", ELog::Info );
extensions.Erase( i );
--i;
}
}
return true;
}
/*
=================================================
_DebugReportCallback
=================================================
*/
VkBool32 VKAPI_CALL Vk1Device::_DebugReportCallback (VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType,
uint64_t object,
size_t /*location*/,
int32_t messageCode,
const char* pLayerPrefix,
const char* pMessage,
void* pUserData)
{
String log;
log << "Vulkan " << _DebugReportFlagsToString( VkDebugReportFlagBitsEXT(flags) )
<< " in object: " << _DebugReportObjectTypeToString( objectType )
<< '(' << String().FormatAlignedI( object, 8, '0', 16 ) << ')'
<< ", layer: " << pLayerPrefix << '(' << messageCode << ')'
<< ", message:\n" << pMessage;
LOG( log, _DebugReportFlagsToLogType( VkDebugReportFlagBitsEXT(flags) ) );
Cast< Vk1Device *>(pUserData)->_debugReportCounter++;
return VK_FALSE;
}
/*
=================================================
_DebugReportFlagsToString
=================================================
*/
StringCRef Vk1Device::_DebugReportFlagsToString (VkDebugReportFlagBitsEXT flags)
{
if ( EnumEq( flags, VK_DEBUG_REPORT_ERROR_BIT_EXT ) )
return "error";
if ( EnumEq( flags, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT ) )
return "performance";
if ( EnumEq( flags, VK_DEBUG_REPORT_WARNING_BIT_EXT ) )
return "warning";
if ( EnumEq( flags, VK_DEBUG_REPORT_INFORMATION_BIT_EXT ) )
return "info";
if ( EnumEq( flags, VK_DEBUG_REPORT_DEBUG_BIT_EXT ) )
return "debug";
return "";
}
/*
=================================================
_DebugReportFlagsToLogType
=================================================
*/
ELog::type Vk1Device::_DebugReportFlagsToLogType (VkDebugReportFlagBitsEXT flags)
{
if ( EnumEq( flags, VK_DEBUG_REPORT_ERROR_BIT_EXT ) )
return ELog::Warning;
if ( EnumEq( flags, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT ) )
return ELog::Debug;
if ( EnumEq( flags, VK_DEBUG_REPORT_WARNING_BIT_EXT ) )
return ELog::Debug;
if ( EnumEq( flags, VK_DEBUG_REPORT_INFORMATION_BIT_EXT ) )
return ELog::Debug;
if ( EnumEq( flags, VK_DEBUG_REPORT_DEBUG_BIT_EXT ) )
return ELog::Debug;
return ELog::Debug;
}
/*
=================================================
_DebugReportObjectTypeToString
=================================================
*/
StringCRef Vk1Device::_DebugReportObjectTypeToString (VkDebugReportObjectTypeEXT objType)
{
switch ( objType )
{
//case VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT : return "unknown";
case VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT : return "Instance";
case VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT : return "PhysicalDevice";
case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT : return "Device";
case VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT : return "Queue";
case VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT : return "Semaphore";
case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT : return "CommandBuffer";
case VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT : return "Fence";
case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT : return "DeviceMemory";
case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT : return "Buffer";
case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT : return "Image";
case VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT : return "Event";
case VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT : return "QueryPool";
case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT : return "BufferView";
case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT : return "ImageView";
case VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT : return "ShaderModule";
case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT : return "PipelineCache";
case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT : return "PipelineLayout";
case VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT : return "RenderPass";
case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT : return "Pipeline";
case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT : return "DescriptorSetLayout";
case VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT : return "Sampler";
case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT : return "DescriptorPool";
case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT : return "DescriptorSet";
case VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT : return "Framebuffer";
case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT : return "CommandPool";
case VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT : return "Surface";
case VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT : return "Swapchain";
case VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT : return "DebugReport";
case VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_KHR_EXT : return "Display";
case VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_MODE_KHR_EXT : return "DisplayMode";
case VK_DEBUG_REPORT_OBJECT_TYPE_OBJECT_TABLE_NVX_EXT : return "ObjectTableNvx";
case VK_DEBUG_REPORT_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX_EXT : return "IndirectCommandsLayoutNvx";
default :
CHECK( objType >= VK_DEBUG_REPORT_OBJECT_TYPE_BEGIN_RANGE_EXT and
objType <= VK_DEBUG_REPORT_OBJECT_TYPE_END_RANGE_EXT );
return "unknown";
}
}
} // PlatformVK
} // Engine
#endif // GRAPHICS_API_VULKAN
| 29.293065 | 152 | 0.640885 | [
"object",
"transform"
] |
ff3abd6f37ef55eee69a2e1362fadbbba0886dab | 5,858 | hh | C++ | spot/spot/taalgos/emptinessta.hh | mcc-petrinets/formulas | 10f835d67c7deedfe98fbbd55a56bd549a5bae9b | [
"MIT"
] | 1 | 2018-03-02T14:29:57.000Z | 2018-03-02T14:29:57.000Z | spot/spot/taalgos/emptinessta.hh | mcc-petrinets/formulas | 10f835d67c7deedfe98fbbd55a56bd549a5bae9b | [
"MIT"
] | null | null | null | spot/spot/taalgos/emptinessta.hh | mcc-petrinets/formulas | 10f835d67c7deedfe98fbbd55a56bd549a5bae9b | [
"MIT"
] | 1 | 2015-06-05T12:42:07.000Z | 2015-06-05T12:42:07.000Z | // -*- coding: utf-8 -*-
// Copyright (C) 2012-2014, 2016, 2018 Laboratoire de Recherche
// et Dévelopment de l'Epita (LRDE).
//
// This file is part of Spot, a model checking library.
//
// Spot 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.
//
// Spot 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 this program. If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include <spot/ta/taproduct.hh>
#include <spot/misc/optionmap.hh>
#include <spot/twaalgos/emptiness_stats.hh>
#include <stack>
#include <queue>
namespace spot
{
namespace
{
typedef std::pair<const spot::state*,
ta_succ_iterator_product*> pair_state_iter;
}
/// \addtogroup ta_emptiness_check Emptiness-checks
/// \ingroup ta_algorithms
/// \ingroup ta_emptiness_check
/// \brief Check whether the language of a product (spot::ta_product) between
/// a Kripke structure and a TA is empty. It works also for the product
/// using Generalized TA (GTA and SGTA).
///
/// you should call spot::ta_check::check() to check the product automaton.
/// If spot::ta_check::check() returns false, then the product automaton
/// was found empty. Otherwise the automaton accepts some run.
///
/// This is based on the following paper.
/** \verbatim
@InProceedings{ geldenhuys.06.spin,
author = {Jaco Geldenhuys and Henri Hansen},
title = {Larger Automata and Less Work for {LTL} Model Checking},
booktitle = {Proceedings of the 13th International SPIN Workshop
(SPIN'06)},
year = {2006},
pages = {53--70},
series = {Lecture Notes in Computer Science},
volume = {3925},
publisher = {Springer}
}
\endverbatim */
///
/// the implementation of spot::ta_check::check() is inspired from the
/// two-pass algorithm of the paper above:
/// - the fist-pass detect all Buchi-accepting cycles and includes
/// the heuristic proposed in the paper to detect some
/// livelock-accepting cycles.
/// - the second-pass detect all livelock-accepting cycles.
/// In addition, we add some optimizations to the fist pass:
/// 1- Detection of all cycles containing a least
/// one state that is both livelock and Buchi accepting states
/// 2- Detection of all livelock-accepting cycles containing a least
/// one state (k,t) such as its "TA component" t is a livelock-accepting
/// state that has no successors in the TA automaton.
///
/// The implementation of the algorithm of each pass is a SCC-based algorithm
/// inspired from spot::gtec.hh.
/// @{
/// \brief An implementation of the emptiness-check algorithm for a product
/// between a TA and a Kripke structure
///
/// See the paper cited above.
class SPOT_API ta_check : public ec_statistics
{
typedef state_map<int> hash_type;
public:
ta_check(const const_ta_product_ptr& a, option_map o = option_map());
virtual
~ta_check();
/// \brief Check whether the TA product automaton contains an accepting run:
/// it detects the two kinds of accepting runs: Buchi-accepting runs
/// and livelock-accepting runs. This emptiness check algorithm can also
/// check a product using the generalized form of TA.
///
/// Return false if the product automaton accepts no run, otherwise true
///
/// \param disable_second_pass is used to disable the second pass when
/// when it is not necessary, for example when all the livelock-accepting
/// states of the TA automaton have no successors, we call this kind of
/// TA as STA (Single-pass Testing Automata)
/// (see spot::tgba2ta::add_artificial_livelock_accepting_state() for an
/// automatic transformation of any TA automaton into STA automaton
///
/// \param disable_heuristic_for_livelock_detection disable the heuristic
/// used in the first pass to detect livelock-accepting runs,
/// this heuristic is described in the paper cited above
bool
check(bool disable_second_pass = false,
bool disable_heuristic_for_livelock_detection = false);
/// \brief Check whether the product automaton contains
/// a livelock-accepting run
/// Return false if the product automaton accepts no livelock-accepting run,
/// otherwise true
bool
livelock_detection(const const_ta_product_ptr& t);
/// Print statistics, if any.
std::ostream&
print_stats(std::ostream& os) const;
protected:
void
clear(hash_type& h, std::stack<pair_state_iter> todo, std::queue<
const spot::state*> init_set);
void
clear(hash_type& h, std::stack<pair_state_iter> todo,
spot::ta_succ_iterator* init_states_it);
/// the heuristic for livelock-accepting runs detection, it's described
/// in the paper cited above
bool
heuristic_livelock_detection(const state * stuttering_succ,
hash_type& h, int h_livelock_root, std::set<const state*,
state_ptr_less_than> liveset_curr);
const_ta_product_ptr a_; ///< The automaton.
option_map o_; ///< The options
// Force the second pass
bool is_full_2_pass_;
// scc: a stack of strongly connected components (SCC)
scc_stack_ta scc;
// sscc: a stack of strongly stuttering-connected components (SSCC)
scc_stack_ta sscc;
};
/// @}
}
| 37.075949 | 80 | 0.684022 | [
"model"
] |
ff455491f2870d785cc3d1622c19a70773c5969e | 3,255 | cpp | C++ | opencv-glib/video-capture.cpp | wagavulin/opencv-glib | 9ca21978b2178ee3b87f27c1ff4f78a2c20e065a | [
"BSD-3-Clause"
] | 4 | 2020-01-14T22:30:36.000Z | 2022-03-06T08:51:30.000Z | opencv-glib/video-capture.cpp | wagavulin/opencv-glib | 9ca21978b2178ee3b87f27c1ff4f78a2c20e065a | [
"BSD-3-Clause"
] | 9 | 2019-08-13T11:18:44.000Z | 2022-03-04T22:03:02.000Z | opencv-glib/video-capture.cpp | wagavulin/opencv-glib | 9ca21978b2178ee3b87f27c1ff4f78a2c20e065a | [
"BSD-3-Clause"
] | 6 | 2018-10-24T18:49:16.000Z | 2022-03-04T13:53:14.000Z | #include <opencv-glib/image.hpp>
#include <opencv-glib/video-capture.hpp>
G_BEGIN_DECLS
/**
* SECTION: video-capture
* @title: Video capture class
* @include: opencv-glib/opencv-glib.h
*
* #GCVVideoCapture is a class for reading images from video.
*
* Since: 1.0.0
*/
typedef struct {
std::shared_ptr<cv::VideoCapture> video_capture;
} GCVVideoCapturePrivate;
G_DEFINE_TYPE_WITH_PRIVATE(GCVVideoCapture, gcv_video_capture, G_TYPE_OBJECT)
#define GCV_VIDEO_CAPTURE_GET_PRIVATE(object) \
static_cast<GCVVideoCapturePrivate *>( \
gcv_video_capture_get_instance_private( \
GCV_VIDEO_CAPTURE(object)))
enum {
PROP_0,
PROP_VIDEO_CAPTURE
};
static void
gcv_video_capture_finalize(GObject *object)
{
auto priv = GCV_VIDEO_CAPTURE_GET_PRIVATE(object);
priv->video_capture = nullptr;
G_OBJECT_CLASS(gcv_video_capture_parent_class)->finalize(object);
}
static void
gcv_video_capture_set_property(GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
auto priv = GCV_VIDEO_CAPTURE_GET_PRIVATE(object);
switch (prop_id) {
case PROP_VIDEO_CAPTURE:
priv->video_capture =
*static_cast<std::shared_ptr<cv::VideoCapture> *>(g_value_get_pointer(value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void
gcv_video_capture_init(GCVVideoCapture *object)
{
}
static void
gcv_video_capture_class_init(GCVVideoCaptureClass *klass)
{
GParamSpec *spec;
auto gobject_class = G_OBJECT_CLASS(klass);
gobject_class->finalize = gcv_video_capture_finalize;
gobject_class->set_property = gcv_video_capture_set_property;
spec = g_param_spec_pointer("video-capture",
"Video capture",
"The raw std::shared<cv::VideoCapture> *",
static_cast<GParamFlags>(G_PARAM_WRITABLE |
G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property(gobject_class, PROP_VIDEO_CAPTURE, spec);
}
/**
* gcv_video_capture_read:
* @capture: A #GCVVideoCapture
*
* It reads an image from the video capture. If no image is left, it
* returns NULL.
*
* Returns: (nullable) (transfer full):
* A captured #GCVImage or %NULL.
*
* Since: 1.0.0
*/
GCVImage *
gcv_video_capture_read(GCVVideoCapture *capture)
{
auto priv = GCV_VIDEO_CAPTURE_GET_PRIVATE(capture);
auto cv_video_capture = priv->video_capture;
auto cv_image = std::make_shared<cv::Mat>();
if (cv_video_capture->read(*cv_image)) {
return gcv_image_new_raw(&cv_image);
} else {
return NULL;
}
}
G_END_DECLS
GCVVideoCapture *
gcv_video_capture_new_raw(std::shared_ptr<cv::VideoCapture> *cv_video_capture)
{
auto video_capture = g_object_new(GCV_TYPE_VIDEO_CAPTURE,
"video-capture", cv_video_capture,
NULL);
return GCV_VIDEO_CAPTURE(video_capture);
}
std::shared_ptr<cv::VideoCapture>
gcv_video_capture_get_raw(GCVVideoCapture *video_capture)
{
auto priv = GCV_VIDEO_CAPTURE_GET_PRIVATE(video_capture);
return priv->video_capture;
}
| 25.833333 | 84 | 0.687865 | [
"object"
] |
ff4598d56a18737072e76f1beeed76e3ee04c84d | 24,903 | cpp | C++ | skeleton/character_skeleton_3d.cpp | Relintai/entity_spell_system | cfba9403cb150d0a1c802039a5b7a8822a4f4832 | [
"MIT"
] | 70 | 2019-12-25T18:11:08.000Z | 2022-03-22T10:23:56.000Z | skeleton/character_skeleton_3d.cpp | Relintai/entity_spell_system | cfba9403cb150d0a1c802039a5b7a8822a4f4832 | [
"MIT"
] | 1 | 2019-12-26T10:36:33.000Z | 2020-04-09T14:21:48.000Z | skeleton/character_skeleton_3d.cpp | Relintai/entity_spell_system | cfba9403cb150d0a1c802039a5b7a8822a4f4832 | [
"MIT"
] | 6 | 2020-01-07T19:04:26.000Z | 2021-10-19T18:29:24.000Z | /*
Copyright (c) 2019-2021 Péter Magyar
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 "character_skeleton_3d.h"
#include "../singletons/ess.h"
#include "../data/items/model_visual.h"
#include "../defines.h"
int CharacterSkeleton3D::get_entity_type() const {
return _entity_type;
}
void CharacterSkeleton3D::set_entity_type(const int value) {
_entity_type = value;
int bones_size = ESS::get_singleton()->skeletons_bones_index_get(_entity_type).get_slice_count(",");
int attachment_size = ESS::get_singleton()->skeletons_bone_attachment_index_get(_entity_type).get_slice_count(",");
_attach_point_nodes.resize(attachment_size);
_entries.resize(bones_size);
}
int CharacterSkeleton3D::get_model_index() {
return _model_index;
}
void CharacterSkeleton3D::set_model_index(int value) {
_model_index = value;
}
bool CharacterSkeleton3D::get_model_dirty() const {
return _model_dirty;
}
void CharacterSkeleton3D::set_model_dirty(bool value) {
_model_dirty = value;
}
NodePath CharacterSkeleton3D::attach_point_path_get(const int index) const {
ERR_FAIL_INDEX_V(index, _attach_point_nodes.size(), NodePath());
return _attach_point_nodes[index].path;
}
void CharacterSkeleton3D::attach_point_path_set(const int index, const NodePath &path) {
ERR_FAIL_INDEX(index, _attach_point_nodes.size());
_attach_point_nodes.write[index].path = path;
_attach_point_nodes.write[index].node = get_node_or_null(path);
}
Node *CharacterSkeleton3D::attach_point_node_get(const int index) {
ERR_FAIL_INDEX_V(index, _attach_point_nodes.size(), NULL);
return _attach_point_nodes[index].node;
}
int CharacterSkeleton3D::attach_point_count() const {
return _attach_point_nodes.size();
}
Node *CharacterSkeleton3D::common_attach_point_node_get(const EntityEnums::CommonCharacterSkeletonPoints index) {
ERR_FAIL_INDEX_V(common_attach_point_index_get(index), _attach_point_nodes.size(), NULL);
return _attach_point_nodes[common_attach_point_index_get(index)].node;
}
void CharacterSkeleton3D::common_attach_point_add(const EntityEnums::CommonCharacterSkeletonPoints point, const Ref<PackedScene> &scene) {
int index = common_attach_point_index_get(point);
ERR_FAIL_INDEX(index, _attach_point_nodes.size());
Node *n = _attach_point_nodes[index].node;
if (INSTANCE_VALIDATE(n) && n->has_method("add")) {
n->call("add", scene);
}
}
void CharacterSkeleton3D::common_attach_point_add_timed(const EntityEnums::CommonCharacterSkeletonPoints point, const Ref<PackedScene> &scene, const float time) {
int index = common_attach_point_index_get(point);
ERR_FAIL_INDEX(index, _attach_point_nodes.size());
Node *n = _attach_point_nodes[index].node;
if (INSTANCE_VALIDATE(n) && n->has_method("add_timed")) {
n->call("add_timed", scene, time);
}
}
void CharacterSkeleton3D::common_attach_point_remove(const EntityEnums::CommonCharacterSkeletonPoints point, const Ref<PackedScene> &scene) {
int index = common_attach_point_index_get(point);
ERR_FAIL_INDEX(index, _attach_point_nodes.size());
Node *n = _attach_point_nodes[index].node;
if (INSTANCE_VALIDATE(n) && n->has_method("remove")) {
n->call("remove", scene);
}
}
int CharacterSkeleton3D::common_attach_point_index_get(const EntityEnums::CommonCharacterSkeletonPoints point) {
return call("_common_attach_point_index_get", point);
}
int CharacterSkeleton3D::_common_attach_point_index_get(const EntityEnums::CommonCharacterSkeletonPoints point) {
return 0;
}
NodePath CharacterSkeleton3D::get_animation_player_path() {
return _animation_player_path;
}
void CharacterSkeleton3D::set_animation_player_path(NodePath path) {
_animation_player_path = path;
Node *node = get_node_or_null(_animation_player_path);
if (node != NULL) {
_animation_player = Object::cast_to<AnimationPlayer>(node);
} else {
_animation_player = NULL;
}
}
AnimationPlayer *CharacterSkeleton3D::get_animation_player() {
return _animation_player;
}
NodePath CharacterSkeleton3D::get_animation_tree_path() {
return _animation_tree_path;
}
void CharacterSkeleton3D::set_animation_tree_path(NodePath path) {
_animation_tree_path = path;
Node *node = get_node_or_null(_animation_tree_path);
if (node != NULL) {
_animation_tree = Object::cast_to<AnimationTree>(node);
} else {
_animation_tree = NULL;
}
}
AnimationTree *CharacterSkeleton3D::get_animation_tree() {
return _animation_tree;
}
void CharacterSkeleton3D::update_nodes() {
for (int i = 0; i < _attach_point_nodes.size(); ++i) {
_attach_point_nodes.write[i].node = get_node_or_null(_attach_point_nodes[i].path);
}
set_animation_player_path(_animation_player_path);
set_animation_tree_path(_animation_tree_path);
}
int CharacterSkeleton3D::bone_additional_mesh_transform_bone_index_get(const int index) const {
ERR_FAIL_INDEX_V(index, _bone_model_additional_mesh_transforms.size(), 0);
return _bone_model_additional_mesh_transforms[index].bone_index;
}
void CharacterSkeleton3D::bone_additional_mesh_transform_bone_index_set(const int index, const int bone_index) {
ERR_FAIL_INDEX(index, _bone_model_additional_mesh_transforms.size());
_bone_model_additional_mesh_transforms.write[index].bone_index = bone_index;
}
Transform CharacterSkeleton3D::bone_additional_mesh_transform_transform_get(const int index) const {
ERR_FAIL_INDEX_V(index, _bone_model_additional_mesh_transforms.size(), Transform());
return _bone_model_additional_mesh_transforms[index].transform;
}
void CharacterSkeleton3D::bone_additional_mesh_transform_transform_set(const int index, const Transform &transform) {
ERR_FAIL_INDEX(index, _bone_model_additional_mesh_transforms.size());
_bone_model_additional_mesh_transforms.write[index].transform = transform;
}
Transform CharacterSkeleton3D::bone_additional_mesh_transform_user_transform_get(const int index) const {
ERR_FAIL_INDEX_V(index, _bone_model_additional_mesh_transforms.size(), Transform());
return _bone_model_additional_mesh_transforms[index].user_transform;
}
void CharacterSkeleton3D::bone_additional_mesh_transform_user_transform_set(const int index, const Transform &transform) {
ERR_FAIL_INDEX(index, _bone_model_additional_mesh_transforms.size());
_bone_model_additional_mesh_transforms.write[index].user_transform = transform;
}
void CharacterSkeleton3D::bone_additional_mesh_transform_set_count(const int size) {
_bone_model_additional_mesh_transforms.resize(size);
}
int CharacterSkeleton3D::bone_additional_mesh_transform_get_count() const {
return _bone_model_additional_mesh_transforms.size();
}
void CharacterSkeleton3D::add_model_visual(Ref<ModelVisual> vis) {
ERR_FAIL_COND(!vis.is_valid());
for (int i = 0; i < vis->get_visual_entry_count(); ++i) {
Ref<ModelVisualEntry> e = vis->get_visual_entry(i);
if (e.is_valid())
add_model_visual_entry(vis, e);
}
_model_visuals.push_back(vis);
set_process(true);
_model_dirty = true;
}
void CharacterSkeleton3D::remove_model_visual(Ref<ModelVisual> vis) {
ERR_FAIL_COND(!vis.is_valid());
int index = _model_visuals.find(vis);
if (index == -1)
return;
for (int i = 0; i < vis->get_visual_entry_count(); ++i) {
Ref<ModelVisualEntry> e = vis->get_visual_entry(i);
if (e.is_valid())
remove_model_visual_entry(vis, e);
}
_model_visuals.remove(index);
set_process(true);
_model_dirty = true;
}
void CharacterSkeleton3D::remove_model_visual_index(int index) {
ERR_FAIL_INDEX(index, _model_visuals.size());
set_process(true);
_model_dirty = true;
_model_visuals.remove(index);
}
Ref<ModelVisual> CharacterSkeleton3D::get_model_visual(int index) {
ERR_FAIL_INDEX_V(index, _model_visuals.size(), Ref<ModelVisual>());
set_process(true);
_model_dirty = true;
return _model_visuals.get(index);
}
int CharacterSkeleton3D::get_model_visual_count() {
return _model_visuals.size();
}
void CharacterSkeleton3D::clear_model_visuals() {
_model_visuals.clear();
for (int i = 0; i < _entries.size(); ++i) {
_entries.write[i].clear();
}
_model_dirty = true;
set_process(true);
}
void CharacterSkeleton3D::add_model_visual_entry(Ref<ModelVisual> vis, Ref<ModelVisualEntry> ive) {
ERR_FAIL_COND(!vis.is_valid());
ERR_FAIL_COND(!ive.is_valid());
if (ive->get_type() == ModelVisualEntry::MODEL_VISUAL_ENTRY_TYPE_ATTACHMENT) {
EntityEnums::CommonCharacterSkeletonPoints target_bone = static_cast<EntityEnums::CommonCharacterSkeletonPoints>(ive->get_bone());
for (int i = 0; i < ive->get_size(); ++i) {
Ref<PackedScene> ps = ive->get_attachment(i);
if (ps.is_valid()) {
common_attach_point_add(target_bone, ps);
}
}
return;
}
int target_bone_idx = ive->get_bone();
Vector<Ref<SkeletonModelEntry> > &entries = _entries.write[target_bone_idx];
for (int i = 0; i < entries.size(); ++i) {
Ref<SkeletonModelEntry> e = entries.get(i);
if (e->get_entry() == ive) {
e->set_count(e->get_count() + 1);
return;
}
}
Ref<SkeletonModelEntry> e;
e.instance();
e->set_priority(vis->get_layer());
//e->set_color(ive->get_color());
e->set_entry(ive);
entries.push_back(e);
_model_dirty = true;
set_process(true);
}
void CharacterSkeleton3D::remove_model_visual_entry(Ref<ModelVisual> vis, Ref<ModelVisualEntry> ive) {
ERR_FAIL_COND(!vis.is_valid());
ERR_FAIL_COND(!ive.is_valid());
if (ive->get_type() == ModelVisualEntry::MODEL_VISUAL_ENTRY_TYPE_ATTACHMENT) {
EntityEnums::CommonCharacterSkeletonPoints target_bone = static_cast<EntityEnums::CommonCharacterSkeletonPoints>(ive->get_bone());
for (int i = 0; i < ive->get_size(); ++i) {
Ref<PackedScene> ps = ive->get_attachment(i);
if (ps.is_valid()) {
common_attach_point_remove(target_bone, ps);
}
}
return;
}
int target_bone_idx = ive->get_bone();
Vector<Ref<SkeletonModelEntry> > &entries = _entries.write[target_bone_idx];
for (int i = 0; i < entries.size(); ++i) {
Ref<SkeletonModelEntry> e = entries.get(i);
if (e->get_entry() == ive) {
e->set_count(e->get_count() - 1);
if (e->get_count() <= 0) {
entries.remove(i);
_model_dirty = true;
set_process(true);
}
return;
}
}
}
Ref<SkeletonModelEntry> CharacterSkeleton3D::get_model_entry(const int bone_index, const int index) {
ERR_FAIL_INDEX_V(bone_index, _entries.size(), Ref<SkeletonModelEntry>());
ERR_FAIL_INDEX_V(index, _entries[bone_index].size(), Ref<SkeletonModelEntry>());
return _entries[bone_index].get(index);
}
int CharacterSkeleton3D::get_model_entry_count(const int bone_index) {
ERR_FAIL_INDEX_V(bone_index, _entries.size(), 0);
return _entries[bone_index].size();
}
void CharacterSkeleton3D::sort_layers() {
for (int i = 0; i < _entries.size(); ++i) {
Vector<Ref<SkeletonModelEntry> > &entries = _entries.write[i];
entries.sort_custom<_ModelEntryComparator>();
}
}
void CharacterSkeleton3D::build_model() {
call("_build_model");
}
void CharacterSkeleton3D::_build_model() {
set_process(false);
}
Array CharacterSkeleton3D::merge_mesh_array(Array arr) const {
ERR_FAIL_COND_V(arr.size() != VisualServer::ARRAY_MAX, arr);
PoolVector3Array verts = arr[VisualServer::ARRAY_VERTEX];
PoolVector3Array normals = arr[VisualServer::ARRAY_NORMAL];
PoolVector2Array uvs = arr[VisualServer::ARRAY_TEX_UV];
PoolColorArray colors = arr[VisualServer::ARRAY_COLOR];
PoolIntArray indices = arr[VisualServer::ARRAY_INDEX];
PoolIntArray bones = arr[VisualServer::ARRAY_BONES];
PoolRealArray weights = arr[VisualServer::ARRAY_WEIGHTS];
int i = 0;
while (i < verts.size()) {
Vector3 v = verts[i];
Array equals;
for (int j = i + 1; j < verts.size(); ++j) {
Vector3 vc = verts[j];
if (Math::is_equal_approx(v.x, vc.x) && Math::is_equal_approx(v.y, vc.y) && Math::is_equal_approx(v.z, vc.z))
equals.push_back(j);
}
for (int k = 0; k < equals.size(); ++k) {
int rem = equals[k];
int remk = rem - k;
verts.remove(remk);
normals.remove(remk);
uvs.remove(remk);
colors.remove(remk);
int bindex = remk * 4;
for (int l = 0; l < 4; ++l) {
bones.remove(bindex);
weights.remove(bindex);
}
for (int j = 0; j < indices.size(); ++j) {
int indx = indices[j];
if (indx == remk)
indices.set(j, i);
else if (indx > remk)
indices.set(j, indx - 1);
}
}
++i;
}
arr[VisualServer::ARRAY_VERTEX] = verts;
arr[VisualServer::ARRAY_NORMAL] = normals;
arr[VisualServer::ARRAY_TEX_UV] = uvs;
arr[VisualServer::ARRAY_COLOR] = colors;
arr[VisualServer::ARRAY_INDEX] = indices;
arr[VisualServer::ARRAY_BONES] = bones;
arr[VisualServer::ARRAY_WEIGHTS] = weights;
return arr;
}
Array CharacterSkeleton3D::bake_mesh_array_uv(Array arr, Ref<Texture> tex, float mul_color) const {
ERR_FAIL_COND_V(arr.size() != VisualServer::ARRAY_MAX, arr);
ERR_FAIL_COND_V(!tex.is_valid(), arr);
Ref<Image> img = tex->get_data();
ERR_FAIL_COND_V(!img.is_valid(), arr);
Vector2 imgsize = img->get_size();
PoolVector2Array uvs = arr[VisualServer::ARRAY_TEX_UV];
PoolColorArray colors = arr[VisualServer::ARRAY_COLOR];
#if !GODOT4
img->lock();
#endif
for (int i = 0; i < uvs.size(); ++i) {
Vector2 uv = uvs[i];
uv *= imgsize;
Color c = img->get_pixelv(uv);
colors.set(i, colors[i] * c * mul_color);
}
#if !GODOT4
img->unlock();
#endif
arr[VisualServer::ARRAY_COLOR] = colors;
return arr;
}
CharacterSkeleton3D::CharacterSkeleton3D() {
_model_dirty = false;
_model_index = 0;
_entity_type = 0;
_animation_player = NULL;
_animation_tree = NULL;
}
CharacterSkeleton3D::~CharacterSkeleton3D() {
_attach_point_nodes.clear();
for (int i = 0; i < _entries.size(); ++i) {
_entries.write[i].clear();
}
_entries.clear();
_model_visuals.clear();
}
void CharacterSkeleton3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
update_nodes();
} break;
case NOTIFICATION_PROCESS: {
if (_model_dirty)
build_model();
} break;
case NOTIFICATION_EXIT_TREE: {
} break;
}
}
bool CharacterSkeleton3D::_set(const StringName &p_name, const Variant &p_value) {
String name = p_name;
if (name.begins_with("attach_point_paths")) {
int index = name.get_slicec('/', 1).get_slicec('_', 0).to_int();
if (index >= _attach_point_nodes.size()) {
_attach_point_nodes.resize(index + 1);
}
NodePath np = p_value;
_attach_point_nodes.write[index].path = np;
if (is_inside_tree())
_attach_point_nodes.write[index].node = get_node_or_null(p_value);
return true;
} else if (name.begins_with("bone_model_additional_mesh_transforms")) {
int index = name.get_slicec('/', 1).to_int();
if (index >= _bone_model_additional_mesh_transforms.size()) {
_bone_model_additional_mesh_transforms.resize(index + 1);
}
String p = name.get_slicec('/', 2);
if (p == "bone_index") {
int bi = p_value;
_bone_model_additional_mesh_transforms.write[index].bone_index = bi;
return true;
} else if (p == "transform") {
Transform tf = p_value;
_bone_model_additional_mesh_transforms.write[index].transform = tf;
return true;
} else if (p == "user_transform") {
Transform tf = p_value;
_bone_model_additional_mesh_transforms.write[index].user_transform = tf;
return true;
}
return false;
}
return false;
}
bool CharacterSkeleton3D::_get(const StringName &p_name, Variant &r_ret) const {
String name = p_name;
if (name.begins_with("attach_point_paths")) {
int index = name.get_slicec('/', 1).get_slicec('_', 0).to_int();
if (index >= _attach_point_nodes.size()) {
return false;
}
r_ret = _attach_point_nodes[index].path;
return true;
} else if (name.begins_with("bone_model_additional_mesh_transforms")) {
int index = name.get_slicec('/', 1).to_int();
if (index >= _bone_model_additional_mesh_transforms.size()) {
return false;
}
String p = name.get_slicec('/', 2);
if (p == "bone_index") {
r_ret = _bone_model_additional_mesh_transforms[index].bone_index;
return true;
} else if (p == "transform") {
r_ret = _bone_model_additional_mesh_transforms[index].transform;
return true;
} else if (p == "user_transform") {
r_ret = _bone_model_additional_mesh_transforms[index].user_transform;
return true;
}
return false;
}
return false;
}
void CharacterSkeleton3D::_get_property_list(List<PropertyInfo> *p_list) const {
if (ESS::get_singleton()->skeletons_bone_attachments_count() == 0) {
return;
}
String bones = ESS::get_singleton()->skeletons_bone_attachment_index_get(_entity_type);
int slicec = bones.get_slice_count(",");
for (int i = 0; i < slicec; ++i) {
p_list->push_back(PropertyInfo(Variant::NODE_PATH, "attach_point_paths/" + itos(i) + "_" + bones.get_slicec(',', i)));
}
for (int i = 0; i < _bone_model_additional_mesh_transforms.size(); ++i) {
p_list->push_back(PropertyInfo(Variant::INT, "bone_model_additional_mesh_transforms/" + itos(i) + "/bone_index", PROPERTY_HINT_ENUM, ESS::get_singleton()->skeletons_bones_index_get(_entity_type)));
p_list->push_back(PropertyInfo(Variant::TRANSFORM, "bone_model_additional_mesh_transforms/" + itos(i) + "/transform"));
p_list->push_back(PropertyInfo(Variant::TRANSFORM, "bone_model_additional_mesh_transforms/" + itos(i) + "/user_transform"));
}
}
void CharacterSkeleton3D::_validate_property(PropertyInfo &property) const {
if (property.name == "entity_type") {
property.hint_string = ESS::get_singleton()->entity_types_get();
}
}
void CharacterSkeleton3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_entity_type"), &CharacterSkeleton3D::get_entity_type);
ClassDB::bind_method(D_METHOD("set_entity_type", "value"), &CharacterSkeleton3D::set_entity_type);
ADD_PROPERTY(PropertyInfo(Variant::INT, "entity_type", PROPERTY_HINT_ENUM, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_entity_type", "get_entity_type");
ClassDB::bind_method(D_METHOD("get_model_index"), &CharacterSkeleton3D::get_model_index);
ClassDB::bind_method(D_METHOD("set_model_index", "value"), &CharacterSkeleton3D::set_model_index);
ADD_PROPERTY(PropertyInfo(Variant::INT, "model_index"), "set_model_index", "get_model_index");
ClassDB::bind_method(D_METHOD("add_model_visual", "vis"), &CharacterSkeleton3D::add_model_visual);
ClassDB::bind_method(D_METHOD("remove_model_visual", "vis"), &CharacterSkeleton3D::remove_model_visual);
ClassDB::bind_method(D_METHOD("remove_model_visual_index", "index"), &CharacterSkeleton3D::remove_model_visual_index);
ClassDB::bind_method(D_METHOD("get_model_visual", "index"), &CharacterSkeleton3D::get_model_visual);
ClassDB::bind_method(D_METHOD("get_model_visual_count"), &CharacterSkeleton3D::get_model_visual_count);
ClassDB::bind_method(D_METHOD("clear_model_visuals"), &CharacterSkeleton3D::clear_model_visuals);
BIND_VMETHOD(MethodInfo("_build_model"));
ClassDB::bind_method(D_METHOD("get_model_dirty"), &CharacterSkeleton3D::get_model_dirty);
ClassDB::bind_method(D_METHOD("set_model_dirty", "value"), &CharacterSkeleton3D::set_model_dirty);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "model_dirty"), "set_model_dirty", "get_model_dirty");
ClassDB::bind_method(D_METHOD("get_animation_player_path"), &CharacterSkeleton3D::get_animation_player_path);
ClassDB::bind_method(D_METHOD("set_animation_player_path", "path"), &CharacterSkeleton3D::set_animation_player_path);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "animation_player_path"), "set_animation_player_path", "get_animation_player_path");
ClassDB::bind_method(D_METHOD("get_animation_tree_path"), &CharacterSkeleton3D::get_animation_tree_path);
ClassDB::bind_method(D_METHOD("set_animation_tree_path", "path"), &CharacterSkeleton3D::set_animation_tree_path);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "animation_tree_path"), "set_animation_tree_path", "get_animation_tree_path");
ClassDB::bind_method(D_METHOD("bone_additional_mesh_transform_bone_index_get", "index"), &CharacterSkeleton3D::bone_additional_mesh_transform_bone_index_get);
ClassDB::bind_method(D_METHOD("bone_additional_mesh_transform_bone_index_set", "index", "bone_index"), &CharacterSkeleton3D::bone_additional_mesh_transform_bone_index_set);
ClassDB::bind_method(D_METHOD("bone_additional_mesh_transform_transform_get", "index"), &CharacterSkeleton3D::bone_additional_mesh_transform_transform_get);
ClassDB::bind_method(D_METHOD("bone_additional_mesh_transform_transform_set", "index", "transform"), &CharacterSkeleton3D::bone_additional_mesh_transform_transform_set);
ClassDB::bind_method(D_METHOD("bone_additional_mesh_transform_user_transform_get", "index"), &CharacterSkeleton3D::bone_additional_mesh_transform_user_transform_get);
ClassDB::bind_method(D_METHOD("bone_additional_mesh_transform_user_transform_set", "index", "transform"), &CharacterSkeleton3D::bone_additional_mesh_transform_user_transform_set);
ClassDB::bind_method(D_METHOD("bone_additional_mesh_transform_set_count", "size"), &CharacterSkeleton3D::bone_additional_mesh_transform_set_count);
ClassDB::bind_method(D_METHOD("bone_additional_mesh_transform_get_count"), &CharacterSkeleton3D::bone_additional_mesh_transform_get_count);
ADD_PROPERTY(PropertyInfo(Variant::INT, "bone_additional_mesh_transform_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "bone_additional_mesh_transform_set_count", "bone_additional_mesh_transform_get_count");
ClassDB::bind_method(D_METHOD("add_model_visual_entry", "vis", "ive"), &CharacterSkeleton3D::add_model_visual_entry);
ClassDB::bind_method(D_METHOD("remove_model_visual_entry", "vis", "ive"), &CharacterSkeleton3D::remove_model_visual_entry);
ClassDB::bind_method(D_METHOD("get_model_entry", "bone_index", "index"), &CharacterSkeleton3D::get_model_entry);
ClassDB::bind_method(D_METHOD("get_model_entry_count", "bone_index"), &CharacterSkeleton3D::get_model_entry_count);
ClassDB::bind_method(D_METHOD("sort_layers"), &CharacterSkeleton3D::sort_layers);
ClassDB::bind_method(D_METHOD("build_model"), &CharacterSkeleton3D::build_model);
ClassDB::bind_method(D_METHOD("_build_model"), &CharacterSkeleton3D::_build_model);
ClassDB::bind_method(D_METHOD("merge_mesh_array", "arr"), &CharacterSkeleton3D::merge_mesh_array);
ClassDB::bind_method(D_METHOD("bake_mesh_array_uv", "arr", "tex", "mul_color"), &CharacterSkeleton3D::bake_mesh_array_uv, DEFVAL(0.7));
//Bone Paths
ClassDB::bind_method(D_METHOD("attach_point_path_get", "index"), &CharacterSkeleton3D::attach_point_path_get);
ClassDB::bind_method(D_METHOD("attach_point_path_set", "index", "path"), &CharacterSkeleton3D::attach_point_path_set);
ClassDB::bind_method(D_METHOD("attach_point_node_get", "index"), &CharacterSkeleton3D::attach_point_node_get);
ClassDB::bind_method(D_METHOD("attach_point_count"), &CharacterSkeleton3D::attach_point_count);
BIND_VMETHOD(MethodInfo("_common_attach_point_index_get", PropertyInfo(Variant::INT, "point", PROPERTY_HINT_NONE, EntityEnums::BINDING_STRING_COMMON_CHARCATER_SKELETON_POINTS)));
ClassDB::bind_method(D_METHOD("common_attach_point_node_get", "point"), &CharacterSkeleton3D::common_attach_point_node_get);
ClassDB::bind_method(D_METHOD("common_attach_point_add", "point", "scene"), &CharacterSkeleton3D::common_attach_point_add);
ClassDB::bind_method(D_METHOD("common_attach_point_add_timed", "point", "scene", "time"), &CharacterSkeleton3D::common_attach_point_add_timed);
ClassDB::bind_method(D_METHOD("common_attach_point_remove", "point", "scene"), &CharacterSkeleton3D::common_attach_point_remove);
ClassDB::bind_method(D_METHOD("common_attach_point_index_get", "point"), &CharacterSkeleton3D::common_attach_point_index_get);
ClassDB::bind_method(D_METHOD("_common_attach_point_index_get", "point"), &CharacterSkeleton3D::_common_attach_point_index_get);
ClassDB::bind_method(D_METHOD("get_animation_player"), &CharacterSkeleton3D::get_animation_player);
ClassDB::bind_method(D_METHOD("get_animation_tree"), &CharacterSkeleton3D::get_animation_tree);
ClassDB::bind_method(D_METHOD("update_nodes"), &CharacterSkeleton3D::update_nodes);
}
| 34.732218 | 258 | 0.768341 | [
"object",
"vector",
"transform"
] |
ff4ea5b20f5e9a81f2b2ed5f95bb06ab3e121c81 | 16,408 | cc | C++ | prediction.cc | litvinen/large_random_fields | c6eb60ee53171d296c02dd73d26476e072360f6c | [
"BSD-2-Clause"
] | 2 | 2021-02-03T05:25:52.000Z | 2021-08-05T23:04:12.000Z | prediction.cc | litvinen/large_random_fields | c6eb60ee53171d296c02dd73d26476e072360f6c | [
"BSD-2-Clause"
] | null | null | null | prediction.cc | litvinen/large_random_fields | c6eb60ee53171d296c02dd73d26476e072360f6c | [
"BSD-2-Clause"
] | 1 | 2021-06-13T11:27:29.000Z | 2021-06-13T11:27:29.000Z | // Run like this
//./prediction --dataL competition/S1a/dataset6_training.csv --dataT competition/S1b/dataset6_testing.csv --sigma=1.14683 --length=0.0825932 --nu=0.600677 --tau=3.49e-14 --ldl
// Developed by Alexander Litvinenko (RWTH Aachen) and Ronald Kriemann (MIS MPG Leipzig)
// Based on the HLIBPro library (v. 2.9) www.hlibpro.com
// No warranties.
#include <iostream>
#include <fstream>
#include <string>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <gsl/gsl_multimin.h>
#include "hlib.hh"
using namespace std;
using boost::format;
using namespace HLIB;
using namespace boost::program_options;
using real_t = HLIB::real;
enum {
IDX_SIGMA = 0,
IDX_LENGTH = 1,
IDX_NU = 2,
IDX_TAU = 3
};
// global options
int nmin = CFG::Cluster::nmin;
double eps = 1e-6;
double fac_eps = 1e-6;
double shift = 1e-7;
bool use_ldl = false;
//
// read dataset from file
//
void
read_data ( const std::string & datafile,
std::vector< T2Point > & vertices,
BLAS::Vector< double > & Z_data_ )
{
std::ifstream in( datafile );
if ( ! in ) // error
exit( 1 );
size_t N_vtx = 0;
#if 1
std::string line;
std::getline( in, line );
if ( line == "x,y,values" )
{
std::list< T2Point > pos;
std::list< double > vals;
while ( std::getline( in, line ) )
{
auto parts = split( line, "," );
double x = atof( parts[0].c_str() );
double y = atof( parts[1].c_str() );
double v = atof( parts[2].c_str() );
pos.push_back( T2Point( x, y ) );
vals.push_back( v );
}// while
N_vtx = pos.size();
std::cout << "learning dataset" << std::endl;
std::cout << N_vtx << std::endl;
vertices.resize( N_vtx );
Z_data_ = BLAS::Vector< double >( N_vtx );
int i = 0;
for ( auto p : pos )
vertices[ i++ ] = p;
i = 0;
int j=0;
for ( auto v : vals )
{
Z_data_( i++ ) = v;
}
}// if
if ( line == "x,y,ignor" )
{
std::list< T2Point > pos;
std::list< double > vals;
while ( std::getline( in, line ) )
{
auto parts = split( line, "," );
double x = atof( parts[0].c_str() );
double y = atof( parts[1].c_str() );
double v = atof( parts[2].c_str() );
pos.push_back( T2Point( x, y ) );
// vals.push_back( v );
}// while
N_vtx = pos.size();
std::cout << "learning dataset" << std::endl;
std::cout << N_vtx << std::endl;
vertices.resize( N_vtx );
Z_data_ = BLAS::Vector< double >( N_vtx );
int i = 0;
for ( auto p : pos )
vertices[ i++ ] = p;
i = 0;
for ( auto v : vals )
Z_data_( i++ ) = 0.0;
}// if
if ( line == "x,y" )
{
std::list< T2Point > pos;
while ( std::getline( in, line ) )
{
auto parts = split( line, "," );
double x = atof( parts[0].c_str() );
double y = atof( parts[1].c_str() );
pos.push_back( T2Point( x, y ) );
}// while
N_vtx = pos.size();
std::cout << "testing dataset" << std::endl;
std::cout << N_vtx << std::endl;
vertices.resize( N_vtx );
int i = 0;
for ( auto p : pos )
vertices[ i++ ] = p;
}// if
//else
//{
// std::cout << "you should not be here" << std::endl;
// HERROR( ERR_NOT_IMPL, "", "" );
//}
#else
in >> N_vtx;
std::cout << "reading " << N_vtx << " datapoints" << std::endl;
vertices.resize( N_vtx );
Z_data_ = BLAS::Vector< double >( N_vtx );
for ( idx_t i = 0; i < idx_t(N_vtx); ++i )
{
int index = i;
double x, y, z;
// double v = 0.0;
in >> index >> x >> y >> z;
// in >> index >> x >> y >> z >> v;
vertices[ index ] = T2Point( x, y );
//Z_data( index ) = v;
}// for
#endif
//
// for visualization of data, export 2D points with v value in csv file
//
// std::ofstream out( "data.csv" );
// out << "x,y,z,v" << std::endl;
// out << "x,y,z" << std::endl;
//for ( uint i = 0; i < N_vtx; ++i )
// out << vertices[i].x() << "," << vertices[i].y() << ",0" << std::endl;
// out << vertices[i].x() << "," << vertices[i].y() << ",0," << Z_data( i ) << std::endl;
}
//
// define PredictionProblem to forecast unknown values in new locations
//
struct PredictionProblem
{
std::vector< T2Point > vertices;
std::vector< T2Point > vertices_predict;
std::unique_ptr< TCoordinate > coord;
std::unique_ptr< TCoordinate > coord_predict;
std::unique_ptr< TClusterTree > ct;
std::unique_ptr< TClusterTree > ct_predict;
std::unique_ptr< TBlockClusterTree > bct;
std::unique_ptr< TBlockClusterTree > bct_predict;
std::unique_ptr< TVector > Z;
std::unique_ptr< TVector > Z_predict;
PredictionProblem ( const std::string & datafile, const std::string & datafile_predict )
{
init( datafile, datafile_predict );
}
void
init ( const std::string & datafile, const std::string & datafile_predict )
{
BLAS::Vector< double > Z_data;
BLAS::Vector< double > Z_data_predict;
read_data( datafile, vertices, Z_data );
read_data( datafile_predict, vertices_predict, Z_data_predict );
std::cout << "both datasets are succesfully read" << std::endl;
coord = std::make_unique< TCoordinate >( vertices );
coord_predict = std::make_unique< TCoordinate >( vertices_predict );
TAutoBSPPartStrat part_strat;
TBSPCTBuilder ct_builder( & part_strat, nmin );
ct = ct_builder.build( coord.get() );
//print_vtk( & coord, "ct_coord" );
ct_predict = ct_builder.build( coord_predict.get() );
//print_vtk( & coord_predict, "ct_coord_predict" );
TStdGeomAdmCond adm_cond( 2.0, use_min_diam );
TBCBuilder bct_builder;
bct = bct_builder.build( ct.get(), ct.get(), & adm_cond );
bct_predict = bct_builder.build( ct_predict.get(), ct.get(), & adm_cond );
Z = std::make_unique< TScalarVector >( *ct->root(), std::move( Z_data ) );
Z_predict = std::make_unique< TScalarVector >( *ct_predict->root(), std::move( Z_data_predict ) );
ct->perm_e2i()->permute( Z.get() );
}
//BLAS::Vector< double >
std::unique_ptr< TVector >
eval ( const double sigma,
const double length,
const double nu,
const double tau )
{
TMaternCovCoeffFn< T2Point > matern_coefffn( sigma, length, nu, vertices );
TMaternCovCoeffFn< T2Point > matern_coefffn_predict( sigma, length, nu, vertices_predict, vertices );
TPermCoeffFn< double > coefffn( & matern_coefffn, ct->perm_i2e(), ct->perm_i2e() );
TPermCoeffFn< double > coefffn_predict( & matern_coefffn_predict, ct_predict->perm_i2e(), ct->perm_i2e() );
TACAPlus< double > aca( & coefffn );
TACAPlus< double > aca_predict( & coefffn_predict );
auto acc = fixed_prec( eps );
TDenseMatBuilder< double > h_builder( & coefffn, & aca );
TDenseMatBuilder< double > h_builder_predict( & coefffn_predict, & aca_predict );
auto C = h_builder.build( bct.get(), acc );
//TPSMatrixVis mvis;
//mvis.svd(true).print( C.get(), "myC" ); Output matrix C as a .eps file
auto C_predict= h_builder_predict.build( bct_predict.get(), unsymmetric, acc ); //A_21 - rectangular matrix
if ( shift != 0.0 )
add_identity( C.get(), tau*tau );
auto fac_acc = fixed_prec( fac_eps );
auto C_fac = C->copy();
auto fac_opts = fac_options_t{ point_wise, CFG::Arith::storage_type, false };
if ( use_ldl )
{
ldl( C_fac.get(), fac_acc, fac_opts );
//std::cout << "LDL is used " << std::endl;
}
else
{
chol( C_fac.get(), fac_acc );
//std::cout << "Cholesky is used " << std::endl;
}
//std::cout << " |С|_F = " << norm_F( C.get() ) << std::endl;
//std::cout << " |С|_2 = " << norm_2( C.get() ) << std::endl;
//std::cout << " |С_fac|_F = " << norm_F( C_fac.get() ) << std::endl;
//std::cout << " |С_fac|_2 = " << norm_2( C_fac.get() ) << std::endl;
std::unique_ptr< TFacInvMatrix > C_inv;
if ( use_ldl )
{
C_inv = std::make_unique< TLDLInvMatrix >( C_fac.get(), symmetric, point_wise );
}
else
{
C_inv = std::make_unique< TLLInvMatrix >( C_fac.get(), symmetric );
}
//std::cout << " |С_inv|_2 = " << norm_2( C_inv.get() ) << std::endl;
const size_t N = vertices.size();
TStopCriterion sstop( 350, 1e-16, 0.0 );
TCG solver( sstop );
auto sol = C->row_vector();
auto Z_predict = C_predict->row_vector();
FILE* f1;
solver.solve( C.get(), sol.get(), Z.get(), C_inv.get() );
//DBG::write( C_predict.get(), "A12.mat", "A12" );
//std::cout << " ||invC_Z|| = " << sol->norm2() << std::endl;
mul_vec( real_t(1), C_predict.get(), sol.get(), real_t(0), Z_predict.get(), apply_normal );
//std::cout << " ||Z_predict|| = " << Z_predict->norm2() << std::endl;
//C_predict->mul_vec( 1.0, sol.get(), 0.0, Z_predict.get(), apply_normal );
ct_predict->perm_i2e()->permute( Z_predict.get() );
//TMatlabVectorIO vio;
//vio.write( Z_predict, "x.mat", "x" );
f1 = fopen("111prediction.txt", "w");
for ( size_t i = 0; i < Z_predict->size(); i++ )
fprintf(f1," %.6f, %.6f, %.6f\n", vertices_predict[i].x(), vertices_predict[i].y(), Z_predict->entry(i));
fclose(f1);
return std::move( Z_predict );
}
};
//
// wrapper from GSL to LogLikeliHoodProblem
//
/*double
eval_logli ( const gsl_vector * param,
void * data )
{
double sigma = gsl_vector_get( param, IDX_SIGMA );
double length = gsl_vector_get( param, IDX_LENGTH );
double nu = gsl_vector_get( param, IDX_NU );
double tau = gsl_vector_get( param, IDX_TAU );
LogLikeliHoodProblem * problem = static_cast< LogLikeliHoodProblem * >( data );
return - problem->eval( sigma, length, nu, tau );
}
*/
//
// optimization function using GSL
//
//
// main function
//
int
main ( int argc,
char ** argv )
{
//CFG::set_verbosity( 3 );
INIT();
//std::string datafile = "datafile.txt";
//std::string datafile_predict = "datafile_predict.txt";
std::string datafile = "LearningSet.txt";
std::string datafile_predict = "TestingSet.txt";
double sigma = 2.7779; //take these values from previous experiments (Part 1a)
double length = 0.07;
double nu = 1.0365;
double tau = 4.2045e-8;
//
// define command line options
//
options_description all_opts;
options_description vis_opts( "usage: loglikelihood [options] datafile\n where options include" );
options_description hid_opts( "Hidden options" );
positional_options_description pos_opts;
variables_map vm;
// standard options
vis_opts.add_options()
( "help,h", ": print this help text" )
( "threads,t", value<int>(), ": number of parallel threads" )
( "verbosity,v", value<int>(), ": verbosity level" )
( "nmin", value<int>(), ": set minimal cluster size" )
( "eps,e", value<double>(), ": set H accuracy" )
( "epslu", value<double>(), ": set only H factorization accuracy" )
( "shift", value<double>(), ": regularization parameter" )
( "ldl", ": use LDL factorization" )
( "sigma", value<double>(), ": sigma parameter" )
( "nu", value<double>(), ": nu parameter" )
( "length", value<double>(), ": length parameter" )
( "tau", value<double>(), ": tau paramater" )
;
hid_opts.add_options()
( "dataL", value<std::string>(), ": datafile defining learning problem" )
( "dataT", value<std::string>(), ": datafile defining testing problem" )
;
// options for command line parsing
all_opts.add( vis_opts ).add( hid_opts );
// all "non-option" arguments should be "--data" arguments
pos_opts.add( "dataL", -1 );
pos_opts.add( "dataT", -1 );
//
// parse command line options
//
try
{
store( command_line_parser( argc, argv ).options( all_opts ).positional( pos_opts ).run(), vm );
notify( vm );
}// try
catch ( required_option & e )
{
std::cout << e.get_option_name() << " requires an argument, try \"-h\"" << std::endl;
exit( 1 );
}// catch
catch ( unknown_option & e )
{
std::cout << e.what() << ", try \"-h\"" << std::endl;
exit( 1 );
}// catch
//
// eval command line options
//
if ( vm.count( "help") )
{
std::cout << vis_opts << std::endl;
exit( 1 );
}// if
if ( vm.count( "nmin" ) ) nmin = vm["nmin"].as<int>();
if ( vm.count( "eps" ) ) eps = vm["eps"].as<double>();
if ( vm.count( "epslu" ) ) fac_eps = vm["epslu"].as<double>();
if ( vm.count( "shift" ) ) shift = vm["shift"].as<double>();
if ( vm.count( "threads" ) ) CFG::set_nthreads( vm["threads"].as<int>() );
if ( vm.count( "verbosity" ) ) CFG::set_verbosity( vm["verbosity"].as<int>() );
if ( vm.count( "ldl" ) ) use_ldl = true;
if ( vm.count( "sigma" ) ) sigma = vm["sigma"].as<double>();
if ( vm.count( "nu" ) ) nu = vm["nu"].as<double>();
if ( vm.count( "length" ) ) length = vm["length"].as<double>();
if ( vm.count( "tau" ) ) tau = vm["tau"].as<double>();
// default to general eps
if ( fac_eps == -1 )
fac_eps = eps;
if ( vm.count( "dataL" ) )
datafile = vm["dataL"].as<std::string>();
else
{
std::cout << "usage: loglikelihood [options] datafile" << std::endl;
exit( 1 );
}// if
if ( vm.count( "dataT" ) )
datafile_predict = vm["dataT"].as<std::string>();
else
{
std::cout << "usage: loglikelihood [options] datafile" << std::endl;
exit( 1 );
}// if
std::cout << "parameters : " << " σ = " << sigma << ", ℓ = " << length << ", ν = " << nu << ", τ = " << tau << std::endl;
PredictionProblem problem( datafile, datafile_predict );
problem.eval( sigma, length, nu, tau);
DONE();
}
| 32.555556 | 176 | 0.485373 | [
"vector"
] |
ff5039be93d09e104653ff20fcb96cfb807080b2 | 150 | cpp | C++ | 0575_distribute_candies.cpp | fxshan/LeetCode | a54bbe22bc335dcb3c7efffcc34357cab7641492 | [
"Apache-2.0"
] | 2 | 2020-06-04T13:20:20.000Z | 2020-06-04T14:49:10.000Z | 0575_distribute_candies.cpp | fxshan/LeetCode | a54bbe22bc335dcb3c7efffcc34357cab7641492 | [
"Apache-2.0"
] | null | null | null | 0575_distribute_candies.cpp | fxshan/LeetCode | a54bbe22bc335dcb3c7efffcc34357cab7641492 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int distributeCandies(vector<int>& c) {
return min(unordered_set<int>(begin(c), end(c)).size(), c.size() / 2);
}
};
| 21.428571 | 74 | 0.626667 | [
"vector"
] |
ff54205c48cb4b3f896240f73c7b8a9acbce68a2 | 5,530 | cpp | C++ | stringManipulationHelperFunctions.cpp | FlatAssembler/AECforWebAssembly | b90b7159bef35b6905b00993b3f262785748fa88 | [
"MIT"
] | 13 | 2020-09-26T10:09:08.000Z | 2022-02-25T16:54:36.000Z | stringManipulationHelperFunctions.cpp | FlatAssembler/AECforWebAssembly | b90b7159bef35b6905b00993b3f262785748fa88 | [
"MIT"
] | 12 | 2020-12-20T18:15:58.000Z | 2022-02-16T11:50:02.000Z | stringManipulationHelperFunctions.cpp | FlatAssembler/AECforWebAssembly | b90b7159bef35b6905b00993b3f262785748fa88 | [
"MIT"
] | 3 | 2021-01-17T13:19:16.000Z | 2021-09-25T16:21:01.000Z | #include <cctype>
#include <string>
#include <vector>
bool isAllWhitespace(
const std::string token) // No obvious way to do it in REGEX so that CLANG
// on Linux won't miscompile it.
{
for (unsigned i = 0; i < token.size(); i++)
if (!std::isspace(token[i]))
return false;
return true;
}
bool isAllDigits(const std::string token) {
if (!token.size())
return false;
for (unsigned i = 0; i < token.size(); i++)
if (!std::isdigit(token[i]))
return false;
return true;
}
bool isWordCharacterButNotDigit(
const char c) // No obvious way to do it in REGEX so that CLANG on Linux
// won't miscompile it.
{
return (std::isalnum(c) or c == '_') and !std::isdigit(c);
}
bool isInteger(std::string str) {
// std::regex("(^\\d+$)|(^0x(\\d|[a-f]|[A-F])+$)"), so that CLANG on Oracle
// Linux doesn't miscompile it (as it miscompiles nearly all regexes).
if (!str.size())
return false;
if (str.substr(0, 2) == "0x") { // Hexadecimal numbers...
if (str.size() == 2)
return false;
for (unsigned i = 2; i < str.size(); i++)
if (!std::isdigit(str[i]) and !((str[i] >= 'A' and str[i] <= 'F') or
(str[i] >= 'a' and str[i] <= 'f')))
return false;
return true;
}
// Integer decimal numbers...
for (unsigned i = 0; i < str.size(); i++)
if (!std::isdigit(str[i]))
return false;
return true;
}
bool isDecimalNumber(std::string str) {
if (!str.size())
return false;
bool haveWePassedOverADecimalPoint = false;
if (str[0] == '.')
return false;
for (unsigned i = 0; i < str.size(); i++)
if (str[i] == '.' and !haveWePassedOverADecimalPoint)
haveWePassedOverADecimalPoint = true;
else if (str[i] == '.')
return false;
else if (!isdigit(str[i]))
return false;
return true;
}
bool isValidVariableName(std::string str) {
// std::regex("^(_|[a-z]|[A-Z])\\w*\\[?$")
if (!str.size())
return false;
if (std::isdigit(str[0]))
return false;
for (unsigned i = 0; i < str.size(); i++)
if (!std::isalnum(str[i]) and str[i] != '_' and
!(i == str.size() - 1 and str[i] == '['))
return false;
return true;
}
bool isPointerType(std::string str) {
if (str.size() < std::string("Pointer").size())
return false;
return str.substr(str.size() - std::string("Pointer").size()) == "Pointer";
}
bool isDecimalType(std::string str) {
return str == "Decimal32" or str == "Decimal64";
}
bool isComposedOfAlnumsAndOneDot(
std::string token) // Done often in the tokenizer, so it's probably better
// (and more portable) to do it this way than in REGEX.
{
bool passedOverADot = false;
for (unsigned i = 0; i < token.size(); i++)
if (token[i] == '.' and !passedOverADot and i != 0)
passedOverADot = true;
else if (token[i] == '.')
return false;
else if (!std::isalnum(token[i]) and token[i] != '_')
return false;
return true;
}
int longest_common_subsequence_length(std::string first, std::string second) {
std::map<int, std::map<int, int>>
DP; // There are, of course, faster ways to make multi-dimensional arrays
// in C++, but let's not worry about performance of a function that
// will be run only upon an error (to suggest a true name of a
// misspelled variable name). Still, they are probably all easier than
// dealing with multi-dimensional arrays in JavaScript.
for (size_t i = 0; i < first.size();
i++) // Microsoft C++ Compiler issues a warning if you put "unsigned"
// instead of "size_t" here, I am not sure why.
for (size_t j = 0; j < second.size(); j++)
if (first[i] == second[j])
DP[i][j] = DP[i - 1][j - 1] +
1; // Had we used vectors instead of maps, we could not do
// this so simply (What if 'i' or 'j' are zero?).
else
DP[i][j] = std::max(DP[i - 1][j], DP[i][j - 1]);
return DP[first.size() - 1][second.size() - 1];
}
int Levenstein_distance(std::string A, std::string B) {
// https://discord.com/channels/530598289813536771/847014270922391563/867319320485167115
// |
// V
// https://github.com/royalpranjal/Interview-Bit/blob/master/DynamicProgramming/EditDistance.cpp
using std::min;
using std::vector;
int row = A.size();
int col = B.size();
vector<vector<int>> temp(row + 1, vector<int>(col + 1));
for (size_t i = 0; i < temp.size();
i++) { // Apparently, GCC issues a warning under "-Wall" unless you
// replace "int" with "size_t" here. I do not know why.
for (size_t j = 0; j < temp[0].size(); j++) {
if (j == 0) {
temp[i][j] = i;
} else if (i == 0) {
temp[i][j] = j;
} else if (A[i - 1] == B[j - 1]) {
temp[i][j] = temp[i - 1][j - 1];
} else {
temp[i][j] = min(temp[i - 1][j - 1], temp[i - 1][j]);
temp[i][j] = min(temp[i][j - 1], temp[i][j]);
temp[i][j] = temp[i][j] + 1;
}
}
}
return temp[row][col];
}
#define USING_LEVENSTEIN_DISTANCE
bool ends_with(
const std::string &first,
const std::string &
second) { // https://stackoverflow.com/questions/67451951/how-to-use-pointers-to-figure-out-if-a-c-string-ends-with-another-c-string/67452057?noredirect=1#comment119223072_67452057
if (second.size() > first.size())
return false;
return first.substr(first.size() - second.size()) == second;
}
| 32.529412 | 188 | 0.57396 | [
"vector"
] |
ff575cd9816c31e8755d4fd5f4a0553a3397d7e1 | 5,270 | cpp | C++ | src/win32/dll/shellx/src/BkShellX.cpp | gspu/bitkeeper | 994fb651a4045b221e33703fc3d665c3a34784e1 | [
"Apache-2.0"
] | 342 | 2016-05-10T14:59:07.000Z | 2022-03-09T23:45:43.000Z | src/win32/dll/shellx/src/BkShellX.cpp | rvs/bitkeeper | 616740d0daad99530951e46ab48e577807cbbaf4 | [
"Apache-2.0"
] | 4 | 2016-05-16T20:14:27.000Z | 2020-10-04T19:59:25.000Z | src/win32/dll/shellx/src/BkShellX.cpp | rvs/bitkeeper | 616740d0daad99530951e46ab48e577807cbbaf4 | [
"Apache-2.0"
] | 78 | 2016-05-10T15:53:30.000Z | 2022-03-09T23:46:06.000Z | /*
* Copyright 2001-2002,2007-2009,2016 BitMover, 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.
*/
// BkShellX.cpp : Implementation of DLL Exports.
#include "stdafx.h"
#include "resource.h"
#define INITGUID // Note: this has to be done only once in the whole project
#include <initguid.h>
#include "BkShellX.h"
#include "BkShellX_i.c"
#include "ContextMenuHandler.h"
#include "BkRootIcon.h"
#include "BkFileIcon.h"
#include "BkModifiedIcon.h"
#include "BkIgnoredIcon.h"
#include "BkExtraIcon.h"
#include "BkReadonlyIcon.h"
#include "system.h"
CComModule _Module;
HANDLE mailslot_thread;
BEGIN_OBJECT_MAP(ObjectMap)
OBJECT_ENTRY(CLSID_ContextMenuHandler, ContextMenuHandler)
OBJECT_ENTRY(CLSID_BkRootIcon, CBkRootIcon)
OBJECT_ENTRY(CLSID_BkModifiedIcon, CBkModifiedIcon)
OBJECT_ENTRY(CLSID_BkFileIcon, CBkFileIcon)
OBJECT_ENTRY(CLSID_BkIgnoredIcon, CBkIgnoredIcon)
OBJECT_ENTRY(CLSID_BkExtraIcon, CBkExtraIcon)
OBJECT_ENTRY(CLSID_BkReadonlyIcon, CBkReadonlyIcon)
END_OBJECT_MAP()
// DLL Entry Point
extern "C"
BOOL WINAPI
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
lpReserved;
if (dwReason == DLL_PROCESS_ATTACH) {
char *buf, *msname;
char sbuf[MAXPATH];
HANDLE mailslot;
DWORD pid;
TRACE("DLL_PROCESS_ATTACH");
_Module.Init(ObjectMap, hInstance, &LIBID_BkShellXLib);
DisableThreadLibraryCalls(hInstance);
// cache `bk bin`
if (buf = (char *)reg_get(REGKEY, "installdir", 0)) {
GetShortPathName(buf, sbuf, MAXPATH);
bkdir = strdup(sbuf);
bkexe = aprintf("%s\\bk.exe", bkdir);
TRACE("bkdir = '%s' bkexe = '%s\\bk.exe'",
bkdir, bkdir);
free(buf);
} else {
bkdir = 0;
// hope bk is in the path
bkexe = strdup("bk.exe");
TRACE("bkdir not found, using bk.exe");
}
// cache whether shellx is enabled
if (buf=(char *)reg_get(REGKEY "\\shellx", "networkDrive", 0)){
if (buf[0] == '1') shellx |= NETWORK_ENABLED;
free(buf);
}
if (buf = (char *)reg_get(REGKEY "\\shellx", "localDrive", 0)){
if (buf[0] == '1') shellx |= LOCAL_ENABLED;
free(buf);
}
// create Mutex, if the call fails, cache_mutex
// will be NULL and the cache will be used without
// a mutex... Look ma! no mutex!
unless (cache_mutex = CreateMutex(0, 0 /*don't take it*/, 0)) {
TRACE("mutex creation failed");
}
// start mailslot listener in a separate thread
pid = GetCurrentProcessId();
buf = aprintf("%u", pid);
msname = aprintf("%s\\%s", MAILSLOT, buf);
mailslot = CreateMailslot(msname, 0, MAILSLOT_WAIT_FOREVER, 0);
if (mailslot == INVALID_HANDLE_VALUE) {
TRACE("mailslot creation failed: %d", GetLastError());
} else {
TRACE("Starting mailbox for process %u", buf);
mailslot_thread = CreateThread(0, 0, cache_mailslot,
(void *)mailslot, 0, 0);
if (reg_set(MAILSLOTKEY,
buf, REG_DWORD, &pid, 0)) {
TRACE("Could not create registry value: %lu",
GetLastError());
} else {
TRACE("added registry key for %s", buf);
}
}
free(buf);
free(msname);
} else if (dwReason == DLL_PROCESS_DETACH) {
char *buf;
DWORD pid;
_Module.Term();
// free caches
if (bkdir) free(bkdir);
bkdir = 0;
if (bkexe) free(bkexe);
bkexe = 0;
if (cache_mutex) CloseHandle(cache_mutex);
if (mailslot_thread) {
// kill the thread gently...
TRACE("shutting down mailslot");
cache_shutdown = 1;
unless (WaitForSingleObject(mailslot_thread,
2*MAILSLOT_DELAY) ==
WAIT_OBJECT_0) {
TRACE("Killing thread: 0x%x", mailslot_thread);
// ...then with prejudice
TerminateThread(mailslot_thread, 0);
}
CloseHandle(mailslot_thread);
pid = GetCurrentProcessId();
buf = aprintf("%u", pid);
if (reg_delete(MAILSLOTKEY, buf)) {
TRACE("Could not delete registry value");
} else {
TRACE("Removed registry key for %s", buf);
}
free(buf);
}
TRACE("DLL_PROCESS_DETACH");
} else if (dwReason == DLL_THREAD_ATTACH) {
TRACE("DLL_THREAD_ATTACH");
} else if (dwReason == DLL_THREAD_DETACH) {
TRACE("DLL_THREAD_DETACH");
} else {
TRACE("UNKNOWN");
}
return (TRUE);
}
// Used to determine whether the DLL can be unloaded by OLE
STDAPI
DllCanUnloadNow(void)
{
return ((_Module.GetLockCount()==0) ? S_OK : S_FALSE);
}
// Returns a class factory to create an object of the requested type
STDAPI
DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
return (_Module.GetClassObject(rclsid, riid, ppv));
}
// DllRegisterServer - Adds entries to the system registry
STDAPI
DllRegisterServer(void)
{
// registers object, typelib and all interfaces in typelib
return (_Module.RegisterServer(TRUE));
}
// DllUnregisterServer - Removes entries from the system registry
STDAPI
DllUnregisterServer(void)
{
return (_Module.UnregisterServer(TRUE));
}
| 28.333333 | 76 | 0.696964 | [
"object"
] |
ff59be2eefb6a5a49fe9089bf9d4d921ae72d4af | 712 | hpp | C++ | src/gltf/v2/dc_model.hpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | src/gltf/v2/dc_model.hpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | src/gltf/v2/dc_model.hpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | #pragma once
#include "../../dc/model_if.hpp"
#include "../../dc/qm_fixed.hpp"
#include "../../dc/bbox.hpp"
namespace rev::gltf::v2 {
struct IGLTFMesh;
using HGMesh = std::shared_ptr<IGLTFMesh>;
class Scene;
class GLTFModel : public dc::IModel {
private:
using MeshV = std::vector<HGMesh>;
MeshV _mesh,
_skinmesh;
HTf _tf;
mutable dc::BSphere_Op _bsphere;
mutable dc::QM_Fixed _qm;
public:
static HMdl FromScene(const Scene& s);
GLTFModel(const MeshV& mesh, const MeshV& skinmesh, const HTf& tf);
void draw(IEffect& e) const override;
HTf getNode() const override;
dc::BSphere_Op getBSphere() const override;
DEF_DEBUGGUI_NAME
DEF_DEBUGGUI_PROP
};
}
| 24.551724 | 70 | 0.676966 | [
"mesh",
"vector"
] |
ff6efe9033dbbb57eb9846e868b310bda1c588df | 5,028 | hxx | C++ | main/package/source/package/manifest/ManifestImport.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/package/source/package/manifest/ManifestImport.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/package/source/package/manifest/ManifestImport.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
#ifndef _MANIFEST_IMPORT_HXX
#define _MANIFEST_IMPORT_HXX
#include <cppuhelper/implbase1.hxx> // helper for implementations
#ifndef _COM_SUN_STAR_XML_SAX_XDUCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#include "PackageConstants.hxx"
#include <vector>
#include <com/sun/star/beans/PropertyValues.hpp>
#include <HashMaps.hxx>
namespace com { namespace sun { namespace star {
namespace xml { namespace sax { class XAttributeList; } }
namespace beans { struct PropertyValue; }
} } }
typedef ::std::hash_map< ::rtl::OUString, ::rtl::OUString, ::rtl::OUStringHash, eqFunc > StringHashMap;
struct ManifestScopeEntry
{
::rtl::OUString m_aConvertedName;
StringHashMap m_aNamespaces;
ManifestScopeEntry( const ::rtl::OUString& aConvertedName, const StringHashMap& aNamespaces )
: m_aConvertedName( aConvertedName )
, m_aNamespaces( aNamespaces )
{}
~ManifestScopeEntry()
{}
};
typedef ::std::vector< ManifestScopeEntry > ManifestStack;
class ManifestImport : public cppu::WeakImplHelper1 < com::sun::star::xml::sax::XDocumentHandler >
{
protected:
::com::sun::star::uno::Any maValues[ PKG_SIZE_ENCR_MNFST ];
::std::vector < ::com::sun::star::beans::PropertyValues > & rManVector;
ManifestStack aStack;
sal_Int32 nDerivedKeySize;
bool bIgnoreEncryptData;
const ::rtl::OUString sCdataAttribute;
const ::rtl::OUString sMediaTypeAttribute;
const ::rtl::OUString sVersionAttribute;
const ::rtl::OUString sFullPathAttribute;
const ::rtl::OUString sSizeAttribute;
const ::rtl::OUString sSaltAttribute;
const ::rtl::OUString sInitialisationVectorAttribute;
const ::rtl::OUString sIterationCountAttribute;
const ::rtl::OUString sKeySizeAttribute;
const ::rtl::OUString sAlgorithmNameAttribute;
const ::rtl::OUString sStartKeyAlgNameAttribute;
const ::rtl::OUString sKeyDerivationNameAttribute;
const ::rtl::OUString sChecksumAttribute;
const ::rtl::OUString sChecksumTypeAttribute;
::rtl::OUString PushNameAndNamespaces( const ::rtl::OUString& aName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttribs,
StringHashMap& o_aConvertedAttribs );
::rtl::OUString ConvertNameWithNamespace( const ::rtl::OUString& aName, const StringHashMap& aNamespaces );
::rtl::OUString ConvertName( const ::rtl::OUString& aName );
public:
ManifestImport( std::vector < ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue > > & rNewVector );
~ManifestImport( void );
virtual void SAL_CALL startDocument( )
throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL endDocument( )
throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL startElement( const ::rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttribs )
throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL endElement( const ::rtl::OUString& aName )
throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL characters( const ::rtl::OUString& aChars )
throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL ignorableWhitespace( const ::rtl::OUString& aWhitespaces )
throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL processingInstruction( const ::rtl::OUString& aTarget, const ::rtl::OUString& aData )
throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDocumentLocator( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >& xLocator )
throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
};
#endif
| 44.892857 | 168 | 0.700676 | [
"vector"
] |
ff735262e60aa09c26fb71f2a5118bf079089254 | 2,203 | hpp | C++ | src/docker/attributes.hpp | HICAS-ChameLeon/Chameleon | cd0666317eb4e92a4f9fe0b2955b46bc224cf862 | [
"Apache-2.0"
] | 4 | 2019-03-06T03:04:40.000Z | 2019-07-20T15:35:00.000Z | src/docker/attributes.hpp | HICAS-ChameLeon/Chameleon | cd0666317eb4e92a4f9fe0b2955b46bc224cf862 | [
"Apache-2.0"
] | 6 | 2018-11-30T08:04:45.000Z | 2019-05-15T03:04:28.000Z | src/docker/attributes.hpp | HICAS-ChameLeon/Chameleon | cd0666317eb4e92a4f9fe0b2955b46bc224cf862 | [
"Apache-2.0"
] | 4 | 2019-03-11T11:51:22.000Z | 2020-05-11T07:27:31.000Z |
#ifndef __ATTRIBUTES_HPP__
#define __ATTRIBUTES_HPP__
// C++ 11 dependencies
#include <iterator>
#include <string>
// protobuf dependencies
#include <mesos.pb.h>
// stout dependencies
#include <stout/option.hpp>
namespace mesos {
std::ostream& operator<<(std::ostream& stream, const Attribute& attribute);
class Attributes
{
public:
Attributes() {}
/*implicit*/
Attributes(const google::protobuf::RepeatedPtrField<Attribute>& _attributes)
{
attributes.MergeFrom(_attributes);
}
/*implicit*/
Attributes(const Attributes& that)
{
attributes.MergeFrom(that.attributes);
}
Attributes& operator=(const Attributes& that)
{
if (this != &that) {
attributes.Clear();
attributes.MergeFrom(that.attributes);
}
return *this;
}
bool operator==(const Attributes& that) const;
bool operator!=(const Attributes& that) const
{
return !(*this == that);
}
size_t size() const
{
return attributes.size();
}
// Using this operator makes it easy to copy an attributes object into
// a protocol buffer field.
operator const google::protobuf::RepeatedPtrField<Attribute>&() const
{
return attributes;
}
void add(const Attribute& attribute)
{
attributes.Add()->MergeFrom(attribute);
}
const Attribute get(int index) const
{
return attributes.Get(index);
}
const Option<Attribute> get(const Attribute& thatAttribute) const;
template <typename T>
T get(const std::string& name, const T& t) const;
typedef google::protobuf::RepeatedPtrField<Attribute>::iterator
iterator;
typedef google::protobuf::RepeatedPtrField<Attribute>::const_iterator
const_iterator;
iterator begin() { return attributes.begin(); }
iterator end() { return attributes.end(); }
const_iterator begin() const { return attributes.begin(); }
const_iterator end() const { return attributes.end(); }
static Attribute parse(const std::string& name, const std::string& value);
static Attributes parse(const std::string& s);
static bool isValid(const Attribute& attribute);
private:
google::protobuf::RepeatedPtrField<Attribute> attributes;
};
} // namespace mesos {
#endif // __ATTRIBUTES_HPP__
| 20.783019 | 78 | 0.702224 | [
"object"
] |
ff768fc8295039ba9a5091d4db0fc69554e69463 | 5,704 | cpp | C++ | serial.cpp | Phlicess/wtNoe | 01dc1bcd3325a90d1ad04775aa0ff41efa93aa77 | [
"BSD-2-Clause"
] | null | null | null | serial.cpp | Phlicess/wtNoe | 01dc1bcd3325a90d1ad04775aa0ff41efa93aa77 | [
"BSD-2-Clause"
] | null | null | null | serial.cpp | Phlicess/wtNoe | 01dc1bcd3325a90d1ad04775aa0ff41efa93aa77 | [
"BSD-2-Clause"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <string>
#include <vector>
#include <sqlite3.h>
#include <set>
#include <map>
#include "protozero/varint.hpp"
#include "geometry.hpp"
#include "mbtiles.hpp"
#include "tile.hpp"
#include "serial.hpp"
size_t fwrite_check(const void *ptr, size_t size, size_t nitems, FILE *stream, const char *fname) {
size_t w = fwrite(ptr, size, nitems, stream);
if (w != nitems) {
fprintf(stderr, "%s: Write to temporary file failed: %s\n", fname, strerror(errno));
exit(EXIT_FAILURE);
}
return w;
}
void serialize_int(FILE *out, int n, long long *fpos, const char *fname) {
serialize_long_long(out, n, fpos, fname);
}
void serialize_long_long(FILE *out, long long n, long long *fpos, const char *fname) {
unsigned long long zigzag = protozero::encode_zigzag64(n);
serialize_ulong_long(out, zigzag, fpos, fname);
}
void serialize_ulong_long(FILE *out, unsigned long long zigzag, long long *fpos, const char *fname) {
while (1) {
unsigned char b = zigzag & 0x7F;
if ((zigzag >> 7) != 0) {
b |= 0x80;
if (putc(b, out) == EOF) {
fprintf(stderr, "%s: Write to temporary file failed: %s\n", fname, strerror(errno));
exit(EXIT_FAILURE);
}
*fpos += 1;
zigzag >>= 7;
} else {
if (putc(b, out) == EOF) {
fprintf(stderr, "%s: Write to temporary file failed: %s\n", fname, strerror(errno));
exit(EXIT_FAILURE);
}
*fpos += 1;
break;
}
}
}
void serialize_byte(FILE *out, signed char n, long long *fpos, const char *fname) {
fwrite_check(&n, sizeof(signed char), 1, out, fname);
*fpos += sizeof(signed char);
}
void serialize_uint(FILE *out, unsigned n, long long *fpos, const char *fname) {
fwrite_check(&n, sizeof(unsigned), 1, out, fname);
*fpos += sizeof(unsigned);
}
void deserialize_int(char **f, int *n) {
long long ll;
deserialize_long_long(f, &ll);
*n = ll;
}
void deserialize_long_long(char **f, long long *n) {
unsigned long long zigzag = 0;
deserialize_ulong_long(f, &zigzag);
*n = protozero::decode_zigzag64(zigzag);
}
void deserialize_ulong_long(char **f, unsigned long long *zigzag) {
*zigzag = 0;
int shift = 0;
while (1) {
if ((**f & 0x80) == 0) {
*zigzag |= ((unsigned long long) **f) << shift;
*f += 1;
shift += 7;
break;
} else {
*zigzag |= ((unsigned long long) (**f & 0x7F)) << shift;
*f += 1;
shift += 7;
}
}
}
void deserialize_uint(char **f, unsigned *n) {
memcpy(n, *f, sizeof(unsigned));
*f += sizeof(unsigned);
}
void deserialize_byte(char **f, signed char *n) {
memcpy(n, *f, sizeof(signed char));
*f += sizeof(signed char);
}
int deserialize_long_long_io(FILE *f, long long *n, long long *geompos) {
unsigned long long zigzag = 0;
int ret = deserialize_ulong_long_io(f, &zigzag, geompos);
*n = protozero::decode_zigzag64(zigzag);
return ret;
}
int deserialize_ulong_long_io(FILE *f, unsigned long long *zigzag, long long *geompos) {
*zigzag = 0;
int shift = 0;
while (1) {
int c = getc(f);
if (c == EOF) {
return 0;
}
(*geompos)++;
if ((c & 0x80) == 0) {
*zigzag |= ((unsigned long long) c) << shift;
shift += 7;
break;
} else {
*zigzag |= ((unsigned long long) (c & 0x7F)) << shift;
shift += 7;
}
}
return 1;
}
int deserialize_int_io(FILE *f, int *n, long long *geompos) {
long long ll = 0;
int ret = deserialize_long_long_io(f, &ll, geompos);
*n = ll;
return ret;
}
int deserialize_uint_io(FILE *f, unsigned *n, long long *geompos) {
if (fread(n, sizeof(unsigned), 1, f) != 1) {
return 0;
}
*geompos += sizeof(unsigned);
return 1;
}
int deserialize_byte_io(FILE *f, signed char *n, long long *geompos) {
int c = getc(f);
if (c == EOF) {
return 0;
}
*n = c;
(*geompos)++;
return 1;
}
static void write_geometry(drawvec const &dv, long long *fpos, FILE *out, const char *fname, long long wx, long long wy) {
for (size_t i = 0; i < dv.size(); i++) {
if (dv[i].op == VT_MOVETO || dv[i].op == VT_LINETO) {
serialize_byte(out, dv[i].op, fpos, fname);
serialize_long_long(out, dv[i].x - wx, fpos, fname);
serialize_long_long(out, dv[i].y - wy, fpos, fname);
wx = dv[i].x;
wy = dv[i].y;
} else {
serialize_byte(out, dv[i].op, fpos, fname);
}
}
}
void serialize_feature(FILE *geomfile, serial_feature *sf, long long *geompos, const char *fname, long long wx, long long wy, bool include_minzoom) {
serialize_byte(geomfile, sf->t, geompos, fname);
serialize_long_long(geomfile, sf->seq, geompos, fname);
serialize_long_long(geomfile, (sf->layer << 3) | (sf->has_id ? 4 : 0) | (sf->has_tippecanoe_minzoom ? 2 : 0) | (sf->has_tippecanoe_maxzoom ? 1 : 0), geompos, fname);
if (sf->has_tippecanoe_minzoom) {
serialize_int(geomfile, sf->tippecanoe_minzoom, geompos, fname);
}
if (sf->has_tippecanoe_maxzoom) {
serialize_int(geomfile, sf->tippecanoe_maxzoom, geompos, fname);
}
if (sf->has_id) {
serialize_ulong_long(geomfile, sf->id, geompos, fname);
}
serialize_int(geomfile, sf->segment, geompos, fname);
write_geometry(sf->geometry, geompos, geomfile, fname, wx, wy);
serialize_byte(geomfile, VT_END, geompos, fname);
serialize_int(geomfile, sf->m, geompos, fname);
serialize_long_long(geomfile, sf->metapos, geompos, fname);
if (sf->metapos < 0 && sf->m != sf->keys.size()) {
fprintf(stderr, "Internal error: %lld doesn't match %lld\n", (long long) sf->m, (long long) sf->keys.size());
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < sf->keys.size(); i++) {
serialize_long_long(geomfile, sf->keys[i], geompos, fname);
serialize_long_long(geomfile, sf->values[i], geompos, fname);
}
if (include_minzoom) {
serialize_byte(geomfile, sf->feature_minzoom, geompos, fname);
}
}
| 26.654206 | 166 | 0.652174 | [
"geometry",
"vector"
] |
ff76a57a5c7f4ad8952cad3bb3daead4ecb81dec | 839 | hpp | C++ | src/petuum_ps_common/util/vector_clock_mt.hpp | alexrenz/bosen-2 | c61ac4e892ba2f6e02bd4595632b15f9e53450e2 | [
"BSD-3-Clause"
] | 370 | 2015-06-30T09:46:17.000Z | 2017-01-21T07:14:00.000Z | src/petuum_ps_common/util/vector_clock_mt.hpp | alexrenz/bosen-2 | c61ac4e892ba2f6e02bd4595632b15f9e53450e2 | [
"BSD-3-Clause"
] | 3 | 2016-11-08T19:45:19.000Z | 2016-11-11T13:21:19.000Z | src/petuum_ps_common/util/vector_clock_mt.hpp | alexrenz/bosen-2 | c61ac4e892ba2f6e02bd4595632b15f9e53450e2 | [
"BSD-3-Clause"
] | 159 | 2015-07-03T05:58:31.000Z | 2016-12-29T20:59:01.000Z | // author: jinliang
#pragma once
#include <petuum_ps_common/util/vector_clock.hpp>
#include <petuum_ps_common/util/lock.hpp>
#include <boost/noncopyable.hpp>
#include <glog/logging.h>
#include <boost/thread.hpp>
#include <vector>
#include <cstdint>
namespace petuum {
// VectorClock is a thread-safe extension of VectorClockST.
class VectorClockMT : public VectorClock, boost::noncopyable {
public:
VectorClockMT();
explicit VectorClockMT(const std::vector<int32_t>& ids);
// Override VectorClock
void AddClock(int32_t id, int32_t clock = 0);
int32_t Tick(int32_t id);
int32_t TickUntil(int32_t id, int32_t clock);
// Accessor to a particular clock.
int32_t get_clock(int32_t id) const;
int32_t get_min_clock() const;
private:
// Lock for slowest record
mutable SharedMutex mutex_;
};
} // namespace petuum
| 22.675676 | 62 | 0.74851 | [
"vector"
] |
ff7b9b2d25b637b49c63bcd41b93c33ccb0929b8 | 40,696 | hh | C++ | third_party/harfbuzz/src/hb-ot-glyf-table.hh | panda-factory/showmaker | cd76586af8227e2325f44b28f3c93aadec6b22ea | [
"Apache-2.0"
] | 48 | 2020-11-18T23:14:25.000Z | 2022-03-11T09:13:42.000Z | third_party/harfbuzz/src/hb-ot-glyf-table.hh | panda-factory/showmaker | cd76586af8227e2325f44b28f3c93aadec6b22ea | [
"Apache-2.0"
] | 1 | 2021-10-12T08:44:43.000Z | 2021-10-12T08:44:43.000Z | third_party/harfbuzz/src/hb-ot-glyf-table.hh | panda-factory/wtf | cd76586af8227e2325f44b28f3c93aadec6b22ea | [
"Apache-2.0"
] | 3 | 2020-12-22T02:40:39.000Z | 2021-10-08T02:54:22.000Z | /*
* Copyright © 2015 Google, Inc.
* Copyright © 2019 Adobe Inc.
* Copyright © 2019 Ebrahim Byagowi
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Behdad Esfahbod, Garret Rieger, Roderick Sheeter
* Adobe Author(s): Michiharu Ariza
*/
#ifndef HB_OT_GLYF_TABLE_HH
#define HB_OT_GLYF_TABLE_HH
#include "hb-open-type.hh"
#include "hb-ot-head-table.hh"
#include "hb-ot-hmtx-table.hh"
#include "hb-ot-var-gvar-table.hh"
#include "hb-draw.hh"
namespace OT {
/*
* loca -- Index to Location
* https://docs.microsoft.com/en-us/typography/opentype/spec/loca
*/
#define HB_OT_TAG_loca HB_TAG('l','o','c','a')
#ifndef HB_MAX_COMPOSITE_OPERATIONS
#define HB_MAX_COMPOSITE_OPERATIONS 100000
#endif
struct loca
{
friend struct glyf;
static constexpr hb_tag_t tableTag = HB_OT_TAG_loca;
bool sanitize (hb_sanitize_context_t *c HB_UNUSED) const
{
TRACE_SANITIZE (this);
return_trace (true);
}
protected:
UnsizedArrayOf<HBUINT8>
dataZ; /* Location data. */
public:
DEFINE_SIZE_MIN (0); /* In reality, this is UNBOUNDED() type; but since we always
* check the size externally, allow Null() object of it by
* defining it _MIN instead. */
};
/*
* glyf -- TrueType Glyph Data
* https://docs.microsoft.com/en-us/typography/opentype/spec/glyf
*/
#define HB_OT_TAG_glyf HB_TAG('g','l','y','f')
struct glyf
{
static constexpr hb_tag_t tableTag = HB_OT_TAG_glyf;
bool sanitize (hb_sanitize_context_t *c HB_UNUSED) const
{
TRACE_SANITIZE (this);
/* Runtime checks as eager sanitizing each glyph is costy */
return_trace (true);
}
template<typename Iterator,
hb_requires (hb_is_source_of (Iterator, unsigned int))>
static bool
_add_loca_and_head (hb_subset_plan_t * plan, Iterator padded_offsets)
{
unsigned max_offset =
+ padded_offsets
| hb_reduce (hb_add, 0)
;
unsigned num_offsets = padded_offsets.len () + 1;
bool use_short_loca = max_offset < 0x1FFFF;
unsigned entry_size = use_short_loca ? 2 : 4;
char *loca_prime_data = (char *) hb_calloc (entry_size, num_offsets);
if (unlikely (!loca_prime_data)) return false;
DEBUG_MSG (SUBSET, nullptr, "loca entry_size %d num_offsets %d "
"max_offset %d size %d",
entry_size, num_offsets, max_offset, entry_size * num_offsets);
if (use_short_loca)
_write_loca (padded_offsets, 1, hb_array ((HBUINT16 *) loca_prime_data, num_offsets));
else
_write_loca (padded_offsets, 0, hb_array ((HBUINT32 *) loca_prime_data, num_offsets));
hb_blob_t *loca_blob = hb_blob_create (loca_prime_data,
entry_size * num_offsets,
HB_MEMORY_MODE_WRITABLE,
loca_prime_data,
hb_free);
bool result = plan->add_table (HB_OT_TAG_loca, loca_blob)
&& _add_head_and_set_loca_version (plan, use_short_loca);
hb_blob_destroy (loca_blob);
return result;
}
template<typename IteratorIn, typename IteratorOut,
hb_requires (hb_is_source_of (IteratorIn, unsigned int)),
hb_requires (hb_is_sink_of (IteratorOut, unsigned))>
static void
_write_loca (IteratorIn it, unsigned right_shift, IteratorOut dest)
{
unsigned int offset = 0;
dest << 0;
+ it
| hb_map ([=, &offset] (unsigned int padded_size)
{
offset += padded_size;
DEBUG_MSG (SUBSET, nullptr, "loca entry offset %d", offset);
return offset >> right_shift;
})
| hb_sink (dest)
;
}
/* requires source of SubsetGlyph complains the identifier isn't declared */
template <typename Iterator>
bool serialize (hb_serialize_context_t *c,
Iterator it,
const hb_subset_plan_t *plan)
{
TRACE_SERIALIZE (this);
unsigned init_len = c->length ();
for (const auto &_ : it) _.serialize (c, plan);
/* As a special case when all glyph in the font are empty, add a zero byte
* to the table, so that OTS doesn’t reject it, and to make the table work
* on Windows as well.
* See https://github.com/khaledhosny/ots/issues/52 */
if (init_len == c->length ())
{
HBUINT8 empty_byte;
empty_byte = 0;
c->copy (empty_byte);
}
return_trace (true);
}
/* Byte region(s) per glyph to output
unpadded, hints removed if so requested
If we fail to process a glyph we produce an empty (0-length) glyph */
bool subset (hb_subset_context_t *c) const
{
TRACE_SUBSET (this);
glyf *glyf_prime = c->serializer->start_embed <glyf> ();
if (unlikely (!c->serializer->check_success (glyf_prime))) return_trace (false);
hb_vector_t<SubsetGlyph> glyphs;
_populate_subset_glyphs (c->plan, &glyphs);
glyf_prime->serialize (c->serializer, hb_iter (glyphs), c->plan);
auto padded_offsets =
+ hb_iter (glyphs)
| hb_map (&SubsetGlyph::padded_size)
;
if (unlikely (c->serializer->in_error ())) return_trace (false);
return_trace (c->serializer->check_success (_add_loca_and_head (c->plan,
padded_offsets)));
}
template <typename SubsetGlyph>
void
_populate_subset_glyphs (const hb_subset_plan_t *plan,
hb_vector_t<SubsetGlyph> *glyphs /* OUT */) const
{
OT::glyf::accelerator_t glyf;
glyf.init (plan->source);
+ hb_range (plan->num_output_glyphs ())
| hb_map ([&] (hb_codepoint_t new_gid)
{
SubsetGlyph subset_glyph = {0};
subset_glyph.new_gid = new_gid;
/* should never fail: all old gids should be mapped */
if (!plan->old_gid_for_new_gid (new_gid, &subset_glyph.old_gid))
return subset_glyph;
if (new_gid == 0 &&
!(plan->flags & HB_SUBSET_FLAGS_NOTDEF_OUTLINE))
subset_glyph.source_glyph = Glyph ();
else
subset_glyph.source_glyph = glyf.glyph_for_gid (subset_glyph.old_gid, true);
if (plan->flags & HB_SUBSET_FLAGS_NO_HINTING)
subset_glyph.drop_hints_bytes ();
else
subset_glyph.dest_start = subset_glyph.source_glyph.get_bytes ();
return subset_glyph;
})
| hb_sink (glyphs)
;
glyf.fini ();
}
static bool
_add_head_and_set_loca_version (hb_subset_plan_t *plan, bool use_short_loca)
{
hb_blob_t *head_blob = hb_sanitize_context_t ().reference_table<head> (plan->source);
hb_blob_t *head_prime_blob = hb_blob_copy_writable_or_fail (head_blob);
hb_blob_destroy (head_blob);
if (unlikely (!head_prime_blob))
return false;
head *head_prime = (head *) hb_blob_get_data_writable (head_prime_blob, nullptr);
head_prime->indexToLocFormat = use_short_loca ? 0 : 1;
bool success = plan->add_table (HB_OT_TAG_head, head_prime_blob);
hb_blob_destroy (head_prime_blob);
return success;
}
struct CompositeGlyphChain
{
protected:
enum composite_glyph_flag_t
{
ARG_1_AND_2_ARE_WORDS = 0x0001,
ARGS_ARE_XY_VALUES = 0x0002,
ROUND_XY_TO_GRID = 0x0004,
WE_HAVE_A_SCALE = 0x0008,
MORE_COMPONENTS = 0x0020,
WE_HAVE_AN_X_AND_Y_SCALE = 0x0040,
WE_HAVE_A_TWO_BY_TWO = 0x0080,
WE_HAVE_INSTRUCTIONS = 0x0100,
USE_MY_METRICS = 0x0200,
OVERLAP_COMPOUND = 0x0400,
SCALED_COMPONENT_OFFSET = 0x0800,
UNSCALED_COMPONENT_OFFSET = 0x1000
};
public:
unsigned int get_size () const
{
unsigned int size = min_size;
/* arg1 and 2 are int16 */
if (flags & ARG_1_AND_2_ARE_WORDS) size += 4;
/* arg1 and 2 are int8 */
else size += 2;
/* One x 16 bit (scale) */
if (flags & WE_HAVE_A_SCALE) size += 2;
/* Two x 16 bit (xscale, yscale) */
else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) size += 4;
/* Four x 16 bit (xscale, scale01, scale10, yscale) */
else if (flags & WE_HAVE_A_TWO_BY_TWO) size += 8;
return size;
}
void set_glyph_index (hb_codepoint_t new_gid) { glyphIndex = new_gid; }
hb_codepoint_t get_glyph_index () const { return glyphIndex; }
void drop_instructions_flag () { flags = (uint16_t) flags & ~WE_HAVE_INSTRUCTIONS; }
void set_overlaps_flag ()
{
flags = (uint16_t) flags | OVERLAP_COMPOUND;
}
bool has_instructions () const { return flags & WE_HAVE_INSTRUCTIONS; }
bool has_more () const { return flags & MORE_COMPONENTS; }
bool is_use_my_metrics () const { return flags & USE_MY_METRICS; }
bool is_anchored () const { return !(flags & ARGS_ARE_XY_VALUES); }
void get_anchor_points (unsigned int &point1, unsigned int &point2) const
{
const HBUINT8 *p = &StructAfter<const HBUINT8> (glyphIndex);
if (flags & ARG_1_AND_2_ARE_WORDS)
{
point1 = ((const HBUINT16 *) p)[0];
point2 = ((const HBUINT16 *) p)[1];
}
else
{
point1 = p[0];
point2 = p[1];
}
}
void transform_points (contour_point_vector_t &points) const
{
float matrix[4];
contour_point_t trans;
if (get_transformation (matrix, trans))
{
if (scaled_offsets ())
{
points.translate (trans);
points.transform (matrix);
}
else
{
points.transform (matrix);
points.translate (trans);
}
}
}
protected:
bool scaled_offsets () const
{ return (flags & (SCALED_COMPONENT_OFFSET | UNSCALED_COMPONENT_OFFSET)) == SCALED_COMPONENT_OFFSET; }
bool get_transformation (float (&matrix)[4], contour_point_t &trans) const
{
matrix[0] = matrix[3] = 1.f;
matrix[1] = matrix[2] = 0.f;
int tx, ty;
const HBINT8 *p = &StructAfter<const HBINT8> (glyphIndex);
if (flags & ARG_1_AND_2_ARE_WORDS)
{
tx = *(const HBINT16 *) p;
p += HBINT16::static_size;
ty = *(const HBINT16 *) p;
p += HBINT16::static_size;
}
else
{
tx = *p++;
ty = *p++;
}
if (is_anchored ()) tx = ty = 0;
trans.init ((float) tx, (float) ty);
{
const F2DOT14 *points = (const F2DOT14 *) p;
if (flags & WE_HAVE_A_SCALE)
{
matrix[0] = matrix[3] = points[0].to_float ();
return true;
}
else if (flags & WE_HAVE_AN_X_AND_Y_SCALE)
{
matrix[0] = points[0].to_float ();
matrix[3] = points[1].to_float ();
return true;
}
else if (flags & WE_HAVE_A_TWO_BY_TWO)
{
matrix[0] = points[0].to_float ();
matrix[1] = points[1].to_float ();
matrix[2] = points[2].to_float ();
matrix[3] = points[3].to_float ();
return true;
}
}
return tx || ty;
}
protected:
HBUINT16 flags;
HBGlyphID glyphIndex;
public:
DEFINE_SIZE_MIN (4);
};
struct composite_iter_t : hb_iter_with_fallback_t<composite_iter_t, const CompositeGlyphChain &>
{
typedef const CompositeGlyphChain *__item_t__;
composite_iter_t (hb_bytes_t glyph_, __item_t__ current_) :
glyph (glyph_), current (nullptr), current_size (0)
{
set_next (current_);
}
composite_iter_t () : glyph (hb_bytes_t ()), current (nullptr), current_size (0) {}
const CompositeGlyphChain &__item__ () const { return *current; }
bool __more__ () const { return current; }
void __next__ ()
{
if (!current->has_more ()) { current = nullptr; return; }
set_next (&StructAtOffset<CompositeGlyphChain> (current, current_size));
}
bool operator != (const composite_iter_t& o) const
{ return glyph != o.glyph || current != o.current; }
void set_next (const CompositeGlyphChain *composite)
{
if (!glyph.check_range (composite, CompositeGlyphChain::min_size))
{
current = nullptr;
current_size = 0;
return;
}
unsigned size = composite->get_size ();
if (!glyph.check_range (composite, size))
{
current = nullptr;
current_size = 0;
return;
}
current = composite;
current_size = size;
}
private:
hb_bytes_t glyph;
__item_t__ current;
unsigned current_size;
};
enum phantom_point_index_t
{
PHANTOM_LEFT = 0,
PHANTOM_RIGHT = 1,
PHANTOM_TOP = 2,
PHANTOM_BOTTOM = 3,
PHANTOM_COUNT = 4
};
struct accelerator_t;
struct Glyph
{
enum simple_glyph_flag_t
{
FLAG_ON_CURVE = 0x01,
FLAG_X_SHORT = 0x02,
FLAG_Y_SHORT = 0x04,
FLAG_REPEAT = 0x08,
FLAG_X_SAME = 0x10,
FLAG_Y_SAME = 0x20,
FLAG_OVERLAP_SIMPLE = 0x40,
FLAG_RESERVED2 = 0x80
};
private:
struct GlyphHeader
{
bool has_data () const { return numberOfContours; }
bool get_extents (hb_font_t *font, const accelerator_t &glyf_accelerator,
hb_codepoint_t gid, hb_glyph_extents_t *extents) const
{
/* Undocumented rasterizer behavior: shift glyph to the left by (lsb - xMin), i.e., xMin = lsb */
/* extents->x_bearing = hb_min (glyph_header.xMin, glyph_header.xMax); */
extents->x_bearing = font->em_scale_x (glyf_accelerator.hmtx->get_side_bearing (gid));
extents->y_bearing = font->em_scale_y (hb_max (yMin, yMax));
extents->width = font->em_scale_x (hb_max (xMin, xMax) - hb_min (xMin, xMax));
extents->height = font->em_scale_y (hb_min (yMin, yMax) - hb_max (yMin, yMax));
return true;
}
HBINT16 numberOfContours;
/* If the number of contours is
* greater than or equal to zero,
* this is a simple glyph; if negative,
* this is a composite glyph. */
FWORD xMin; /* Minimum x for coordinate data. */
FWORD yMin; /* Minimum y for coordinate data. */
FWORD xMax; /* Maximum x for coordinate data. */
FWORD yMax; /* Maximum y for coordinate data. */
public:
DEFINE_SIZE_STATIC (10);
};
struct SimpleGlyph
{
const GlyphHeader &header;
hb_bytes_t bytes;
SimpleGlyph (const GlyphHeader &header_, hb_bytes_t bytes_) :
header (header_), bytes (bytes_) {}
unsigned int instruction_len_offset () const
{ return GlyphHeader::static_size + 2 * header.numberOfContours; }
unsigned int length (unsigned int instruction_len) const
{ return instruction_len_offset () + 2 + instruction_len; }
unsigned int instructions_length () const
{
unsigned int instruction_length_offset = instruction_len_offset ();
if (unlikely (instruction_length_offset + 2 > bytes.length)) return 0;
const HBUINT16 &instructionLength = StructAtOffset<HBUINT16> (&bytes, instruction_length_offset);
/* Out of bounds of the current glyph */
if (unlikely (length (instructionLength) > bytes.length)) return 0;
return instructionLength;
}
const Glyph trim_padding () const
{
/* based on FontTools _g_l_y_f.py::trim */
const uint8_t *glyph = (uint8_t*) bytes.arrayZ;
const uint8_t *glyph_end = glyph + bytes.length;
/* simple glyph w/contours, possibly trimmable */
glyph += instruction_len_offset ();
if (unlikely (glyph + 2 >= glyph_end)) return Glyph ();
unsigned int num_coordinates = StructAtOffset<HBUINT16> (glyph - 2, 0) + 1;
unsigned int num_instructions = StructAtOffset<HBUINT16> (glyph, 0);
glyph += 2 + num_instructions;
unsigned int coord_bytes = 0;
unsigned int coords_with_flags = 0;
while (glyph < glyph_end)
{
uint8_t flag = *glyph;
glyph++;
unsigned int repeat = 1;
if (flag & FLAG_REPEAT)
{
if (unlikely (glyph >= glyph_end)) return Glyph ();
repeat = *glyph + 1;
glyph++;
}
unsigned int xBytes, yBytes;
xBytes = yBytes = 0;
if (flag & FLAG_X_SHORT) xBytes = 1;
else if ((flag & FLAG_X_SAME) == 0) xBytes = 2;
if (flag & FLAG_Y_SHORT) yBytes = 1;
else if ((flag & FLAG_Y_SAME) == 0) yBytes = 2;
coord_bytes += (xBytes + yBytes) * repeat;
coords_with_flags += repeat;
if (coords_with_flags >= num_coordinates) break;
}
if (unlikely (coords_with_flags != num_coordinates)) return Glyph ();
return Glyph (bytes.sub_array (0, bytes.length + coord_bytes - (glyph_end - glyph)));
}
/* zero instruction length */
void drop_hints ()
{
GlyphHeader &glyph_header = const_cast<GlyphHeader &> (header);
(HBUINT16 &) StructAtOffset<HBUINT16> (&glyph_header, instruction_len_offset ()) = 0;
}
void drop_hints_bytes (hb_bytes_t &dest_start, hb_bytes_t &dest_end) const
{
unsigned int instructions_len = instructions_length ();
unsigned int glyph_length = length (instructions_len);
dest_start = bytes.sub_array (0, glyph_length - instructions_len);
dest_end = bytes.sub_array (glyph_length, bytes.length - glyph_length);
}
void set_overlaps_flag ()
{
if (unlikely (!header.numberOfContours)) return;
unsigned flags_offset = length (instructions_length ());
if (unlikely (length (flags_offset + 1) > bytes.length)) return;
HBUINT8 &first_flag = (HBUINT8 &) StructAtOffset<HBUINT16> (&bytes, flags_offset);
first_flag = (uint8_t) first_flag | FLAG_OVERLAP_SIMPLE;
}
static bool read_points (const HBUINT8 *&p /* IN/OUT */,
contour_point_vector_t &points_ /* IN/OUT */,
const hb_bytes_t &bytes,
void (* setter) (contour_point_t &_, float v),
const simple_glyph_flag_t short_flag,
const simple_glyph_flag_t same_flag)
{
float v = 0;
for (unsigned i = 0; i < points_.length; i++)
{
uint8_t flag = points_[i].flag;
if (flag & short_flag)
{
if (unlikely (!bytes.check_range (p))) return false;
if (flag & same_flag)
v += *p++;
else
v -= *p++;
}
else
{
if (!(flag & same_flag))
{
if (unlikely (!bytes.check_range ((const HBUINT16 *) p))) return false;
v += *(const HBINT16 *) p;
p += HBINT16::static_size;
}
}
setter (points_[i], v);
}
return true;
}
bool get_contour_points (contour_point_vector_t &points_ /* OUT */,
bool phantom_only = false) const
{
const HBUINT16 *endPtsOfContours = &StructAfter<HBUINT16> (header);
int num_contours = header.numberOfContours;
if (unlikely (!bytes.check_range (&endPtsOfContours[num_contours + 1]))) return false;
unsigned int num_points = endPtsOfContours[num_contours - 1] + 1;
points_.resize (num_points);
for (unsigned int i = 0; i < points_.length; i++) points_[i].init ();
if (phantom_only) return true;
for (int i = 0; i < num_contours; i++)
points_[endPtsOfContours[i]].is_end_point = true;
/* Skip instructions */
const HBUINT8 *p = &StructAtOffset<HBUINT8> (&endPtsOfContours[num_contours + 1],
endPtsOfContours[num_contours]);
/* Read flags */
for (unsigned int i = 0; i < num_points; i++)
{
if (unlikely (!bytes.check_range (p))) return false;
uint8_t flag = *p++;
points_[i].flag = flag;
if (flag & FLAG_REPEAT)
{
if (unlikely (!bytes.check_range (p))) return false;
unsigned int repeat_count = *p++;
while ((repeat_count-- > 0) && (++i < num_points))
points_[i].flag = flag;
}
}
/* Read x & y coordinates */
return read_points (p, points_, bytes, [] (contour_point_t &p, float v) { p.x = v; },
FLAG_X_SHORT, FLAG_X_SAME)
&& read_points (p, points_, bytes, [] (contour_point_t &p, float v) { p.y = v; },
FLAG_Y_SHORT, FLAG_Y_SAME);
}
};
struct CompositeGlyph
{
const GlyphHeader &header;
hb_bytes_t bytes;
CompositeGlyph (const GlyphHeader &header_, hb_bytes_t bytes_) :
header (header_), bytes (bytes_) {}
composite_iter_t get_iterator () const
{ return composite_iter_t (bytes, &StructAfter<CompositeGlyphChain, GlyphHeader> (header)); }
unsigned int instructions_length (hb_bytes_t bytes) const
{
unsigned int start = bytes.length;
unsigned int end = bytes.length;
const CompositeGlyphChain *last = nullptr;
for (auto &item : get_iterator ())
last = &item;
if (unlikely (!last)) return 0;
if (last->has_instructions ())
start = (char *) last - &bytes + last->get_size ();
if (unlikely (start > end)) return 0;
return end - start;
}
/* Trimming for composites not implemented.
* If removing hints it falls out of that. */
const Glyph trim_padding () const { return Glyph (bytes); }
void drop_hints ()
{
for (const auto &_ : get_iterator ())
const_cast<CompositeGlyphChain &> (_).drop_instructions_flag ();
}
/* Chop instructions off the end */
void drop_hints_bytes (hb_bytes_t &dest_start) const
{ dest_start = bytes.sub_array (0, bytes.length - instructions_length (bytes)); }
void set_overlaps_flag ()
{
const_cast<CompositeGlyphChain &> (StructAfter<CompositeGlyphChain, GlyphHeader> (header))
.set_overlaps_flag ();
}
};
enum glyph_type_t { EMPTY, SIMPLE, COMPOSITE };
public:
composite_iter_t get_composite_iterator () const
{
if (type != COMPOSITE) return composite_iter_t ();
return CompositeGlyph (*header, bytes).get_iterator ();
}
const Glyph trim_padding () const
{
switch (type) {
case COMPOSITE: return CompositeGlyph (*header, bytes).trim_padding ();
case SIMPLE: return SimpleGlyph (*header, bytes).trim_padding ();
default: return bytes;
}
}
void drop_hints ()
{
switch (type) {
case COMPOSITE: CompositeGlyph (*header, bytes).drop_hints (); return;
case SIMPLE: SimpleGlyph (*header, bytes).drop_hints (); return;
default: return;
}
}
void set_overlaps_flag ()
{
switch (type) {
case COMPOSITE: CompositeGlyph (*header, bytes).set_overlaps_flag (); return;
case SIMPLE: SimpleGlyph (*header, bytes).set_overlaps_flag (); return;
default: return;
}
}
void drop_hints_bytes (hb_bytes_t &dest_start, hb_bytes_t &dest_end) const
{
switch (type) {
case COMPOSITE: CompositeGlyph (*header, bytes).drop_hints_bytes (dest_start); return;
case SIMPLE: SimpleGlyph (*header, bytes).drop_hints_bytes (dest_start, dest_end); return;
default: return;
}
}
/* Note: Recursively calls itself.
* all_points includes phantom points
*/
bool get_points (hb_font_t *font, const accelerator_t &glyf_accelerator,
contour_point_vector_t &all_points /* OUT */,
bool phantom_only = false,
unsigned int depth = 0) const
{
if (unlikely (depth > HB_MAX_NESTING_LEVEL)) return false;
contour_point_vector_t points;
switch (type) {
case COMPOSITE:
{
/* pseudo component points for each component in composite glyph */
unsigned num_points = hb_len (CompositeGlyph (*header, bytes).get_iterator ());
if (unlikely (!points.resize (num_points))) return false;
for (unsigned i = 0; i < points.length; i++)
points[i].init ();
break;
}
case SIMPLE:
if (unlikely (!SimpleGlyph (*header, bytes).get_contour_points (points, phantom_only)))
return false;
break;
}
/* Init phantom points */
if (unlikely (!points.resize (points.length + PHANTOM_COUNT))) return false;
hb_array_t<contour_point_t> phantoms = points.sub_array (points.length - PHANTOM_COUNT, PHANTOM_COUNT);
{
for (unsigned i = 0; i < PHANTOM_COUNT; ++i) phantoms[i].init ();
int h_delta = (int) header->xMin - glyf_accelerator.hmtx->get_side_bearing (gid);
int v_orig = (int) header->yMax + glyf_accelerator.vmtx->get_side_bearing (gid);
unsigned h_adv = glyf_accelerator.hmtx->get_advance (gid);
unsigned v_adv = glyf_accelerator.vmtx->get_advance (gid);
phantoms[PHANTOM_LEFT].x = h_delta;
phantoms[PHANTOM_RIGHT].x = h_adv + h_delta;
phantoms[PHANTOM_TOP].y = v_orig;
phantoms[PHANTOM_BOTTOM].y = v_orig - (int) v_adv;
}
#ifndef HB_NO_VAR
if (unlikely (!glyf_accelerator.gvar->apply_deltas_to_points (gid, font, points.as_array ())))
return false;
#endif
switch (type) {
case SIMPLE:
all_points.extend (points.as_array ());
break;
case COMPOSITE:
{
unsigned int comp_index = 0;
for (auto &item : get_composite_iterator ())
{
contour_point_vector_t comp_points;
if (unlikely (!glyf_accelerator.glyph_for_gid (item.get_glyph_index ())
.get_points (font, glyf_accelerator, comp_points,
phantom_only, depth + 1)
|| comp_points.length < PHANTOM_COUNT))
return false;
/* Copy phantom points from component if USE_MY_METRICS flag set */
if (item.is_use_my_metrics ())
for (unsigned int i = 0; i < PHANTOM_COUNT; i++)
phantoms[i] = comp_points[comp_points.length - PHANTOM_COUNT + i];
/* Apply component transformation & translation */
item.transform_points (comp_points);
/* Apply translation from gvar */
comp_points.translate (points[comp_index]);
if (item.is_anchored ())
{
unsigned int p1, p2;
item.get_anchor_points (p1, p2);
if (likely (p1 < all_points.length && p2 < comp_points.length))
{
contour_point_t delta;
delta.init (all_points[p1].x - comp_points[p2].x,
all_points[p1].y - comp_points[p2].y);
comp_points.translate (delta);
}
}
all_points.extend (comp_points.sub_array (0, comp_points.length - PHANTOM_COUNT));
comp_index++;
}
all_points.extend (phantoms);
} break;
default:
all_points.extend (phantoms);
}
if (depth == 0) /* Apply at top level */
{
/* Undocumented rasterizer behavior:
* Shift points horizontally by the updated left side bearing
*/
contour_point_t delta;
delta.init (-phantoms[PHANTOM_LEFT].x, 0.f);
if (delta.x) all_points.translate (delta);
}
return true;
}
bool get_extents (hb_font_t *font, const accelerator_t &glyf_accelerator,
hb_glyph_extents_t *extents) const
{
if (type == EMPTY) return true; /* Empty glyph; zero extents. */
return header->get_extents (font, glyf_accelerator, gid, extents);
}
hb_bytes_t get_bytes () const { return bytes; }
Glyph (hb_bytes_t bytes_ = hb_bytes_t (),
hb_codepoint_t gid_ = (hb_codepoint_t) -1) : bytes (bytes_), gid (gid_),
header (bytes.as<GlyphHeader> ())
{
int num_contours = header->numberOfContours;
if (unlikely (num_contours == 0)) type = EMPTY;
else if (num_contours > 0) type = SIMPLE;
else type = COMPOSITE; /* negative numbers */
}
protected:
hb_bytes_t bytes;
hb_codepoint_t gid;
const GlyphHeader *header;
unsigned type;
};
struct accelerator_t
{
void init (hb_face_t *face_)
{
short_offset = false;
num_glyphs = 0;
loca_table = nullptr;
glyf_table = nullptr;
#ifndef HB_NO_VAR
gvar = nullptr;
#endif
hmtx = nullptr;
vmtx = nullptr;
face = face_;
const OT::head &head = *face->table.head;
if (head.indexToLocFormat > 1 || head.glyphDataFormat > 0)
/* Unknown format. Leave num_glyphs=0, that takes care of disabling us. */
return;
short_offset = 0 == head.indexToLocFormat;
loca_table = hb_sanitize_context_t ().reference_table<loca> (face);
glyf_table = hb_sanitize_context_t ().reference_table<glyf> (face);
#ifndef HB_NO_VAR
gvar = face->table.gvar;
#endif
hmtx = face->table.hmtx;
vmtx = face->table.vmtx;
num_glyphs = hb_max (1u, loca_table.get_length () / (short_offset ? 2 : 4)) - 1;
num_glyphs = hb_min (num_glyphs, face->get_num_glyphs ());
}
void fini ()
{
loca_table.destroy ();
glyf_table.destroy ();
}
protected:
template<typename T>
bool get_points (hb_font_t *font, hb_codepoint_t gid, T consumer) const
{
if (gid >= num_glyphs) return false;
/* Making this allocfree is not that easy
https://github.com/harfbuzz/harfbuzz/issues/2095
mostly because of gvar handling in VF fonts,
perhaps a separate path for non-VF fonts can be considered */
contour_point_vector_t all_points;
bool phantom_only = !consumer.is_consuming_contour_points ();
if (unlikely (!glyph_for_gid (gid).get_points (font, *this, all_points, phantom_only)))
return false;
if (consumer.is_consuming_contour_points ())
{
for (unsigned point_index = 0; point_index + 4 < all_points.length; ++point_index)
consumer.consume_point (all_points[point_index]);
consumer.points_end ();
}
/* Where to write phantoms, nullptr if not requested */
contour_point_t *phantoms = consumer.get_phantoms_sink ();
if (phantoms)
for (unsigned i = 0; i < PHANTOM_COUNT; ++i)
phantoms[i] = all_points[all_points.length - PHANTOM_COUNT + i];
return true;
}
#ifndef HB_NO_VAR
struct points_aggregator_t
{
hb_font_t *font;
hb_glyph_extents_t *extents;
contour_point_t *phantoms;
struct contour_bounds_t
{
contour_bounds_t () { min_x = min_y = FLT_MAX; max_x = max_y = -FLT_MAX; }
void add (const contour_point_t &p)
{
min_x = hb_min (min_x, p.x);
min_y = hb_min (min_y, p.y);
max_x = hb_max (max_x, p.x);
max_y = hb_max (max_y, p.y);
}
bool empty () const { return (min_x >= max_x) || (min_y >= max_y); }
void get_extents (hb_font_t *font, hb_glyph_extents_t *extents)
{
if (unlikely (empty ()))
{
extents->width = 0;
extents->x_bearing = 0;
extents->height = 0;
extents->y_bearing = 0;
return;
}
extents->x_bearing = font->em_scalef_x (min_x);
extents->width = font->em_scalef_x (max_x) - extents->x_bearing;
extents->y_bearing = font->em_scalef_y (max_y);
extents->height = font->em_scalef_y (min_y) - extents->y_bearing;
}
protected:
float min_x, min_y, max_x, max_y;
} bounds;
points_aggregator_t (hb_font_t *font_, hb_glyph_extents_t *extents_, contour_point_t *phantoms_)
{
font = font_;
extents = extents_;
phantoms = phantoms_;
if (extents) bounds = contour_bounds_t ();
}
void consume_point (const contour_point_t &point) { bounds.add (point); }
void points_end () { bounds.get_extents (font, extents); }
bool is_consuming_contour_points () { return extents; }
contour_point_t *get_phantoms_sink () { return phantoms; }
};
public:
unsigned
get_advance_var (hb_font_t *font, hb_codepoint_t gid, bool is_vertical) const
{
if (unlikely (gid >= num_glyphs)) return 0;
bool success = false;
contour_point_t phantoms[PHANTOM_COUNT];
if (likely (font->num_coords == gvar->get_axis_count ()))
success = get_points (font, gid, points_aggregator_t (font, nullptr, phantoms));
if (unlikely (!success))
return is_vertical ? vmtx->get_advance (gid) : hmtx->get_advance (gid);
float result = is_vertical
? phantoms[PHANTOM_TOP].y - phantoms[PHANTOM_BOTTOM].y
: phantoms[PHANTOM_RIGHT].x - phantoms[PHANTOM_LEFT].x;
return hb_clamp (roundf (result), 0.f, (float) UINT_MAX / 2);
}
int get_side_bearing_var (hb_font_t *font, hb_codepoint_t gid, bool is_vertical) const
{
if (unlikely (gid >= num_glyphs)) return 0;
hb_glyph_extents_t extents;
contour_point_t phantoms[PHANTOM_COUNT];
if (unlikely (!get_points (font, gid, points_aggregator_t (font, &extents, phantoms))))
return is_vertical ? vmtx->get_side_bearing (gid) : hmtx->get_side_bearing (gid);
return is_vertical
? ceilf (phantoms[PHANTOM_TOP].y) - extents.y_bearing
: floorf (phantoms[PHANTOM_LEFT].x);
}
#endif
public:
bool get_extents (hb_font_t *font, hb_codepoint_t gid, hb_glyph_extents_t *extents) const
{
if (unlikely (gid >= num_glyphs)) return false;
#ifndef HB_NO_VAR
if (font->num_coords && font->num_coords == gvar->get_axis_count ())
return get_points (font, gid, points_aggregator_t (font, extents, nullptr));
#endif
return glyph_for_gid (gid).get_extents (font, *this, extents);
}
const Glyph
glyph_for_gid (hb_codepoint_t gid, bool needs_padding_removal = false) const
{
if (unlikely (gid >= num_glyphs)) return Glyph ();
unsigned int start_offset, end_offset;
if (short_offset)
{
const HBUINT16 *offsets = (const HBUINT16 *) loca_table->dataZ.arrayZ;
start_offset = 2 * offsets[gid];
end_offset = 2 * offsets[gid + 1];
}
else
{
const HBUINT32 *offsets = (const HBUINT32 *) loca_table->dataZ.arrayZ;
start_offset = offsets[gid];
end_offset = offsets[gid + 1];
}
if (unlikely (start_offset > end_offset || end_offset > glyf_table.get_length ()))
return Glyph ();
Glyph glyph (hb_bytes_t ((const char *) this->glyf_table + start_offset,
end_offset - start_offset), gid);
return needs_padding_removal ? glyph.trim_padding () : glyph;
}
unsigned
add_gid_and_children (hb_codepoint_t gid,
hb_set_t *gids_to_retain,
unsigned depth = 0,
unsigned operation_count = 0) const
{
if (unlikely (depth++ > HB_MAX_NESTING_LEVEL)) return operation_count;
if (unlikely (operation_count++ > HB_MAX_COMPOSITE_OPERATIONS)) return operation_count;
/* Check if is already visited */
if (gids_to_retain->has (gid)) return operation_count;
gids_to_retain->add (gid);
auto it = glyph_for_gid (gid).get_composite_iterator ();
while (it)
{
auto item = *(it++);
operation_count +=
add_gid_and_children (item.get_glyph_index (), gids_to_retain, depth, operation_count);
}
return operation_count;
}
#ifdef HB_EXPERIMENTAL_API
struct path_builder_t
{
hb_font_t *font;
draw_helper_t *draw_helper;
struct optional_point_t
{
optional_point_t () { has_data = false; }
optional_point_t (float x_, float y_) { x = x_; y = y_; has_data = true; }
bool has_data;
float x;
float y;
optional_point_t lerp (optional_point_t p, float t)
{ return optional_point_t (x + t * (p.x - x), y + t * (p.y - y)); }
} first_oncurve, first_offcurve, last_offcurve;
path_builder_t (hb_font_t *font_, draw_helper_t &draw_helper_)
{
font = font_;
draw_helper = &draw_helper_;
first_oncurve = first_offcurve = last_offcurve = optional_point_t ();
}
/* based on https://github.com/RazrFalcon/ttf-parser/blob/4f32821/src/glyf.rs#L287
See also:
* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM01/Chap1.html
* https://stackoverflow.com/a/20772557 */
void consume_point (const contour_point_t &point)
{
/* Skip empty contours */
if (unlikely (point.is_end_point && !first_oncurve.has_data && !first_offcurve.has_data))
return;
bool is_on_curve = point.flag & Glyph::FLAG_ON_CURVE;
optional_point_t p (point.x, point.y);
if (!first_oncurve.has_data)
{
if (is_on_curve)
{
first_oncurve = p;
draw_helper->move_to (font->em_scalef_x (p.x), font->em_scalef_y (p.y));
}
else
{
if (first_offcurve.has_data)
{
optional_point_t mid = first_offcurve.lerp (p, .5f);
first_oncurve = mid;
last_offcurve = p;
draw_helper->move_to (font->em_scalef_x (mid.x), font->em_scalef_y (mid.y));
}
else
first_offcurve = p;
}
}
else
{
if (last_offcurve.has_data)
{
if (is_on_curve)
{
draw_helper->quadratic_to (font->em_scalef_x (last_offcurve.x), font->em_scalef_y (last_offcurve.y),
font->em_scalef_x (p.x), font->em_scalef_y (p.y));
last_offcurve = optional_point_t ();
}
else
{
optional_point_t mid = last_offcurve.lerp (p, .5f);
draw_helper->quadratic_to (font->em_scalef_x (last_offcurve.x), font->em_scalef_y (last_offcurve.y),
font->em_scalef_x (mid.x), font->em_scalef_y (mid.y));
last_offcurve = p;
}
}
else
{
if (is_on_curve)
draw_helper->line_to (font->em_scalef_x (p.x), font->em_scalef_y (p.y));
else
last_offcurve = p;
}
}
if (point.is_end_point)
{
if (first_offcurve.has_data && last_offcurve.has_data)
{
optional_point_t mid = last_offcurve.lerp (first_offcurve, .5f);
draw_helper->quadratic_to (font->em_scalef_x (last_offcurve.x), font->em_scalef_y (last_offcurve.y),
font->em_scalef_x (mid.x), font->em_scalef_y (mid.y));
last_offcurve = optional_point_t ();
/* now check the rest */
}
if (first_offcurve.has_data && first_oncurve.has_data)
draw_helper->quadratic_to (font->em_scalef_x (first_offcurve.x), font->em_scalef_y (first_offcurve.y),
font->em_scalef_x (first_oncurve.x), font->em_scalef_y (first_oncurve.y));
else if (last_offcurve.has_data && first_oncurve.has_data)
draw_helper->quadratic_to (font->em_scalef_x (last_offcurve.x), font->em_scalef_y (last_offcurve.y),
font->em_scalef_x (first_oncurve.x), font->em_scalef_y (first_oncurve.y));
else if (first_oncurve.has_data)
draw_helper->line_to (font->em_scalef_x (first_oncurve.x), font->em_scalef_y (first_oncurve.y));
/* Getting ready for the next contour */
first_oncurve = first_offcurve = last_offcurve = optional_point_t ();
draw_helper->end_path ();
}
}
void points_end () {}
bool is_consuming_contour_points () { return true; }
contour_point_t *get_phantoms_sink () { return nullptr; }
};
bool
get_path (hb_font_t *font, hb_codepoint_t gid, draw_helper_t &draw_helper) const
{ return get_points (font, gid, path_builder_t (font, draw_helper)); }
#endif
#ifndef HB_NO_VAR
const gvar_accelerator_t *gvar;
#endif
const hmtx_accelerator_t *hmtx;
const vmtx_accelerator_t *vmtx;
private:
bool short_offset;
unsigned int num_glyphs;
hb_blob_ptr_t<loca> loca_table;
hb_blob_ptr_t<glyf> glyf_table;
hb_face_t *face;
};
struct SubsetGlyph
{
hb_codepoint_t new_gid;
hb_codepoint_t old_gid;
Glyph source_glyph;
hb_bytes_t dest_start; /* region of source_glyph to copy first */
hb_bytes_t dest_end; /* region of source_glyph to copy second */
bool serialize (hb_serialize_context_t *c,
const hb_subset_plan_t *plan) const
{
TRACE_SERIALIZE (this);
hb_bytes_t dest_glyph = dest_start.copy (c);
dest_glyph = hb_bytes_t (&dest_glyph, dest_glyph.length + dest_end.copy (c).length);
unsigned int pad_length = padding ();
DEBUG_MSG (SUBSET, nullptr, "serialize %d byte glyph, width %d pad %d", dest_glyph.length, dest_glyph.length + pad_length, pad_length);
HBUINT8 pad;
pad = 0;
while (pad_length > 0)
{
c->embed (pad);
pad_length--;
}
if (unlikely (!dest_glyph.length)) return_trace (true);
/* update components gids */
for (auto &_ : Glyph (dest_glyph).get_composite_iterator ())
{
hb_codepoint_t new_gid;
if (plan->new_gid_for_old_gid (_.get_glyph_index (), &new_gid))
const_cast<CompositeGlyphChain &> (_).set_glyph_index (new_gid);
}
if (plan->flags & HB_SUBSET_FLAGS_NO_HINTING)
Glyph (dest_glyph).drop_hints ();
if (plan->flags & HB_SUBSET_FLAGS_SET_OVERLAPS_FLAG)
Glyph (dest_glyph).set_overlaps_flag ();
return_trace (true);
}
void drop_hints_bytes ()
{ source_glyph.drop_hints_bytes (dest_start, dest_end); }
unsigned int length () const { return dest_start.length + dest_end.length; }
/* pad to 2 to ensure 2-byte loca will be ok */
unsigned int padding () const { return length () % 2; }
unsigned int padded_size () const { return length () + padding (); }
};
protected:
UnsizedArrayOf<HBUINT8>
dataZ; /* Glyphs data. */
public:
DEFINE_SIZE_MIN (0); /* In reality, this is UNBOUNDED() type; but since we always
* check the size externally, allow Null() object of it by
* defining it _MIN instead. */
};
struct glyf_accelerator_t : glyf::accelerator_t {};
} /* namespace OT */
#endif /* HB_OT_GLYF_TABLE_HH */
| 30.552553 | 141 | 0.658197 | [
"object",
"transform"
] |
ff7c38d4c4e4b6286cad33685d231d4d124515ca | 1,628 | cpp | C++ | samples/sample_rplycpp_read_surface.cpp | manlito/rplycpp | 76df2953c4c62769a1913d28a47e06709681bc66 | [
"MIT"
] | 1 | 2019-10-11T18:45:04.000Z | 2019-10-11T18:45:04.000Z | samples/sample_rplycpp_read_surface.cpp | manlito/rplycpp | 76df2953c4c62769a1913d28a47e06709681bc66 | [
"MIT"
] | null | null | null | samples/sample_rplycpp_read_surface.cpp | manlito/rplycpp | 76df2953c4c62769a1913d28a47e06709681bc66 | [
"MIT"
] | 1 | 2016-04-16T15:36:26.000Z | 2016-04-16T15:36:26.000Z | #include <functional>
#include <vector>
#include <iostream>
#include "rplycpp.hpp"
#include "my_types.hpp"
using namespace myproject;
int main(int argc, char *argv[])
{
// Some randome data type from your app logic
Surface<PointXYZRGB> cloud;
rplycpp::PLYReader reader;
reader.Open(RPLYCPP_SAMPLE_SURFACE_PLY);
auto vertices_handler = [&cloud](const std::vector<double> &vertex) {
// This is your app logic, just remember there is an array of double with all row values
// Input ply has 9 vertex properties: x y z nx ny nz red green blue
PointXYZRGB point;
point.x = vertex[0];
point.y = vertex[1];
point.z = vertex[2];
point.red = vertex[3];
point.green = vertex[4];
point.blue = vertex[5];
cloud.points.push_back(point);
};
auto faces_handler = [&cloud](const std::vector<double> &vertex_indexes) {
// Input ply has vertex indices is an array (first element is number of elements)
Face face;
face.resize(static_cast<size_t>(vertex_indexes[0]));
face[0] = vertex_indexes[1];
face[1] = vertex_indexes[2];
face[2] = vertex_indexes[3];
cloud.faces.push_back(face);
};
// Register the handlers
std::vector<rplycpp::PLYReadHandler> handlers;
handlers.push_back(vertices_handler);
handlers.push_back(faces_handler);
// Read. This will be invoke your handlers when needed
reader.Read(handlers);
// Optional close (destructor will try it anyway)
reader.Close();
// Print
for (const auto &point : cloud.points) {
std::cout << point;
}
for (const auto &face : cloud.faces) {
std::cout << face;
}
return 0;
}
| 27.133333 | 92 | 0.679975 | [
"vector"
] |
ff7e97ad9292d05554190ea16cdbd33cacba5bdd | 12,814 | cc | C++ | backend/query/feature_filter/query_size_limits_checker.cc | j143/cloud-spanner-emulator | bf8cd7da44e5c7c42eee2bb813bb117b04d86a67 | [
"Apache-2.0"
] | null | null | null | backend/query/feature_filter/query_size_limits_checker.cc | j143/cloud-spanner-emulator | bf8cd7da44e5c7c42eee2bb813bb117b04d86a67 | [
"Apache-2.0"
] | null | null | null | backend/query/feature_filter/query_size_limits_checker.cc | j143/cloud-spanner-emulator | bf8cd7da44e5c7c42eee2bb813bb117b04d86a67 | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2020 Google LLC
//
// 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 "backend/query/feature_filter/query_size_limits_checker.h"
#include <map>
#include <queue>
#include <set>
#include <utility>
#include <vector>
#include "zetasql/public/types/array_type.h"
#include "zetasql/public/types/struct_type.h"
#include "zetasql/public/types/type.h"
#include "zetasql/resolved_ast/resolved_ast.h"
#include "zetasql/resolved_ast/resolved_node.h"
#include "zetasql/resolved_ast/resolved_node_kind.pb.h"
#include "absl/status/status.h"
#include "common/errors.h"
#include "zetasql/base/ret_check.h"
#include "zetasql/base/status_macros.h"
using zetasql::ResolvedAggregateScan;
using zetasql::ResolvedMakeStruct;
using zetasql::ResolvedNode;
using zetasql::ResolvedNodeKind;
using zetasql::ResolvedParameter;
using zetasql::ResolvedProjectScan;
using zetasql::ResolvedSetOperationScan;
namespace google::spanner::emulator::backend {
const int QuerySizeLimitsChecker::kMaxJoins = 15;
const int QuerySizeLimitsChecker::kMaxNestedFunctionNodes = 75;
const int QuerySizeLimitsChecker::kMaxNestedSubqueryExpressions = 25;
const int QuerySizeLimitsChecker::kMaxNestedSubselects = 60;
const int QuerySizeLimitsChecker::kMaxNestedGroupBy = 35;
const int QuerySizeLimitsChecker::kMaxUnionsInQuery = 200;
const int QuerySizeLimitsChecker::kMaxSubqueryExpressionChildren = 40;
const int QuerySizeLimitsChecker::kMaxFunctionNodes = 1000;
const int QuerySizeLimitsChecker::kMaxColumnsInGroupBy = 1000;
const int QuerySizeLimitsChecker::kMaxParameters = 950;
const int QuerySizeLimitsChecker::kMaxStructFields = 1000;
const int QuerySizeLimitsChecker::kMaxNestedStructDepth = 15;
absl::Status QuerySizeLimitsChecker::CheckQueryAgainstLimits(
const ResolvedNode* ast_root) {
std::set<ResolvedNodeKind> interest_nodes;
interest_nodes.insert(ResolvedNodeKind::RESOLVED_JOIN_SCAN);
interest_nodes.insert(ResolvedNodeKind::RESOLVED_PROJECT_SCAN);
interest_nodes.insert(ResolvedNodeKind::RESOLVED_SUBQUERY_EXPR);
interest_nodes.insert(ResolvedNodeKind::RESOLVED_AGGREGATE_SCAN);
interest_nodes.insert(ResolvedNodeKind::RESOLVED_FUNCTION_CALL);
interest_nodes.insert(ResolvedNodeKind::RESOLVED_PARAMETER);
std::map<ResolvedNodeKind, NodeCounts> collected_node_counts;
ZETASQL_RETURN_IF_ERROR(GetNodeMetricsAndRunLocalChecks(ast_root, interest_nodes,
&collected_node_counts));
ZETASQL_RETURN_IF_ERROR(RunGlobalChecks(collected_node_counts));
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckNumPredicates(
const std::map<ResolvedNodeKind, NodeCounts>& collected_node_counts) {
auto it =
collected_node_counts.find(ResolvedNodeKind::RESOLVED_FUNCTION_CALL);
if (it == collected_node_counts.end()) {
return absl::OkStatus();
}
const auto node_counts = it->second;
if (node_counts.total_occurrences > kMaxFunctionNodes) {
return error::TooManyFunctions(kMaxFunctionNodes);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckPredicateBooleanExpressionDepth(
const std::map<ResolvedNodeKind, NodeCounts>& collected_node_counts) {
auto it =
collected_node_counts.find(ResolvedNodeKind::RESOLVED_FUNCTION_CALL);
if (it == collected_node_counts.end()) {
return absl::OkStatus();
}
const auto node_counts = it->second;
if (node_counts.nested_occurrences > kMaxNestedFunctionNodes) {
return error::TooManyNestedBooleanPredicates(kMaxNestedFunctionNodes);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckNumJoins(
const std::map<ResolvedNodeKind, NodeCounts>& collected_node_counts) {
auto it = collected_node_counts.find(ResolvedNodeKind::RESOLVED_JOIN_SCAN);
if (it == collected_node_counts.end()) {
return absl::OkStatus();
}
const auto node_counts = it->second;
if (node_counts.total_occurrences > kMaxJoins) {
return error::TooManyJoins(kMaxJoins);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckSubqueryExpressionDepth(
const std::map<ResolvedNodeKind, NodeCounts>& collected_node_counts) {
auto it =
collected_node_counts.find(ResolvedNodeKind::RESOLVED_SUBQUERY_EXPR);
if (it == collected_node_counts.end()) {
return absl::OkStatus();
}
const auto node_counts = it->second;
if (node_counts.nested_occurrences > kMaxNestedSubqueryExpressions) {
return error::TooManyNestedSubqueries(kMaxNestedSubqueryExpressions);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckSubselectDepth(
const std::map<ResolvedNodeKind, NodeCounts>& collected_node_counts) {
auto it = collected_node_counts.find(ResolvedNodeKind::RESOLVED_PROJECT_SCAN);
if (it == collected_node_counts.end()) {
return absl::OkStatus();
}
const auto node_counts = it->second;
if (node_counts.nested_occurrences > kMaxNestedSubselects) {
return error::TooManyNestedSubselects(kMaxNestedSubselects);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckGroupByDepth(
const std::map<ResolvedNodeKind, NodeCounts>& collected_node_counts) {
auto it =
collected_node_counts.find(ResolvedNodeKind::RESOLVED_AGGREGATE_SCAN);
if (it == collected_node_counts.end()) {
return absl::OkStatus();
}
const auto node_counts = it->second;
if (node_counts.nested_occurrences > kMaxNestedGroupBy) {
return error::TooManyNestedAggregates(kMaxNestedGroupBy);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckNumParameters(
const std::map<ResolvedNodeKind, NodeCounts>& collected_node_counts) {
auto it = collected_node_counts.find(ResolvedNodeKind::RESOLVED_PARAMETER);
if (it == collected_node_counts.end()) {
return absl::OkStatus();
}
const auto node_counts = it->second;
if (node_counts.total_occurrences > kMaxParameters) {
return error::TooManyParameters(kMaxParameters);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckNumColumnsInGroupBy(
const ResolvedNode* node) {
const ResolvedAggregateScan* aggregate_scan =
node->GetAs<ResolvedAggregateScan>();
ZETASQL_RET_CHECK(aggregate_scan != nullptr);
if (aggregate_scan->group_by_list().size() > kMaxColumnsInGroupBy) {
return error::TooManyAggregates(kMaxColumnsInGroupBy);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckNumUnions(const ResolvedNode* node) {
const ResolvedSetOperationScan* union_scan =
node->GetAs<ResolvedSetOperationScan>();
ZETASQL_RET_CHECK(union_scan != nullptr);
if (union_scan->input_item_list().size() > kMaxUnionsInQuery) {
return error::TooManyUnions(kMaxUnionsInQuery);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckNumSubQueriesInSelectList(
const ResolvedNode* node) {
const ResolvedProjectScan* project_scan = node->GetAs<ResolvedProjectScan>();
ZETASQL_RET_CHECK(project_scan != nullptr);
if (project_scan->expr_list_size() > kMaxSubqueryExpressionChildren) {
return error::TooManySubqueryChildren(kMaxSubqueryExpressionChildren);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckNumFieldsInStruct(
const ResolvedNode* node) {
const ResolvedMakeStruct* struct_node = node->GetAs<ResolvedMakeStruct>();
ZETASQL_RET_CHECK(struct_node != nullptr);
if (struct_node->field_list().size() > kMaxStructFields) {
return error::TooManyStructFields(kMaxStructFields);
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::CheckStructParameterBreadthAndDepth(
const ResolvedNode* node) {
const ResolvedParameter* param_node = node->GetAs<ResolvedParameter>();
ZETASQL_RET_CHECK(param_node != nullptr);
if (!param_node->type()->IsStruct() &&
!(param_node->type()->IsArray() &&
param_node->type()->AsArray()->element_type()->IsStruct())) {
return absl::OkStatus();
}
const zetasql::StructType* struct_type =
param_node->type()->IsStruct()
? param_node->type()->AsStruct()
: param_node->type()->AsArray()->element_type()->AsStruct();
std::queue<const zetasql::StructType*> type_queue;
int depth = 1;
type_queue.push(struct_type);
type_queue.push(nullptr);
while (!type_queue.empty()) {
const auto* type = type_queue.front();
type_queue.pop();
if (type == nullptr) {
if (!type_queue.empty()) {
type_queue.push(nullptr);
++depth;
if (depth > kMaxNestedStructDepth) {
return error::TooManyNestedStructs(kMaxNestedStructDepth);
}
}
continue;
}
if (type->num_fields() > kMaxStructFields) {
return error::TooManyStructFields(kMaxStructFields);
}
for (int i = 0; i < type->num_fields(); ++i) {
const zetasql::Type* next_type = nullptr;
if (type->field(i).type->IsArray()) {
next_type = type->field(i).type->AsArray()->element_type();
} else {
next_type = type->field(i).type;
}
if (next_type->IsStruct()) {
type_queue.push(next_type->AsStruct());
}
}
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::RunGlobalChecks(
const std::map<zetasql::ResolvedNodeKind, NodeCounts>&
collected_node_counts) {
ZETASQL_RETURN_IF_ERROR(CheckNumPredicates(collected_node_counts));
ZETASQL_RETURN_IF_ERROR(CheckPredicateBooleanExpressionDepth(collected_node_counts));
ZETASQL_RETURN_IF_ERROR(CheckNumJoins(collected_node_counts));
ZETASQL_RETURN_IF_ERROR(CheckSubqueryExpressionDepth(collected_node_counts));
ZETASQL_RETURN_IF_ERROR(CheckSubselectDepth(collected_node_counts));
ZETASQL_RETURN_IF_ERROR(CheckGroupByDepth(collected_node_counts));
ZETASQL_RETURN_IF_ERROR(CheckNumParameters(collected_node_counts));
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::RunNodeLocalChecks(
const ResolvedNode* node) {
switch (node->node_kind()) {
case ResolvedNodeKind::RESOLVED_AGGREGATE_SCAN:
ZETASQL_RETURN_IF_ERROR(CheckNumColumnsInGroupBy(node));
break;
case ResolvedNodeKind::RESOLVED_SET_OPERATION_SCAN:
ZETASQL_RETURN_IF_ERROR(CheckNumUnions(node));
break;
case ResolvedNodeKind::RESOLVED_MAKE_STRUCT:
ZETASQL_RETURN_IF_ERROR(CheckNumFieldsInStruct(node));
break;
case ResolvedNodeKind::RESOLVED_PROJECT_SCAN:
ZETASQL_RETURN_IF_ERROR(CheckNumSubQueriesInSelectList(node));
break;
case ResolvedNodeKind::RESOLVED_PARAMETER:
ZETASQL_RETURN_IF_ERROR(CheckStructParameterBreadthAndDepth(node));
break;
default:
return absl::OkStatus();
}
return absl::OkStatus();
}
absl::Status QuerySizeLimitsChecker::GetNodeMetricsAndRunLocalChecks(
const ResolvedNode* ast_root,
const std::set<ResolvedNodeKind>& interest_nodes,
std::map<ResolvedNodeKind, NodeCounts>* collected_node_counts) {
std::queue<const ResolvedNode*> node_queue;
node_queue.push(ast_root);
node_queue.push(nullptr);
int tree_depth = 0;
while (!node_queue.empty()) {
const ResolvedNode* node = node_queue.front();
node_queue.pop();
if (node == nullptr) {
if (!node_queue.empty()) {
node_queue.push(nullptr);
tree_depth++;
}
continue;
}
if (interest_nodes.find(node->node_kind()) != interest_nodes.end()) {
auto it = collected_node_counts->find(node->node_kind());
if (it != collected_node_counts->end()) {
NodeCounts& count_info = it->second;
count_info.total_occurrences++;
if (tree_depth > count_info.max_occurrence_depth) {
count_info.nested_occurrences++;
}
count_info.max_occurrence_depth = tree_depth;
} else {
NodeCounts node_counts;
node_counts.max_occurrence_depth = tree_depth;
node_counts.nested_occurrences = 1;
node_counts.total_occurrences = 1;
(*collected_node_counts)[node->node_kind()] = node_counts;
}
}
ZETASQL_RETURN_IF_ERROR(RunNodeLocalChecks(node));
std::vector<const ResolvedNode*> child_nodes;
node->GetChildNodes(&child_nodes);
for (const ResolvedNode* child_node : child_nodes) {
node_queue.push(child_node);
}
}
return absl::OkStatus();
}
} // namespace google::spanner::emulator::backend
| 37.142029 | 87 | 0.743718 | [
"vector"
] |
ff8035f5f8fe3d962de2f3dcfdcc2c1b6b63364c | 20,553 | cpp | C++ | multimedia/directx/dplay/dplay8/sp/serial/dpnmodemspdata.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | multimedia/directx/dplay/dplay8/sp/serial/dpnmodemspdata.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | multimedia/directx/dplay/dplay8/sp/serial/dpnmodemspdata.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*==========================================================================
*
* Copyright (C) 1999-2000 Microsoft Corporation. All Rights Reserved.
*
* File: SPData.cpp
* Content: Global variables for the DNSerial service provider in class
* format.
*
*
* History:
* Date By Reason
* ==== == ======
* 03/15/99 jtk Dereived from Locals.cpp
***************************************************************************/
#include "dnmdmi.h"
//**********************************************************************
// Constant definitions
//**********************************************************************
// default number of command descriptors to create
#define DEFAULT_COMMAND_POOL_SIZE 20
#define COMMAND_POOL_GROW_SIZE 5
//**********************************************************************
// Macro definitions
//**********************************************************************
//**********************************************************************
// Structure definitions
//**********************************************************************
//**********************************************************************
// Variable definitions
//**********************************************************************
//**********************************************************************
// Function prototypes
//**********************************************************************
//**********************************************************************
// Function definitions
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::CModemSPData - constructor
//
// Entry: Nothing
//
// Exit: Nothing
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::CModemSPData"
CModemSPData::CModemSPData():
m_lRefCount( 0 ),
m_lObjectRefCount( 0 ),
m_hShutdownEvent( NULL ),
m_SPType( TYPE_UNKNOWN ),
m_State( SPSTATE_UNINITIALIZED ),
m_pThreadPool( NULL ),
m_fLockInitialized( FALSE ),
m_fHandleTableInitialized( FALSE ),
m_fDataPortDataLockInitialized( FALSE ),
m_fInterfaceGlobalsInitialized( FALSE )
{
m_Sig[0] = 'S';
m_Sig[1] = 'P';
m_Sig[2] = 'D';
m_Sig[3] = 'T';
memset( &m_InitData, 0x00, sizeof( m_InitData ) );
memset( &m_DataPortList, 0x00, sizeof( m_DataPortList ) );
memset( &m_COMInterface, 0x00, sizeof( m_COMInterface ) );
#ifndef DPNBUILD_LIBINTERFACE
DNInterlockedIncrement( &g_lModemOutstandingInterfaceCount );
#endif // ! DPNBUILD_LIBINTERFACE
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::~CModemSPData - destructor
//
// Entry: Nothing
//
// Exit: Nothing
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::~CModemSPData"
CModemSPData::~CModemSPData()
{
UINT_PTR uIndex;
DNASSERT( m_lRefCount == 0 );
DNASSERT( m_lObjectRefCount == 0 );
DNASSERT( m_hShutdownEvent == NULL );
DNASSERT( m_SPType == TYPE_UNKNOWN );
DNASSERT( m_State == SPSTATE_UNINITIALIZED );
DNASSERT( m_pThreadPool == NULL );
uIndex = LENGTHOF( m_DataPortList );
while ( uIndex > 0 )
{
uIndex--;
DNASSERT( m_DataPortList[ uIndex ] == NULL );
}
DNASSERT( m_fLockInitialized == FALSE );
DNASSERT( m_fHandleTableInitialized == FALSE );
DNASSERT( m_fDataPortDataLockInitialized == FALSE );
DNASSERT( m_fInterfaceGlobalsInitialized == FALSE );
#ifndef DPNBUILD_LIBINTERFACE
DNInterlockedDecrement( &g_lModemOutstandingInterfaceCount );
#endif // ! DPNBUILD_LIBINTERFACE
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::Initialize - intialize
//
// Entry: Pointer to DirectNet
//
// Exit: Error code
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::Initialize"
HRESULT CModemSPData::Initialize( const SP_TYPE SPType,
IDP8ServiceProviderVtbl *const pVtbl )
{
HRESULT hr;
DNASSERT( pVtbl != NULL );
//
// initialize
//
hr = DPN_OK;
DNASSERT( m_lRefCount == 1 );
DNASSERT( m_lObjectRefCount == 0 );
DNASSERT( GetType() == TYPE_UNKNOWN );
DNASSERT( GetType() == TYPE_UNKNOWN );
m_SPType = SPType;
DNASSERT( m_COMInterface.m_pCOMVtbl == NULL );
m_COMInterface.m_pCOMVtbl = pVtbl;
DNASSERT( m_fLockInitialized == FALSE );
DNASSERT( m_fDataPortDataLockInitialized == FALSE );
DNASSERT( m_fInterfaceGlobalsInitialized == FALSE );
//
// attempt to initialize shutdown event
//
DNASSERT( m_hShutdownEvent == NULL );
m_hShutdownEvent = DNCreateEvent( NULL, // pointer to security (none)
TRUE, // manual reset
TRUE, // start signalled (so close can be called without any endpoints being created)
NULL // pointer to name (none)
);
if ( m_hShutdownEvent == NULL )
{
DWORD dwError;
dwError = GetLastError();
DPFX(DPFPREP, 0, "Failed to create event for shutting down spdata!" );
DisplayErrorCode( 0, dwError );
}
//
// initialize critical sections
//
if ( DNInitializeCriticalSection( &m_Lock ) == FALSE )
{
hr = DPNERR_OUTOFMEMORY;
DPFX(DPFPREP, 0, "Failed to initialize SP lock!" );
goto Failure;
}
DebugSetCriticalSectionRecursionCount( &m_Lock, 0 );
DebugSetCriticalSectionGroup( &m_Lock, &g_blDPNModemCritSecsHeld ); // separate dpnmodem CSes from the rest of DPlay's CSes
m_fLockInitialized = TRUE;
hr = m_HandleTable.Initialize();
if ( hr != DPN_OK )
{
DPFX(DPFPREP, 0, "Failed to initialize handle table!" );
DisplayDNError( 0, hr );
goto Failure;
}
m_fHandleTableInitialized = TRUE;
if ( DNInitializeCriticalSection( &m_DataPortDataLock ) == FALSE )
{
hr = DPNERR_OUTOFMEMORY;
DPFX(DPFPREP, 0, "Failed to initialize data port data lock!" );
goto Failure;
}
DebugSetCriticalSectionRecursionCount( &m_DataPortDataLock, 0 );
DebugSetCriticalSectionGroup( &m_DataPortDataLock, &g_blDPNModemCritSecsHeld ); // separate dpnmodem CSes from the rest of DPlay's CSes
m_fDataPortDataLockInitialized = TRUE;
//
// get a thread pool
//
DNASSERT( m_pThreadPool == NULL );
hr = InitializeInterfaceGlobals( this );
if ( hr != DPN_OK )
{
DPFX(DPFPREP, 0, "Failed to create thread pool!" );
DisplayDNError( 0, hr );
goto Failure;
}
m_fInterfaceGlobalsInitialized = TRUE;
Exit:
if ( hr != DPN_OK )
{
DPFX(DPFPREP, 0, "Problem with CModemSPData::Initialize" );
DisplayDNError( 0, hr );
}
return hr;
Failure:
Deinitialize();
goto Exit;
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::Shutdown - shut down this set of SP data
//
// Entry: Nothing
//
// Exit: Nothing
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::Shutdown"
void CModemSPData::Shutdown( void )
{
BOOL fLooping;
//
// Unbind this interface from the globals. This will cause a closure of all
// of the I/O which will release endpoints, socket ports and then this data.
//
if ( m_fInterfaceGlobalsInitialized != FALSE )
{
DeinitializeInterfaceGlobals( this );
DNASSERT( GetThreadPool() != NULL );
m_fInterfaceGlobalsInitialized = FALSE;
}
SetState( SPSTATE_CLOSING );
DNASSERT( m_hShutdownEvent != NULL );
fLooping = TRUE;
while ( fLooping != FALSE )
{
switch ( DNWaitForSingleObjectEx( m_hShutdownEvent, INFINITE, TRUE ) )
{
case WAIT_OBJECT_0:
{
fLooping = FALSE;
break;
}
case WAIT_IO_COMPLETION:
{
break;
}
default:
{
DNASSERT( FALSE );
break;
}
}
}
if ( DNCloseHandle( m_hShutdownEvent ) == FALSE )
{
DWORD dwError;
dwError = GetLastError();
DPFX(DPFPREP, 0, "Failed to close shutdown event!" );
DisplayErrorCode( 0, dwError );
}
m_hShutdownEvent = NULL;
if ( DP8SPCallbackInterface() != NULL)
{
IDP8SPCallback_Release( DP8SPCallbackInterface() );
memset( &m_InitData, 0x00, sizeof( m_InitData ) );
}
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::Deinitialize - deinitialize
//
// Entry: Nothing
//
// Exit: Nothing
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::Deinitialize"
void CModemSPData::Deinitialize( void )
{
DPFX(DPFPREP, 9, "Entering CModemSPData::Deinitialize" );
//
// deinitialize interface globals
//
if ( m_fInterfaceGlobalsInitialized != FALSE )
{
DeinitializeInterfaceGlobals( this );
DNASSERT( GetThreadPool() != NULL );
m_fInterfaceGlobalsInitialized = FALSE;
}
if ( m_fDataPortDataLockInitialized != FALSE )
{
DNDeleteCriticalSection( &m_DataPortDataLock );
m_fDataPortDataLockInitialized = FALSE;
}
if ( m_fHandleTableInitialized != FALSE )
{
m_HandleTable.Deinitialize();
m_fHandleTableInitialized = FALSE;
}
if ( m_fLockInitialized != FALSE )
{
DNDeleteCriticalSection( &m_Lock );
m_fLockInitialized = FALSE;
}
m_COMInterface.m_pCOMVtbl = NULL;
SetState( SPSTATE_UNINITIALIZED );
m_SPType = TYPE_UNKNOWN;
if ( GetThreadPool() != NULL )
{
GetThreadPool()->DecRef();
SetThreadPool( NULL );
}
if ( m_hShutdownEvent != NULL )
{
if ( DNCloseHandle( m_hShutdownEvent ) == FALSE )
{
DWORD dwError;
dwError = GetLastError();
DPFX(DPFPREP, 0, "Failed to close shutdown handle!" );
DisplayErrorCode( 0, dwError );
}
m_hShutdownEvent = NULL;
}
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::SetCallbackData - set data for SP callbacks to application
//
// Entry: Pointer to initialization data
//
// Exit: Nothing
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::SetCallbackData"
void CModemSPData::SetCallbackData( const SPINITIALIZEDATA *const pInitData )
{
DNASSERT( pInitData != NULL );
DNASSERT( pInitData->dwFlags == SP_SESSION_TYPE_PEER ||
pInitData->dwFlags == SP_SESSION_TYPE_CLIENT ||
pInitData->dwFlags == SP_SESSION_TYPE_SERVER ||
pInitData->dwFlags == 0);
m_InitData.dwFlags = pInitData->dwFlags;
DNASSERT( pInitData->pIDP != NULL );
m_InitData.pIDP = pInitData->pIDP;
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::BindEndpoint - bind endpoint to a data port
//
// Entry: Pointer to endpoint
// DeviceID
// Device context
//
// Exit: Error code
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::BindEndpoint"
HRESULT CModemSPData::BindEndpoint( CModemEndpoint *const pEndpoint,
const DWORD dwDeviceID,
const void *const pDeviceContext )
{
HRESULT hr;
CDataPort *pDataPort;
BOOL fDataPortDataLocked;
BOOL fDataPortCreated;
BOOL fDataPortBoundToNetwork;
DPFX(DPFPREP, 9, "(0x%p) Parameters: (0x%p, %u, 0x%p)",
this, pEndpoint, dwDeviceID, pDeviceContext);
//
// intialize
//
hr = DPN_OK;
pDataPort = NULL;
fDataPortDataLocked = FALSE;
fDataPortCreated = FALSE;
fDataPortBoundToNetwork = FALSE;
LockDataPortData();
fDataPortDataLocked = TRUE;
if ( m_DataPortList[ dwDeviceID ] != NULL )
{
pDataPort = m_DataPortList[ dwDeviceID ];
}
else
{
DATA_PORT_POOL_CONTEXT DataPortPoolContext;
memset( &DataPortPoolContext, 0x00, sizeof( DataPortPoolContext ) );
DataPortPoolContext.pSPData = this;
pDataPort = CreateDataPort( &DataPortPoolContext );
if ( pDataPort == NULL )
{
hr = DPNERR_OUTOFMEMORY;
DPFX(DPFPREP, 0, "Failed to create new data port!" );
goto Failure;
}
fDataPortCreated = TRUE;
hr = GetThreadPool()->CreateDataPortHandle( pDataPort );
if ( hr != DPN_OK )
{
DPFX(DPFPREP, 0, "Failed to create handle for data port!" );
DisplayDNError( 0, hr );
goto Failure;
}
hr = pDataPort->BindToNetwork( dwDeviceID, pDeviceContext );
if ( hr != DPN_OK )
{
DPFX(DPFPREP, 0, "Failed to bind data port to network!" );
DisplayDNError( 0, hr );
goto Failure;
}
fDataPortBoundToNetwork = TRUE;
//
// update the list, keep the reference added by 'CreateDataPort' as it
// will be cleaned when the data port is removed from the active list.
//
m_DataPortList[ dwDeviceID ] = pDataPort;
}
DNASSERT( pDataPort != NULL );
pDataPort->EndpointAddRef();
hr = pDataPort->BindEndpoint( pEndpoint, pEndpoint->GetType() );
if ( hr != DPN_OK )
{
pDataPort->EndpointDecRef();
DPFX(DPFPREP, 0, "Failed to bind endpoint!" );
DisplayDNError( 0, hr );
goto Failure;
}
Exit:
if ( fDataPortDataLocked != FALSE )
{
UnlockDataPortData();
fDataPortDataLocked = FALSE;
}
DPFX(DPFPREP, 9, "(0x%p) Returning [0x%lx]", this, hr);
return hr;
Failure:
if ( pDataPort != NULL )
{
if ( fDataPortBoundToNetwork != FALSE )
{
pDataPort->UnbindFromNetwork();
fDataPortBoundToNetwork = FALSE;
}
if ( fDataPortCreated != FALSE )
{
if ( pDataPort->GetHandle() != 0 )
{
GetThreadPool()->CloseDataPortHandle( pDataPort );
DNASSERT( pDataPort->GetHandle() == 0 );
}
pDataPort->DecRef();
fDataPortCreated = FALSE;
}
pDataPort = NULL;
}
goto Exit;
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::UnbindEndpoint - unbind an endpoint from a dataport
//
// Entry: Pointer to endpoint
// Endpoint type
//
// Exit: Nothing
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::UnbindEndpoint"
void CModemSPData::UnbindEndpoint( CModemEndpoint *const pEndpoint, const ENDPOINT_TYPE EndpointType )
{
CDataPort *pDataPort;
DWORD dwDeviceID;
BOOL fCleanUpDataPort;
DPFX(DPFPREP, 9, "(0x%p) Parameters: (0x%p, %u)", this, pEndpoint, EndpointType);
DNASSERT( pEndpoint != NULL );
//
// initialize
//
pDataPort = NULL;
fCleanUpDataPort = FALSE;
pDataPort = pEndpoint->GetDataPort();
dwDeviceID = pDataPort->GetDeviceID();
LockDataPortData();
pDataPort->UnbindEndpoint( pEndpoint, EndpointType );
if ( pDataPort->EndpointDecRef() == 0 )
{
DNASSERT( m_DataPortList[ dwDeviceID ] == pDataPort );
m_DataPortList[ dwDeviceID ] = NULL;
fCleanUpDataPort = TRUE;
}
UnlockDataPortData();
if ( fCleanUpDataPort != FALSE )
{
pDataPort->DecRef();
fCleanUpDataPort = FALSE;
}
DPFX(DPFPREP, 9, "(0x%p) Leave", this);
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::GetNewEndpoint - get a new endpoint
//
// Entry: Nothing
//
// Exit: Pointer to new endpoint
// NULL = out of memory
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::GetNewEndpoint"
CModemEndpoint *CModemSPData::GetNewEndpoint( void )
{
HRESULT hTempResult;
CModemEndpoint *pEndpoint;
DPNHANDLE hEndpoint;
ENDPOINT_POOL_CONTEXT PoolContext;
DPFX(DPFPREP, 9, "(0x%p) Enter", this);
//
// initialize
//
pEndpoint = NULL;
hEndpoint = 0;
memset( &PoolContext, 0x00, sizeof( PoolContext ) );
PoolContext.pSPData = this;
pEndpoint = CreateEndpoint( &PoolContext );
if ( pEndpoint == NULL )
{
DPFX(DPFPREP, 0, "Failed to create endpoint!" );
goto Failure;
}
hTempResult = m_HandleTable.Create( pEndpoint, &hEndpoint );
if ( hTempResult != DPN_OK )
{
DNASSERT( hEndpoint == 0 );
DPFX(DPFPREP, 0, "Failed to create endpoint handle!" );
DisplayErrorCode( 0, hTempResult );
goto Failure;
}
pEndpoint->SetHandle( hEndpoint );
pEndpoint->AddCommandRef();
pEndpoint->DecRef();
Exit:
DPFX(DPFPREP, 9, "(0x%p) Returning [0x%p]", this, pEndpoint);
return pEndpoint;
Failure:
if ( hEndpoint != 0 )
{
m_HandleTable.Destroy( hEndpoint, NULL );
hEndpoint = 0;
}
if ( pEndpoint != NULL )
{
pEndpoint->DecRef();
pEndpoint = NULL;
}
goto Exit;
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::EndpointFromHandle - get endpoint from handle
//
// Entry: Handle
//
// Exit: Pointer to endpoint
// NULL = invalid handle
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::EndpointFromHandle"
CModemEndpoint *CModemSPData::EndpointFromHandle( const DPNHANDLE hEndpoint )
{
CModemEndpoint *pEndpoint;
DPFX(DPFPREP, 9, "(0x%p) Parameters: (0x%p)", this, hEndpoint);
pEndpoint = NULL;
m_HandleTable.Lock();
if (SUCCEEDED(m_HandleTable.Find( hEndpoint, (PVOID*)&pEndpoint )))
{
pEndpoint->AddCommandRef();
}
m_HandleTable.Unlock();
DPFX(DPFPREP, 9, "(0x%p) Returning [0x%p]", this, pEndpoint);
return pEndpoint;
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::CloseEndpointHandle - close endpoint handle
//
// Entry: Poiner to endpoint
//
// Exit: Nothing
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::CloseEndpointHandle"
void CModemSPData::CloseEndpointHandle( CModemEndpoint *const pEndpoint )
{
DPNHANDLE Handle;
DNASSERT( pEndpoint != NULL );
Handle = pEndpoint->GetHandle();
DPFX(DPFPREP, 9, "(0x%p) Parameters: (0x%p {handle = 0x%p})",
this, pEndpoint, Handle);
if (SUCCEEDED(m_HandleTable.Destroy( Handle, NULL )))
{
pEndpoint->DecCommandRef();
}
DPFX(DPFPREP, 9, "(0x%p) Leave", this);
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::GetEndpointAndCloseHandle - get endpoint from handle and close the
// handle
//
// Entry: Handle
//
// Exit: Pointer to endpoint (it needs a call to 'DecCommandRef' when done)
// NULL = invalid handle
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::GetEndpointAndCloseHandle"
CModemEndpoint *CModemSPData::GetEndpointAndCloseHandle( const DPNHANDLE hEndpoint )
{
CModemEndpoint *pEndpoint;
DPFX(DPFPREP, 9, "(0x%p) Parameters: (0x%p)", this, hEndpoint);
//
// initialize
//
pEndpoint = NULL;
if (SUCCEEDED( m_HandleTable.Destroy( hEndpoint, (PVOID*)&pEndpoint )))
{
pEndpoint->AddRef();
}
DPFX(DPFPREP, 9, "(0x%p) Returning [0x%p]", this, pEndpoint);
return pEndpoint;
}
//**********************************************************************
//**********************************************************************
// ------------------------------
// CModemSPData::DestroyThisObject - destroy this object
//
// Entry: Nothing
//
// Exit: Nothing
// ------------------------------
#undef DPF_MODNAME
#define DPF_MODNAME "CModemSPData::DestroyThisObject"
void CModemSPData::DestroyThisObject( void )
{
Deinitialize();
delete this; // maybe a little too extreme......
}
//**********************************************************************
| 25.311576 | 138 | 0.540116 | [
"object"
] |
ff8a54d2a8de26d62a340d09a4053b188c9adde6 | 4,958 | cpp | C++ | toolkits/topic_modeling/deprecated/cvb0_lda_common.cpp | coreyp1/graphlab | 637be90021c5f83ab7833ca15c48e76039057969 | [
"ECL-2.0",
"Apache-2.0"
] | 8 | 2017-11-19T11:46:55.000Z | 2021-07-08T22:45:55.000Z | toolkits/topic_modeling/deprecated/cvb0_lda_common.cpp | coreyp1/graphlab | 637be90021c5f83ab7833ca15c48e76039057969 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | toolkits/topic_modeling/deprecated/cvb0_lda_common.cpp | coreyp1/graphlab | 637be90021c5f83ab7833ca15c48e76039057969 | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2015-12-15T12:12:23.000Z | 2019-10-16T16:48:40.000Z | /**
* Copyright (c) 2009 Carnegie Mellon University.
* 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.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#include <vector>
#include <algorithm>
#include <graphlab.hpp>
#include "cvb0_lda_common.hpp"
#include <graphlab/macros_def.hpp>
double ALPHA = 0.1;
double BETA = 0.1;
size_t NTOPICS = 50;
size_t NWORDS = 0;
size_t TOPK = 5;
size_t INTERVAL = 10;
factor_type GLOBAL_TOPIC_COUNT;
std::vector<std::string> DICTIONARY;
size_t MAX_COUNT = 100;
bool graph_loader(graph_type& graph, const std::string& fname,
const std::string& line) {
ASSERT_FALSE(line.empty());
const int BASE = 10;
char* next_char_ptr = NULL;
graph_type::vertex_id_type doc_id =
strtoul(line.c_str(), &next_char_ptr, BASE);
if(next_char_ptr == NULL) return false;
const graph_type::vertex_id_type word_id =
strtoul(next_char_ptr, &next_char_ptr, BASE);
if(next_char_ptr == NULL) return false;
size_t count =
strtoul(next_char_ptr, &next_char_ptr, BASE);
if(next_char_ptr == NULL) return false;
count = std::min(count, MAX_COUNT);
// since this is a bipartite graph I need a method to number the
// left and right vertices differently. To accomplish I make sure
// all vertices have non-zero ids and then negate the right vertex.
doc_id += 2;
ASSERT_GT(doc_id, 1);
doc_id = -doc_id;
ASSERT_NE(doc_id, word_id);
// Create an edge and add it to the graph
graph.add_edge(doc_id, word_id, edge_data(count));
return true; // successful load
}; // end of graph loader
/** populate the global dictionary */
bool load_dictionary(const std::string& fname) {
const bool gzip = boost::ends_with(fname, ".gz");
// test to see if the graph_dir is an hadoop path
if(boost::starts_with(fname, "hdfs://")) {
graphlab::hdfs hdfs;
graphlab::hdfs::fstream in_file(hdfs, fname);
boost::iostreams::filtering_stream<boost::iostreams::input> fin;
fin.set_auto_close(false);
if(gzip) fin.push(boost::iostreams::gzip_decompressor());
fin.push(in_file);
if(!fin.good()) {
logstream(LOG_ERROR) << "Error loading dictionary: "
<< fname << std::endl;
return false;
}
std::string term;
while(std::getline(fin,term).good()) DICTIONARY.push_back(term);
if (gzip) fin.pop();
fin.pop();
in_file.close();
} else {
std::cout << "opening: " << fname << std::endl;
std::ifstream in_file(fname.c_str(),
std::ios_base::in | std::ios_base::binary);
boost::iostreams::filtering_stream<boost::iostreams::input> fin;
if (gzip) fin.push(boost::iostreams::gzip_decompressor());
fin.push(in_file);
if(!fin.good()) {
logstream(LOG_ERROR) << "Error loading dictionary: "
<< fname << std::endl;
return false;
}
std::string term;
std::cout << "Loooping" << std::endl;
while(std::getline(fin, term).good()) DICTIONARY.push_back(term);
if (gzip) fin.pop();
fin.pop();
in_file.close();
} // end of else
std::cout << "Dictionary Size: " << DICTIONARY.size() << std::endl;
return true;
} // end of load dictionary
bool load_and_initialize_graph(graphlab::distributed_control& dc,
graph_type& graph,
const std::string& matrix_dir) {
dc.cout() << "Loading graph." << std::endl;
graphlab::timer timer; timer.start();
graph.load(matrix_dir, graph_loader);
dc.cout() << ": Loading graph. Finished in "
<< timer.current_time() << " seconds." << std::endl;
dc.cout() << "Finalizing graph." << std::endl;
timer.start();
graph.finalize();
dc.cout() << "Finalizing graph. Finished in "
<< timer.current_time() << " seconds." << std::endl;
dc.cout() << "Initializing Vertex Data" << std::endl;
timer.start();
graph.transform_vertices(initialize_vertex_data);
dc.cout() << "Finished initializing Vertex Data in "
<< timer.current_time() << " seconds." << std::endl;
dc.cout() << "Verivying dictionary size." << std::endl;
NWORDS = graph.map_reduce_vertices<size_t>(is_word);
dc.cout() << "Number of words: " << NWORDS;
//ASSERT_LT(NWORDS, DICTIONARY.size());
return true;
} // end of load and initialize graph
| 27.853933 | 70 | 0.640783 | [
"vector"
] |
ff8d9692d31e15f6ddc070329e9b401afbb838c7 | 8,145 | cpp | C++ | verilate/core-ver-src/aquila_core_tb.cpp | chao0502/aquila | 48517c49470c53d1015b31358d128865d5b7b662 | [
"BSD-3-Clause"
] | null | null | null | verilate/core-ver-src/aquila_core_tb.cpp | chao0502/aquila | 48517c49470c53d1015b31358d128865d5b7b662 | [
"BSD-3-Clause"
] | null | null | null | verilate/core-ver-src/aquila_core_tb.cpp | chao0502/aquila | 48517c49470c53d1015b31358d128865d5b7b662 | [
"BSD-3-Clause"
] | null | null | null |
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <map>
#include <cstdint>
#include "decode2.cpp"
#include "verilated_vcd_c.h"
#include "Vaquila_testharness.h"
#include "Vaquila_testharness__Syms.h"
#include "verilated.h"
#include "sim_mem.h"
#define TRACE
//#undef TRACE
#define FENCE_ENABLE
#undef FENCE_ENABLE
#define MAX_SIM_CYCLE 1000000
using namespace std;
static vluint64_t cpuTime = 0;
uint32_t tohost_addr = 0;
double sc_time_stamp() { return cpuTime; }
Vaquila_testharness* top;
VerilatedVcdC* Vcdfp;
void load_simple_asm();
static void usage(const char * program_name)
{
cout << "Usage: " << program_name << " [RISCV_TEST_ELF] [RVTEST(0/1),default 0]" <<endl;
}
int main(int argc, char **argv)
{
Verilated::commandArgs(argc,argv);
map<string,uint64_t> elf_symbols;
bool rv_test_enable = false;
if (argc < 2) {
usage(argv[0]);
cerr << "Please provide riscv test elf file" << endl;
return -1;
}
fstream log_file("cpu.log",fstream::out);
fstream log_file2("cpu2.log",fstream::out);
if (!log_file.is_open()) {
cerr << "Failed to open cpu.log file!!!" << endl;
return -1;
}
if (argc >=3 ) {
if (argv[2][0] == '1')
rv_test_enable = true;
cout << "set rv_test_enable to " << (rv_test_enable ? "\"true\"" : "\"false\"") << endl;
}
top = new Vaquila_testharness("top");
#ifdef TRACE
Verilated::traceEverOn(true);
Vcdfp = new VerilatedVcdC;
top->trace(Vcdfp, 99);
Vcdfp->open("aquila_core.vcd");
#endif
uint32_t entry_addr = 0x00000000;
elf_symbols = sim_mem_load_program(top->aquila_testharness->mock_ram, string(argv[1]), &entry_addr);
if (rv_test_enable) {
if (elf_symbols.count("tohost")){
tohost_addr = static_cast<uint32_t>(elf_symbols["tohost"]);
} else {
cerr << "no tohost symbols existed.!!!" << endl;
return -1;
}
}
top->rst_n = 0;
cout << "entry_addr = " << "0x" << setfill('0') << setw(8) << right << hex << entry_addr << endl;
top->main_memory_addr = entry_addr;
//load_simple_asm();
sim_mem_dump_memory(top->aquila_testharness->mock_ram, "dump.mem");
for (int i = 0 ; i < 5 ; i ++){
top->clk = 0;
top->eval ();
cpuTime += 5;
#ifdef TRACE
Vcdfp->dump(cpuTime);
#endif
top->clk = 1;
top->eval ();
cpuTime += 5;
#ifdef TRACE
Vcdfp->dump(cpuTime);
#endif
}
top->rst_n = 1;
uint32_t tohost_val;
int prev_stall = 1;
vluint64_t time[9][8];
string instruction[9];
unsigned int instr_addr[9];
long long int count = 0;
for (int i = 0 ; i < MAX_SIM_CYCLE ; i ++){
top->clk = 0;
top->eval ();
cpuTime += 5;
#ifdef TRACE
Vcdfp->dump(cpuTime);
#endif
//__PVT__aquila_core__DOT__RISCV_CORE0__DOT__JAL_BHT__DOT__we 看jump
//aquila_core__DOT__RISCV_CORE0__DOT____Vcellinp__Fetch__flush 決定 Fetch flush
//__PVT__aquila_core__DOT__RISCV_CORE0__DOT__exe_branch_taken
prev_stall = (int)top->aquila_testharness->aquila_core__DOT__RISCV_CORE0__DOT____Vcellinp__Fetch__stall;
if(prev_stall == 0){
int fet_flush = (int) top->aquila_testharness->aquila_core__DOT__RISCV_CORE0__DOT____Vcellinp__Fetch__flush;
//unsigned int instr = top->aquila_testharness->__PVT__aquila_core__DOT__RISCV_CORE0__DOT__fet_instr2dec;
unsigned int instr = top->aquila_testharness->aquila_core__DOT____Vtogcov__p_i_instr;
log_file << "#" << setfill('0') << setw(10) << right << cpuTime <<
":" << setfill('0') << setw(8) << right << hex << top->cur_instr_addr <<
"::" << (int)top->aquila_testharness->aquila_core__DOT__RISCV_CORE0__DOT____Vcellinp__Fetch__stall <<
"::" << setfill('0') << setw(8) << right <<instr << "::";
log_file << dec;
char *tem = int_to_str(instr);
tem[32] = 0;
/*for(int i = 0; i < 32; i++)
log_file << tem[i];*/
riscv_decode(tem, &log_file);
log_file << endl;
//shift
count++;
if(count > 8){
log_file2 << "O3PipeView:fetch:" << time[7][0] << ":0x" << setfill('0') << setw(8) << hex << instr_addr[7] << dec << ":0:" << count - 7 << ":" << instruction[7] << endl;;
log_file2 << "O3PipeView:decode:" << time[7][1] << endl;
log_file2 << "O3PipeView:rename:" << time[7][2] << endl;
log_file2 << "O3PipeView:dispatch:" << time[7][3] << endl;
log_file2 << "O3PipeView:issue:" << time[7][4] << endl;
log_file2 << "O3PipeView:complete:" << time[7][5] << endl;
log_file2 << "O3PipeView:retire:" << time[7][6] << ":store:" << time[7][7] << endl;
}
for(int k = 8; k > 0; k--)
for(int j = 0; j < 8; j++)
time[k][j] = time[k-1][j];
for(int k = 0; k < 8; k++)
time[k][k] = cpuTime;
for(int k = 8; k > 0; k--){
instr_addr[k] = instr_addr[k-1];
instruction[k] = instruction[k-1];
}
instr_addr[0] = top->cur_instr_addr;
instruction[0] = tem;
if(fet_flush){
instr_addr[0] = 0;
instruction[0] = int_to_str(19);
for(int k = 0; k < 2; k++){
for(int j = 0; j < 8; j++)
time[k][j] = 0;
}
}
//
}
//printf("%ld:%08x\n",cpuTime,top->aquila_testharness->__PVT__aquila_core__DOT__RISCV_CORE0__DOT__fet_instr2dec);
top->clk = 1;
top->eval ();
cpuTime += 5;
#ifdef TRACE
Vcdfp->dump(cpuTime);
#endif
if (rv_test_enable) {
#ifdef FENCE_ENABLE
tohost_val = sim_mem_tohost_monitor(top->aquila_testharness->mock_ram, tohost_addr);
#else
tohost_val = top->aquila_testharness->mock_uart_0->read_tohost();
#endif
if (tohost_val != 0){
if (tohost_val == 1)
cout << "pass testcase: " << argv[1] << endl;
else
cout << "testcase #" << tohost_val << " failed !!!!!\ntestcase:" << argv[1] << endl;
break;
}
}
}
#ifdef TRACE
Vcdfp->close();
delete Vcdfp;
#endif
delete top;
if (rv_test_enable && tohost_val != 1)
exit(-1);
else
exit(0);
}
void load_simple_asm()
{
//_start
top->aquila_testharness->mock_ram->writeWord(0x00000000,0x04c0006f);
// trap_vector
top->aquila_testharness->mock_ram->writeWord(0x00000004,0x34202f73);
top->aquila_testharness->mock_ram->writeWord(0x00000008,0x00800f93);
top->aquila_testharness->mock_ram->writeWord(0x0000000c,0x03ff0a63);
top->aquila_testharness->mock_ram->writeWord(0x00000010,0x00900f93);
top->aquila_testharness->mock_ram->writeWord(0x00000014,0x03ff0663);
top->aquila_testharness->mock_ram->writeWord(0x00000018,0x00b00f93);
top->aquila_testharness->mock_ram->writeWord(0x0000001c,0x03ff0263);
top->aquila_testharness->mock_ram->writeWord(0x00000020,0x00000f17);
top->aquila_testharness->mock_ram->writeWord(0x00000024,0xfe0f0f13);
top->aquila_testharness->mock_ram->writeWord(0x00000028,0x000f0463);
top->aquila_testharness->mock_ram->writeWord(0x0000002c,0x000f0067);
top->aquila_testharness->mock_ram->writeWord(0x00000030,0x34202f73);
top->aquila_testharness->mock_ram->writeWord(0x00000034,0x000f5463);
top->aquila_testharness->mock_ram->writeWord(0x00000038,0x0040006f);
// handle exception
top->aquila_testharness->mock_ram->writeWord(0x0000003c,0x5391e193);
top->aquila_testharness->mock_ram->writeWord(0x00000040,0x00001f17);
top->aquila_testharness->mock_ram->writeWord(0x00000044,0xfc3f2023);
top->aquila_testharness->mock_ram->writeWord(0x00000048,0xff9ff06f);
//reset vector
top->aquila_testharness->mock_ram->writeWord(0x0000004c,0xf1402573);
top->aquila_testharness->mock_ram->writeWord(0x00000050,0x00051063);
top->aquila_testharness->mock_ram->writeWord(0x00000054,0x00000297);
top->aquila_testharness->mock_ram->writeWord(0x00000058,0x01028293);
top->aquila_testharness->mock_ram->writeWord(0x0000005c,0x30529073);
top->aquila_testharness->mock_ram->writeWord(0x00000060,0x18005073);
top->aquila_testharness->mock_ram->writeWord(0x00000064,0x00000297);
top->aquila_testharness->mock_ram->writeWord(0x00000068,0x02028293);
top->aquila_testharness->mock_ram->writeWord(0x0000006c,0x30529073);
top->aquila_testharness->mock_ram->writeWord(0x00000070,0x800002b7);
}
| 32.710843 | 178 | 0.663352 | [
"vector"
] |
ff8e75a50aa35f82f2d8f7c16bd4e29148019f3f | 32,757 | cpp | C++ | vsports/SingleControlWindow.cpp | snumrl/VSports | c35bc82db31cd7252ab3d0f78c3f941bae5e799b | [
"Apache-2.0"
] | null | null | null | vsports/SingleControlWindow.cpp | snumrl/VSports | c35bc82db31cd7252ab3d0f78c3f941bae5e799b | [
"Apache-2.0"
] | null | null | null | vsports/SingleControlWindow.cpp | snumrl/VSports | c35bc82db31cd7252ab3d0f78c3f941bae5e799b | [
"Apache-2.0"
] | null | null | null | #include "SingleControlWindow.h"
#include "../render/GLfunctionsDART.h"
#include "../model/SkelMaker.h"
#include "../model/SkelHelper.h"
#include "../pyvs/EnvironmentPython.h"
#include <dart/dart.hpp>
#include <dart/utils/utils.hpp>
#include "../motion/BVHmanager.h"
#include <numeric>
// #include "./common/loadShader.h"
// #include <GL/glew.h>
#include <GL/glut.h>
// #include <GL/glew.h>
#include <GLFW/glfw3.h>
// Include GLM
#include <glm/glm.hpp>
#include "../extern/ICA/plugin/MotionGenerator.h"
#include "../extern/ICA/plugin/MotionGeneratorBatch.h"
#include "../extern/ICA/plugin/utils.h"
#include "../extern/ICA/Utils/PathManager.h"
#include "../extern/ICA/CharacterControl/MotionRepresentation.h"
#include "../utils/Utils.h"
using namespace glm;
#include <iostream>
#include <random>
using namespace dart::dynamics;
using namespace dart::simulation;
using namespace std;
namespace p = boost::python;
namespace np = boost::python::numpy;
// double floorDepth = -0.1;
void
SingleControlWindow::
initWindow(int _w, int _h, char* _name)
{
mWindows.push_back(this);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE | GLUT_ACCUM);
glutInitWindowPosition(100, 100);
glutInitWindowSize(_w, _h);
mWinIDs.push_back(glutCreateWindow(_name));
glutDisplayFunc(displayEvent);
glutReshapeFunc(reshapeEvent);
glutKeyboardFunc(keyboardEvent);
glutKeyboardUpFunc(keyboardUpEvent);
glutMouseFunc(mouseEvent);
glutMotionFunc(motionEvent);
glutTimerFunc(mDisplayTimeout, timerEvent, 0);
mScreenshotTemp.resize(4*_w*_h);
mScreenshotTemp2.resize(4*_w*_h);
}
SingleControlWindow::
SingleControlWindow()
:SimWindow(), mIsNNLoaded(false), mFrame(0), windowFrame(0)
{
initCustomView();
initGoalpost();
mm = p::import("__main__");
mns = mm.attr("__dict__");
sys_module = p::import("sys");
boost::python::str module_dir = "../pyvs";
sys_module.attr("path").attr("insert")(1, module_dir);
p::exec("import os",mns);
p::exec("import sys",mns);
p::exec("import math",mns);
p::exec("import sys",mns);
p::exec("import torch",mns);
p::exec("import torch.nn as nn",mns);
p::exec("import torch.optim as optim",mns);
p::exec("import torch.nn.functional as F",mns);
p::exec("import torchvision.transforms as T",mns);
p::exec("import numpy as np",mns);
p::exec("from Model import *",mns);
p::exec("from CAAE import CAAEDecoder, CAAEEncoder",mns);
controlOn = false;
this->vsHardcoded = false;
this->showCourtMesh = true;
this->targetLocal.resize(10);
this->targetLocal.setZero();
this->goal.resize(2);
this->goal.setZero();
this->mTrackCharacter = true;
for(int i=0;i<3;i++)
{
std::vector<Eigen::Isometry3d> prevHandTransform;
prevHandTransform.push_back(Eigen::Isometry3d::Identity());
prevHandTransform.push_back(Eigen::Isometry3d::Identity());
this->prevHandTransforms.push_back(prevHandTransform);
}
fingerAngle = 0;
fingerBallAngle =0;
for(int i=0;i<2;i++)
{
prevValues.push_back(0);
prevRewards.push_back(0);
curValues.push_back(0);
}
}
SingleControlWindow::
SingleControlWindow(const char* nn_path,
const char* control_nn_path)
:SingleControlWindow()
{
int numActionTypes = 5;
latentSize = 4;
mEnv = new Environment(30, 180, 1, "../data/motions/basketData/motion/s_004_1_1.bvh", nn_path);
reducedDim = false;
mMotionGeneratorBatch = new ICA::dart::MotionGeneratorBatch(nn_path, mEnv->initDartNameIdMapping(), 1);
mEnv->initialize(mMotionGeneratorBatch, 0);
recorder = new Recorder();
p::str str = ("num_state = "+std::to_string(mEnv->getNumState())).c_str();
p::exec(str,mns);
if(reducedDim)
str = "num_action = 4";
else
str = ("num_action = "+std::to_string(mEnv->getNumAction()-1)).c_str();
p::exec(str, mns);
nn_module_0 = new boost::python::object[mEnv->mNumChars];
nn_module_1 = new boost::python::object[mEnv->mNumChars];
nn_module_2 = new boost::python::object[mEnv->mNumChars];
p::object *load_0 = new p::object[mEnv->mNumChars];
p::object *load_1 = new p::object[mEnv->mNumChars];
p::object *load_2 = new p::object[mEnv->mNumChars];
p::object *load_rms_0 = new p::object[mEnv->mNumChars];
p::object *load_rms_1 = new p::object[mEnv->mNumChars];
for(int i=0;i<mEnv->mNumChars;i++)
{
nn_module_0[i] = p::eval(("ActorCriticNN(num_state, "+to_string(numActionTypes)+", 0.0, True, True).cuda()").data(), mns);
load_0[i] = nn_module_0[i].attr("load");
load_rms_0[i] = nn_module_0[i].attr("loadRMS");
}
for(int i=0;i<mEnv->mNumChars;i++)
{
nn_module_1[i] = p::eval(("ActorCriticNN(num_state + "+to_string(numActionTypes)+", "+to_string(latentSize)+").cuda()").data(), mns);
load_1[i] = nn_module_1[i].attr("load");
load_rms_1[i] = nn_module_1[i].attr("loadRMS");
}
load_0[0](string(control_nn_path) + "_0.pt");
load_1[0](string(control_nn_path) + "_1.pt");
std::string dir = control_nn_path;
std::string subdir = "";
while(dir.find("/")!=std::string::npos)
{
subdir += dir.substr(0,dir.find("/")+1);
dir = dir.substr(dir.find("/")+1);
}
load_rms_0[0]((subdir + "rms.ms").data());
load_rms_1[0]((subdir + "rms.ms").data());
std::cout<<"Loaded control nn : "<<control_nn_path<<std::endl;
// nn_module_decoders = new ;
// p::object load_decoder = new ;
// for(int i=0;i<numActionTypes;i++)
// {
nn_module_decoder = p::eval("CAAEDecoder().cuda()", mns);
// exit(0);
p::object load_decoder = nn_module_decoder.attr("load");
nn_module_encoder = p::eval("CAAEEncoder().cuda()", mns);
p::object load_encoder = nn_module_encoder.attr("load");
// }
// for(int i=0;i<numActionTypes;i++)
// {
load_decoder("../pyvs/caae_nn2/vae_action_decoder.pt");
load_encoder("../pyvs/caae_nn2/vae_action_encoder.pt");
// }
// load_decoders[0]("../pyvs/vae_nn_sep/vae_action_decoder_"+to_string(0)+".pt");
// load_decoders[1]("../pyvs/vae_nn_sep/vae_action_decoder_"+to_string(3)+".pt");
std::cout<<"Loaded CAAE decoder"<<std::endl;
mActions.resize(mEnv->mNumChars);
for(int i=0;i<mActions.size();i++)
{
mActions[i].resize(mEnv->getNumAction());
mActions[i].setZero();
}
mStates.resize(mEnv->mNumChars);
targetActionType = 0;
actionDelay = 0;
/// Read training X data
std::string sub_dir = "data";
std::string xDataPath= PathManager::getFilePath_data(nn_path, sub_dir, "xData.dat", 0 );
std::string xNormalPath= PathManager::getFilePath_data(nn_path, sub_dir, "xNormal.dat");
std::cout<<"xDataPath:"<<xDataPath<<std::endl;
this->xData.push_back(MotionRepresentation::readXData(xNormalPath, xDataPath, sub_dir));
}
void
SingleControlWindow::
initCustomView()
{
mCamera->eye = Eigen::Vector3d(5.0, 8.0, 18.0);
mCamera->lookAt = Eigen::Vector3d(5.0, 0.0, 0.0);
mCamera->up = Eigen::Vector3d(0.0, 1.0, 0.0);
}
void
SingleControlWindow::
initGoalpost()
{
redGoalpostSkel = SkelHelper::makeGoalpost(Eigen::Vector3d(-8.0, 0.25 + floorDepth, 0.0), "red");
blueGoalpostSkel = SkelHelper::makeGoalpost(Eigen::Vector3d(8.0, 0.25 + floorDepth, 0.0), "blue");
mWorld->addSkeleton(redGoalpostSkel);
mWorld->addSkeleton(blueGoalpostSkel);
}
void
SingleControlWindow::
keyboard(unsigned char key, int x, int y)
{
SkeletonPtr manualSkel = mEnv->getCharacter(0)->getSkeleton();
switch(key)
{
case 'c':
mTakeScreenShot = true;
// cout<<mCamera->eye.transpose()<<endl;
// cout<<mCamera->lookAt.transpose()<<endl;
// cout<<mCamera->up.transpose()<<endl;
break;
case 'w':
keyarr[int('w')] = PUSHED;
break;
case 's':
keyarr[int('s')] = PUSHED;
break;
case 'a':
keyarr[int('a')] = PUSHED;
break;
case 'd':
keyarr[int('d')] = PUSHED;
break;
case 'j':
mEnv->genObstacleNearGoalpost();
break;
case 'k':
mEnv->removeOldestObstacle();
break;
case 't':
{
mTrackCharacter = !mTrackCharacter;
break;
}
case 'r':
{
mEnv->slaveReset();
for(int i=0;i<2;i++)
{
prevValues[i] = 0.0;
prevRewards[i] = 0.0;
}
recorder->recordCurrentFrame(mEnv);
break;
}
case 'h':
mEnv->reset();
break;
case 'g':
mEnv->goBackEnvironment();
break;
case 'l':
controlOn = !controlOn;
break;
case 'i':
showCourtMesh = !showCourtMesh;
break;
case 'p':
int curAction;
for(int i=4;i<4+6;i++)
{
if(xData[0][mFrame+10][i] >= 0.5)
curAction = i-4;
}
while(curAction!=1 && curAction!=2 && curAction!=3)
{
mFrame++;
for(int i=4;i<4+6;i++)
{
if(xData[0][mFrame+10][i] >= 0.5)
{
curAction = i-4;
}
}
}
break;
case ']':
mFrame += 100;
if(mPlay)
step();
else
{
if(windowFrame >= recorder->getNumFrames())
{
step();
recorder->recordCurrentFrame(mEnv);
}
else
recorder->loadFrame(mEnv, windowFrame++);
}
break;
case '[':
mFrame -= 100;
if(mFrame <0)
mFrame = 0;
if(!mPlay)
recorder->loadFrame(mEnv, windowFrame--);
if(windowFrame < 0)
windowFrame = 0;
break;
case ' ':
if(!mPlay)
windowFrame = recorder->loadLastFrame(mEnv);
mPlay = !mPlay;
break;
default: SimWindow::keyboard(key, x, y);
}
}
void
SingleControlWindow::
keyboardUp(unsigned char key, int x, int y)
{
SkeletonPtr manualSkel = mEnv->getCharacter(0)->getSkeleton();
switch(key)
{
case 'w':
keyarr[int('w')] = NOTPUSHED;
break;
case 's':
keyarr[int('s')] = NOTPUSHED;
break;
case 'a':
keyarr[int('a')] = NOTPUSHED;
break;
case 'd':
keyarr[int('d')] = NOTPUSHED;
break;
case 'g':
keyarr[int('g')] = NOTPUSHED;
break;
case 'h':
keyarr[int('h')] = NOTPUSHED;
break;
case 'q':
keyarr[int('q')] = NOTPUSHED;
break;
case 'e':
keyarr[int('e')] = NOTPUSHED;
break;
}
}
void
SingleControlWindow::
timer(int value)
{
// time_check_start();
if(mPlay)
{
value = step();
recorder->recordCurrentFrame(mEnv);
}
glutPostRedisplay();
// time_check_end();
SimWindow::timer(value);
}
void
SingleControlWindow::
applyKeyBoardEvent()
{
double scale = 150.0;
Eigen::Vector2d frontVec, rightVec;
Eigen::Vector3d temp;
temp = (mCamera->lookAt - mCamera->eye);
frontVec[0] = temp[0];
frontVec[1] = temp[2];
frontVec.normalize();
rightVec[0] = -frontVec[1];
rightVec[1] = frontVec[0];
if(keyarr[int('w')] == PUSHED)
this->targetLocal.segment(0,2) += scale*frontVec;
if(keyarr[int('s')] == PUSHED)
this->targetLocal.segment(0,2) += -scale*frontVec;
if(keyarr[int('a')] == PUSHED)
this->targetLocal.segment(0,2) += -scale*rightVec;
if(keyarr[int('d')] == PUSHED)
this->targetLocal.segment(0,2) += scale*rightVec;
}
void
SingleControlWindow::
applyMouseEvent()
{
Eigen::Vector3d facing = mCamera->lookAt - mCamera->eye;
this->targetLocal[2] = facing[0];
this->targetLocal[3] = facing[2];
this->targetLocal.segment(2,2).normalize();
}
int
SingleControlWindow::
step()
{
std::cout<<"mEnv->curFrame : "<<mEnv->curFrame<<std::endl;
std::chrono::time_point<std::chrono::system_clock> m_time_check_s = std::chrono::system_clock::now();
if(mEnv->isFoulState())
{
sleep(1);
std::cout<<"Foul Reset"<<std::endl;
mEnv->foulReset();
}
if(mEnv->isTerminalState())
{
if(mTakeScreenShot)
{
for(int i=0;i<15;i++)
screenshot();
}
else
{
sleep(1);
}
mEnv->slaveReset();
}
this->targetLocal.setZero();
mEnv->getState(0);
mEnv->saveEnvironment();
bool useXData = false;
if(!useXData)
{
if(mEnv->resetCount<=0)
getActionFromNN(0);
}
else
{
mActions[0] = stdVecToEigen(xData[0][110+mEnv->curFrame]).segment(NUM_ACTION_TYPE,ACTION_SIZE-NUM_ACTION_TYPE-1);
int actionType = getActionTypeFromVec(stdVecToEigen(xData[0][110+mEnv->curFrame]).segment(0,NUM_ACTION_TYPE));
mEnv->setActionType(0, actionType);
Eigen::VectorXd actionTypeVector = stdVecToEigen(xData[0][110+mEnv->curFrame]).segment(0,NUM_ACTION_TYPE);
Eigen::VectorXd normalizedAction = mEnv->mNormalizer->normalizeAction(mActions[0]);
Eigen::VectorXd encodedAction = getEncodedAction(normalizedAction, actionTypeVector);
std::cout<<"Encoded aciton : "<<encodedAction.transpose()<<std::endl;
// std::cout<<"Action type : "<<actionType<<std::endl;
// std::cout<<"1mActions[0].transpose() : "<<mActions[0].transpose()<<std::endl;
}
std::vector<std::vector<double>> concatControlVector;
int resetDuration = mEnv->resetDuration;
for(int id=0;id<1;++id)
{
if(mEnv->resetCount>resetDuration/2)
{
if(mEnv->randomPointTrajectoryStart)
{
mMotionGeneratorBatch->setBatchStateAndMotionGeneratorState(id,
mEnv->slaveResetPositionTrajectory[resetDuration - mEnv->resetCount],
mEnv->slaveResetBallPositionTrajectory[resetDuration - mEnv->resetCount]);
}
else
{
mMotionGeneratorBatch->setBatchStateAndMotionGeneratorState(id, mEnv->slaveResetPositionVector, mEnv->slaveResetBallPosition);
}
}
}
for(int id=0;id<1;++id)
{
if(mEnv->resetCount<=0)
{
concatControlVector.push_back(eigenToStdVec(mEnv->getMGAction(0)));
// std::cout<<"2mActions[0].transpose() : "<<mActions[0].transpose()<<std::endl;
mEnv->setAction(0, mActions[0]);
}
else
{
if(mEnv->resetCount>resetDuration)
{
concatControlVector.push_back(eigenToStdVec(mEnv->slaveResetTargetVector));
Eigen::VectorXd actionTypeVector = mEnv->slaveResetTargetVector.segment(0,5);
Eigen::VectorXd actionDetailVector(16);
actionDetailVector = mEnv->slaveResetTargetVector.segment(5,16);
mEnv->setActionType(0,getActionTypeFromVec(actionTypeVector));
mEnv->setAction(0, actionDetailVector);
}
else
{
if(mEnv->randomPointTrajectoryStart)
{
concatControlVector.push_back(eigenToStdVec(mEnv->slaveResetTargetTrajectory[resetDuration-mEnv->resetCount]));
Eigen::VectorXd actionTypeVector = mEnv->slaveResetTargetTrajectory[resetDuration-mEnv->resetCount].segment(0,5);
Eigen::VectorXd actionDetailVector(16);
actionDetailVector = mEnv->slaveResetTargetTrajectory[resetDuration-mEnv->resetCount].segment(5,16);
// actionDetailVector.segment(4,5) = mEnv->slaveResetTargetTrajectory[resetDuration-mEnv->resetCount].segment(9,5);
mEnv->setActionType(0,getActionTypeFromVec(actionTypeVector));
mEnv->setAction(0, actionDetailVector);
}
else
{
concatControlVector.push_back(eigenToStdVec(mEnv->slaveResetTargetVector));
Eigen::VectorXd actionTypeVector = mEnv->slaveResetTargetVector.segment(0,5);
Eigen::VectorXd actionDetailVector(16);
actionDetailVector = mEnv->slaveResetTargetVector.segment(5,16);
// actionDetailVector.segment(4,5) = mEnv->slaveResetTargetVector.segment(9,5);
mEnv->setActionType(0,getActionTypeFromVec(actionTypeVector));
mEnv->setAction(0, actionDetailVector);
}
}
}
}
std::cout<<"action : "<<std::endl;
std::cout<<mEnv->mActions[0].segment(0,5).transpose()<<std::endl;
std::cout<<mEnv->mActions[0].segment(ROOT_OFFSET,2).transpose()<<std::endl;
std::cout<<mEnv->mActions[0].segment(HAND_OFFSET,6).transpose()<<std::endl;
std::cout<<mEnv->mActions[0].segment(BALLP_OFFSET,9).transpose()<<std::endl;
std::cout<<std::endl;
std::vector<std::tuple<Eigen::VectorXd, Eigen::VectorXd, bool>>
nextPoseAndContactsWithBatch = mMotionGeneratorBatch->generateNextPoseAndContactsWithBatch(concatControlVector);
for(int id=0;id<1;++id)
{
mEnv->stepAtOnce(nextPoseAndContactsWithBatch[id]);
}
for(int i=0;i<2;i++)
{
prevValues[i] = curValues[i];
prevRewards[i] = mEnv->curReward;
}
for(int i=0;i<2;i++)
{
Eigen::VectorXd state = mEnv->mStates[0];
p::object get_value_0;
if(i==0)
get_value_0 = nn_module_0[0].attr("get_value");
else
get_value_0 = nn_module_1[0].attr("get_value");
if(i == 1)
{
Eigen::VectorXd oneHotAction(NUM_ACTION_TYPE);
oneHotAction.setZero();
oneHotAction[mEnv->mCurActionTypes[0]] = 1;
state.resize(state.size()+NUM_ACTION_TYPE);
state.segment(0, mEnv->mStates[0].size()) = mEnv->mStates[0];
state.segment(mEnv->mStates[0].size(), NUM_ACTION_TYPE) =oneHotAction;
}
p::tuple shape = p::make_tuple(state.size());
np::dtype dtype = np::dtype::get_builtin<float>();
np::ndarray state_np = np::empty(shape, dtype);
float* dest = reinterpret_cast<float*>(state_np.get_data());
for(int j=0;j<state.size();j++)
{
dest[j] = state[j];
}
p::object temp = get_value_0(state_np);
np::ndarray value = np::from_object(temp);
float* srcs = reinterpret_cast<float*>(value.get_data());
curValues[i] = srcs[0];
}
mEnv->getRewards();
windowFrame++;
mFrame++;
std::chrono::duration<double> elapsed_seconds;
elapsed_seconds = std::chrono::system_clock::now()-m_time_check_s;
int calTime = std::min((int)(1000*elapsed_seconds.count()), 33);
return calTime;
}
void
SingleControlWindow::
display()
{
glClearColor(0.85, 0.85, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
initLights();
std::vector<Character3D*> chars = mEnv->getCharacters();
if(mTrackCharacter)
{
mCamera->lookAt = chars[0]->getSkeleton()->getCOM();
}
mCamera->apply();
GUI::drawCoordinate(Eigen::Vector3d(0.0, 0.015, 0.0), 1.0);
GUI::drawSkeleton(mEnv->floorSkel, Eigen::Vector3d(0.5, 1.0, 0.5), showCourtMesh, false);
Eigen::Vector3d ballColor = Eigen::Vector3d(0.9, 0.8, 0.4);
if(mEnv->curFrame < mEnv->throwingTime)
ballColor = Eigen::Vector3d(0.9, 0.6, 0.0);
GUI::drawSkeleton(mEnv->ballSkel, ballColor);
Eigen::Vector3d skelColor(1.0, 1.0, 1.0);
if(mEnv->resetCount >= 0)
skelColor = Eigen::Vector3d(0.5, 0.5, 0.5);
GUI::drawSkeleton(chars[0]->getSkeleton(), skelColor);
Eigen::Isometry3d rootIsometry = mEnv->getRootT(0);
glPushMatrix();
Eigen::Vector3d rootPosition = rootIsometry.translation();
glTranslated(rootPosition[0], rootPosition[1], rootPosition[2]);
Eigen::AngleAxisd rootAA(rootIsometry.linear());
glRotated(180/M_PI*rootAA.angle(), rootAA.axis()[0], rootAA.axis()[1], rootAA.axis()[2]);
GUI::drawCoordinate(Eigen::Vector3d::Zero(), 0.2);
glPopMatrix();
// glPushMatrix();
// glTranslated(mEnv->mTargetBallPosition[0], 0, mEnv->mTargetBallPosition[2]);
// glBegin(GL_LINES);
// glColor3f(0.0, 0.0, 0.0);
// glVertex3f(0,0,0);
// glVertex3f(0,mEnv->mTargetBallPosition[1],0);
// glEnd();
// glPopMatrix();
glLineWidth(1.0);
glPushMatrix();
glTranslated(mEnv->curBallPosition[0], 0, mEnv->curBallPosition[2]);
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(0,0,0);
glVertex3f(0,mEnv->curBallPosition[1],0);
glEnd();
GUI::drawSphere(0.05, Eigen::Vector3d::Zero(), Eigen::Vector3d(0.0, 0.0, 0.0));
glPopMatrix();
// Eigen::Vector3d targetBall2DPosition = mEnv->mTargetBallPosition;
// targetBall2DPosition[1] = 0;
for(int i=0;i<mEnv->mObstacles.size();i++)
{
glPushMatrix();
glTranslated(mEnv->mObstacles[i][0], 1.0, mEnv->mObstacles[i][2]);
GUI::drawCylinder(0.5, 2.0, Eigen::Vector3d(0.3, 0.3, 0.3));
// glColor3f(0.0,0.0,1.0);
// GUI::draw2dCircle(Eigen::Vector3d(0.0, 0.02, 0.0), Eigen::Vector3d::UnitX(), Eigen::Vector3d::UnitZ(),0.75, true);
glPopMatrix();
}
GUI::drawStringOnScreen(0.2, 0.6, to_string((int)mEnv->mCharacters[0]->blocked), true, Eigen::Vector3d::Zero());
GUI::drawStringOnScreen(0.8, 0.8, to_string(mEnv->getElapsedTime()), true, Eigen::Vector3d(0.5, 0.5, 0.5));
if(mEnv->curContact[0]==0 || mEnv->curContact[0]==2)
{
Eigen::Isometry3d handIsometry = mEnv->mCharacters[0]->getSkeleton()->getBodyNode("LeftFinger")->getWorldTransform();
glPushMatrix();
Eigen::Vector3d handPosition = handIsometry.translation();
glTranslated(handPosition[0], handPosition[1], handPosition[2]);
Eigen::AngleAxisd handAA(handIsometry.linear());
glRotated(180/M_PI*handAA.angle(), handAA.axis()[0], handAA.axis()[1], handAA.axis()[2]);
glColor3f(0.0, 0.0, 0.0);
GUI::drawCube(Eigen::Vector3d(0.072, 0.035, 0.055));
glPopMatrix();
}
if(mEnv->curContact[0]==1 || mEnv->curContact[0]==2)
{
Eigen::Isometry3d handIsometry = mEnv->mCharacters[0]->getSkeleton()->getBodyNode("RightFinger")->getWorldTransform();
glPushMatrix();
Eigen::Vector3d handPosition = handIsometry.translation();
glTranslated(handPosition[0], handPosition[1], handPosition[2]);
Eigen::AngleAxisd handAA(handIsometry.linear());
glRotated(180/M_PI*handAA.angle(), handAA.axis()[0], handAA.axis()[1], handAA.axis()[2]);
glColor3f(0.0, 0.0, 0.0);
GUI::drawCube(Eigen::Vector3d(0.072, 0.035, 0.055));
glPopMatrix();
}
if(mEnv->mLFootContacting[0])
{
Eigen::Isometry3d handIsometry = mEnv->mCharacters[0]->getSkeleton()->getBodyNode("LeftToe")->getWorldTransform();
glPushMatrix();
Eigen::Vector3d handPosition = handIsometry.translation();
glTranslated(handPosition[0], handPosition[1], handPosition[2]);
Eigen::AngleAxisd handAA(handIsometry.linear());
glRotated(180/M_PI*handAA.angle(), handAA.axis()[0], handAA.axis()[1], handAA.axis()[2]);
glTranslated(0.05, 0.0, 0.0);
glColor3f(0.3, 0.3, 0.3);
GUI::drawCube(Eigen::Vector3d(0.10, 0.06, 0.06));
glPopMatrix();
}
if(mEnv->mRFootContacting[0])
{
Eigen::Isometry3d handIsometry = mEnv->mCharacters[0]->getSkeleton()->getBodyNode("RightToe")->getWorldTransform();
glPushMatrix();
Eigen::Vector3d handPosition = handIsometry.translation();
glTranslated(handPosition[0], handPosition[1], handPosition[2]);
Eigen::AngleAxisd handAA(handIsometry.linear());
glRotated(180/M_PI*handAA.angle(), handAA.axis()[0], handAA.axis()[1], handAA.axis()[2]);
glTranslated(0.05, 0.0, 0.0);
glColor3f(0.3, 0.3, 0.3);
GUI::drawCube(Eigen::Vector3d(0.10, 0.06, 0.06));
glPopMatrix();
}
// GUI::drawVerticalLine(this->goal.segment(0,2), Eigen::Vector3d(1.0, 1.0, 1.0));
int numActions = 5;
std::string curAction;
bool useXData = false;
if(useXData)
{
for(int i=0;i<numActions;i++)
{
if(xData[0][mFrame][i] >= 0.5)
curAction = std::to_string(i);
}
curAction = curAction+" "+std::to_string(xData[0][mFrame][CRITICAL_OFFSET]/30.0);
}
else
{
int maxIndex = 0;
double maxValue = -100;
for(int i=0;i<numActions;i++)
{
if(mEnv->mActions[0][i]> maxValue)
{
maxValue= mEnv->mActions[0][i];
maxIndex = i;
}
}
curAction = std::to_string(maxIndex);
curAction = curAction+" "+std::to_string(mEnv->mActions[0][CRITICAL_OFFSET]/30.0);
}
Eigen::Vector3d ballTargetPosition =mEnv->mActions[0].segment(BALLTP_OFFSET,3)/100.0;
Eigen::Vector3d ballTargetVelocity = mEnv->mActions[0].segment(BALLTV_OFFSET,3)/100.0;
ballTargetPosition = rootIsometry * ballTargetPosition;
ballTargetVelocity = rootIsometry.linear() * ballTargetVelocity;
if(mEnv->mCurActionTypes[0] == 1 || mEnv->mCurActionTypes[0] == 3 )
{
GUI::drawArrow3D(ballTargetPosition, ballTargetVelocity, ballTargetVelocity.norm()/8.0, 0.05, Eigen::Vector3d(1.0, 0.0, 0.0), 0.08);
}
if(mEnv->mCurActionTypes[0] == 2)
{
GUI::drawSphere(0.15, ballTargetPosition, Eigen::Vector3d(1.0, 0.0, 0.0));
}
//Draw root to ball vector
Eigen::Vector3d rootToBall;
rootToBall[0] = 0.01*mEnv->mActions[0][2];
rootToBall[2] = 0.01*mEnv->mActions[0][3];
rootToBall[1] = 0.1;
// std::cout<<"root to ball : "<<rootToBall.transpose()<<std::endl;
glLineWidth(2.0);
GUI::drawLine(rootIsometry.translation(), rootIsometry*rootToBall, Eigen::Vector3d(1.0, 1.0, 1.0));
// GUI::drawLine(rootIsometry.translation(), rootIsometry*Eigen::Vector3d::UnitX(), Eigen::Vector3d(1.0, 0.0, 0.0));
GUI::drawStringOnScreen(0.2, 0.25, std::to_string(mEnv->mActions[0][CRITICAL_OFFSET]/30.0), true, Eigen::Vector3d(1,1,1));
std::string score = "Score : "+to_string(mEnv->mAccScore[0]);
GUI::drawBoxOnScreen(0.25, 0.75, Eigen::Vector2d(15.0, 4.0),Eigen::Vector3d(1.0, 1.0, 1.0), true);
GUI::drawStringOnScreen(0.2, 0.75, score, true, Eigen::Vector3d(0.0,0.0,0.0));
GUI::drawStringOnScreen(0.2, 0.55, std::to_string(mEnv->mCurBallPossessions[0]), true, Eigen::Vector3d(1,1,1));
showAvailableActions();
GUI::drawBoxOnScreen(0.2+0.6*((double)mEnv->mCurActionTypes[0] / (numActions)), 0.2, Eigen::Vector2d(6.0, 4.0),Eigen::Vector3d(1.0, 1.0, 1.0));
GUI::drawStringOnScreen(0.8, 0.55, std::to_string(curValues[0]), true, Eigen::Vector3d(1,1,1));
GUI::drawStringOnScreen(0.8, 0.45, std::to_string(curValues[1]), true, Eigen::Vector3d(1,1,1));
double tdError[2];
for(int i=0;i<2;i++)
{
tdError[i] = prevValues[i] - (prevRewards[i] + 0.999 * curValues[i]);
}
GUI::drawStringOnScreen(0.90, 0.55, std::to_string(tdError[0]), true, Eigen::Vector3d(1,1,1));
GUI::drawStringOnScreen(0.90, 0.45, std::to_string(tdError[1]), true, Eigen::Vector3d(1,1,1));
glutSwapBuffers();
if(mTakeScreenShot)
{
screenshot();
}
}
std::string
SingleControlWindow::
indexToStateString(int index)
{
switch(index)
{
case 0:
return "P_x";
case 1:
return "P_y";
case 2:
return "V_x";
case 3:
return "V_y";
case 4:
return "BP_x";
case 5:
return "BP_y";
case 6:
return "BV_x";
case 7:
return "BV_y";
case 8:
return "Kick";
case 9:
return "B_GP";
case 10:
return " ";
case 11:
return "B_GP";
case 12:
return " ";
case 13:
return "R_GP";
case 14:
return " ";
case 15:
return "R_GP";
case 16:
return " ";
default:
return "N";
}
return "N";
}
void
SingleControlWindow::
mouse(int button, int state, int x, int y)
{
mPrevX = x;
mPrevY = y;
if(button == GLUT_LEFT_BUTTON && glutGetModifiers()==GLUT_ACTIVE_SHIFT){
GLdouble modelview[16], projection[16];
GLint viewport[4];
double height = glutGet(GLUT_WINDOW_HEIGHT);
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);
double objx1, objy1, objz1;
double objx2, objy2, objz2;
int res1 = gluUnProject(x, height - y, 0, modelview, projection, viewport, &objx1, &objy1, &objz1);
int res2 = gluUnProject(x, height - y, 10, modelview, projection, viewport, &objx2, &objy2, &objz2);
this->goal[0] = objx1 + (objx2 - objx1)*(objy1)/(objy1-objy2);
this->goal[1] = objz1 + (objz2 - objz1)*(objy1)/(objy1-objy2);
}
else
{
SimWindow::mouse(button, state, x, y);
}
}
void
SingleControlWindow::
motion(int x, int y)
{
SimWindow::motion(x, y);
}
Eigen::VectorXd
SingleControlWindow::
toOneHotVector(Eigen::VectorXd action)
{
int maxIndex = 0;
double maxValue = -100;
for(int i=0;i<action.size();i++)
{
if(action[i]> maxValue)
{
maxValue= action[i];
maxIndex = i;
}
}
Eigen::VectorXd result(action.size());
result.setZero();
result[maxIndex] = 1.0;
return result;
}
Eigen::VectorXd
SingleControlWindow::
toOneHotVectorWithConstraint(int index, Eigen::VectorXd action)
{
int maxIndex = 0;
double maxValue = -100;
for(int i=0;i<action.size();i++)
{
if(action[i]> maxValue)
{
maxValue= action[i];
maxIndex = i;
}
}
maxIndex = mEnv->setActionType(index, maxIndex);
Eigen::VectorXd result(action.size());
result.setZero();
result[maxIndex] = 1.0;
return result;
}
int
SingleControlWindow::
getActionTypeFromVec(Eigen::VectorXd action)
{
int maxIndex = 0;
double maxValue = -100;
for(int i=0;i<action.size();i++)
{
if(action[i]> maxValue)
{
maxValue= action[i];
maxIndex = i;
}
}
return maxIndex;
}
void
SingleControlWindow::
getActionFromNN(int index)
{
p::object get_action_0;
Eigen::VectorXd state = mEnv->getState(index);
int numActions = 5;
Eigen::VectorXd mActionType(numActions);
mActionType.setZero();
get_action_0 = nn_module_0[index].attr("get_action");
p::tuple shape = p::make_tuple(state.size());
np::dtype dtype = np::dtype::get_builtin<float>();
np::ndarray state_np = np::empty(shape, dtype);
float* dest = reinterpret_cast<float*>(state_np.get_data());
for(int j=0;j<state.size();j++)
{
dest[j] = state[j];
}
p::object temp = get_action_0(state_np);
np::ndarray action_np = np::from_object(temp);
float* srcs = reinterpret_cast<float*>(action_np.get_data());
for(int j=0;j<numActions;j++)
{
mActionType[j] = srcs[j];
}
std::cout<<"**ActionType : "<<mActionType.transpose()<<std::endl;
std::cout<<"mEnv->curFrame : "<<mEnv->curFrame<<std::endl;
std::cout<<"mEnv->resetCount : "<<mEnv->resetCount<<std::endl;
if(mEnv->curFrame%mEnv->typeFreq == 0)
mActionType = toOneHotVectorWithConstraint(index, mActionType);
else
{
mActionType.setZero();
int prevActionType = mEnv->mCurActionTypes[index];
mActionType[prevActionType] = 1.0;
}
int actionType = getActionTypeFromVec(mActionType);
Eigen::VectorXd mAction(mEnv->getNumAction() - numActions);
Eigen::VectorXd state_1(state.size()+mActionType.rows());
state_1.segment(0,state.size()) = state;
state_1.segment(state.size(),mActionType.rows()) = mActionType;
p::object get_action_1;
get_action_1 = nn_module_1[index].attr("get_action_detail");
p::tuple shape_1 = p::make_tuple(state_1.size());
np::ndarray state_np_1 = np::empty(shape_1, dtype);
float* dest_1 = reinterpret_cast<float*>(state_np_1.get_data());
for(int j=0;j<state_1.size();j++)
{
dest_1[j] = state_1[j];
}
temp = get_action_1(state_np_1, actionType);
np::ndarray action_np_1 = np::from_object(temp);
float* srcs_1 = reinterpret_cast<float*>(action_np_1.get_data());
for(int j=0;j<latentSize;j++)
{
mAction[j] = srcs_1[j];
}
Eigen::VectorXd encodedAction(latentSize+numActions);
encodedAction.segment(0,numActions) = mActionType;
encodedAction.segment(numActions,latentSize) = mAction.segment(0,latentSize);
Eigen::VectorXd decodedAction(16);
std::cout<<"encoded action : "<<encodedAction.transpose()<<std::endl;
p::object decode;
decode = nn_module_decoder.attr("decodeAction");
p::tuple shape_d = p::make_tuple(encodedAction.size());
np::ndarray state_np_d = np::empty(shape_d, dtype);
float* dest_d = reinterpret_cast<float*>(state_np_d.get_data());
for(int j=0;j<encodedAction.size();j++)
{
dest_d[j] = encodedAction[j];
}
temp = decode(state_np_d);
np::ndarray action_np_d = np::from_object(temp);
float* src_d = reinterpret_cast<float*>(action_np_d.get_data());
for(int j=0;j<decodedAction.size();j++)
{
decodedAction[j] = src_d[j];
}
std::cout<<"Cur Action Type : "<<actionType<<std::endl;
// std::cout<<"normalized action in actionnn : "<<decodedAction.transpose()<<std::endl;
mActions[index] = mEnv->mNormalizer->denormalizeAction(decodedAction);
}
void
SingleControlWindow::
showAvailableActions()
{
std::vector<int> aa = mEnv->mCharacters[0]->availableActionTypes;
int numActionTypes = 5;
for(int i=0;i<numActionTypes;i++)
{
if(std::find(aa.begin(), aa.end(), i) != aa.end())
GUI::drawStringOnScreen_Big(-0.01 + 0.2+0.6*(((double) i)/numActionTypes), 0.2, mEnv->actionNameMap[i], Eigen::Vector3d::Ones());
else
GUI::drawStringOnScreen_Big(-0.01 + 0.2+0.6*(((double) i)/numActionTypes), 0.2, mEnv->actionNameMap[i], Eigen::Vector3d(0.5, 0.5, 0.5));
}
}
Eigen::VectorXd
SingleControlWindow::
getEncodedAction(Eigen::VectorXd decodedAction, Eigen::VectorXd actionType)
{
np::dtype dtype = np::dtype::get_builtin<float>();
Eigen::VectorXd decodedActionWithType(decodedAction.size()+actionType.size());
decodedActionWithType.segment(0, actionType.size()) = actionType;
decodedActionWithType.segment(actionType.size(), decodedAction.size()) = decodedAction;
p::object encode;
encode = nn_module_encoder.attr("encodeAction");
p::tuple shape_d = p::make_tuple(decodedActionWithType.size());
np::ndarray state_np_d = np::empty(shape_d, dtype);
float* dest_d = reinterpret_cast<float*>(state_np_d.get_data());
for(int j=0;j<decodedActionWithType.size();j++)
{
dest_d[j] = decodedActionWithType[j];
}
p::object temp = encode(state_np_d);
np::ndarray action_np_d = np::from_object(temp);
float* src_d = reinterpret_cast<float*>(action_np_d.get_data());
Eigen::VectorXd encodedAction(latentSize);
for(int j=0;j<encodedAction.size();j++)
{
encodedAction[j] = src_d[j];
}
return encodedAction;
} | 26.696822 | 144 | 0.661935 | [
"render",
"object",
"shape",
"vector",
"model"
] |
ff92a38f310bd8df119207535eb96c646fa19450 | 498 | cpp | C++ | Solutions/1-50/31/Solution.cpp | kitegi/Edmonton | 774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d | [
"Unlicense"
] | 2 | 2021-07-16T13:30:10.000Z | 2021-07-16T18:17:40.000Z | Solutions/1-50/31/Solution.cpp | kitegi/Edmonton | 774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d | [
"Unlicense"
] | null | null | null | Solutions/1-50/31/Solution.cpp | kitegi/Edmonton | 774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d | [
"Unlicense"
] | 1 | 2021-04-16T22:56:07.000Z | 2021-04-16T22:56:07.000Z | #include <iostream>
#include <vector>
using namespace std;
int changeCount(int goal, vector<int> &change) {
vector<int> subchange(goal + 1, 0);
subchange[0] = 1; // 1 way to make 0.
for(const auto &coin : change) {
for(int i = coin; i <= goal; i++) {
subchange[i] += subchange[i - coin];
}
}
return subchange[goal];
}
int main(int argc, char *argv[]) {
vector<int> change = {1, 2, 5, 10, 20, 50, 100, 200};
cout << changeCount(200, change) << endl;
return 0;
} | 23.714286 | 55 | 0.594378 | [
"vector"
] |
ff943d27195bc2b2a0d0618586705471e6e79595 | 1,678 | cpp | C++ | ACM87_vs2022/arithmetic_coding.cpp | Termibear/ArithmeticCoding_cpp | 9753db2c24ccbe94be90846f41020d59ba28ad38 | [
"MIT"
] | null | null | null | ACM87_vs2022/arithmetic_coding.cpp | Termibear/ArithmeticCoding_cpp | 9753db2c24ccbe94be90846f41020d59ba28ad38 | [
"MIT"
] | null | null | null | ACM87_vs2022/arithmetic_coding.cpp | Termibear/ArithmeticCoding_cpp | 9753db2c24ccbe94be90846f41020d59ba28ad38 | [
"MIT"
] | null | null | null | #include "arithmetic_coding.h"
// Initialize the model.
Arithmetic_Coding::Arithmetic_Coding()
{
int i;
// Set up tables that translate between symbol indexes and characters.
for (i = 0; i < NO_OF_CHARS; i++)
{
char_to_index[i] = i + 1;
index_to_char[i + 1] = static_cast<unsigned char>(i);
}
// Set up initial frequency counts to be 1 for all symbols.
for (i = 0; i <= NO_OF_SYMBOLS; i++)
{
freq[i] = 1;
cum_freq[i] = NO_OF_SYMBOLS - i;
}
// freq[0] must not be the same as freq[1].
freq[0] = 0;
}
// Update the model to account for a new symbol.
void Arithmetic_Coding::update_tables(int symbol)
{
int i;
// See if frequency counts are at their maximum.
if (cum_freq[0] == MAX_FREQUENCY)
{
int cum = 0;
// If so, halve all the counts (keeping them non-zero).
for (i = NO_OF_SYMBOLS; i >= 0; i--)
{
freq[i] = (freq[i] + 1) / 2;
cum_freq[i] = cum;
cum += freq[i];
}
}
// Find symbol's new index.
for (i = symbol; freq[i] == freq[i - 1]; i--);
// Update the translation tables if the symbol has moved.
if (i < symbol)
{
int ch_i = index_to_char[i], ch_symbol = index_to_char[symbol];
index_to_char[i] = static_cast<unsigned char>(ch_symbol);
index_to_char[symbol] = static_cast<unsigned char>(ch_i);
char_to_index[ch_i] = symbol;
char_to_index[ch_symbol] = i;
}
// Increment the frequency count for the symbol and update the cumulative frequencies.
freq[i]++;
while (i > 0)
{
i--;
cum_freq[i]++;
}
} | 26.634921 | 90 | 0.569726 | [
"model"
] |
ff946474c5a5b04521254790c7a691131e0a104e | 1,985 | hpp | C++ | src/lib/cli_cpp/render/ascii/A_Variable_List_Window.hpp | marvins/cli-cpp | 4f98a09d5cfeffe0d5c330cda3272ae207c511d1 | [
"MIT"
] | 4 | 2020-10-08T03:09:10.000Z | 2022-03-13T09:22:51.000Z | src/lib/cli_cpp/render/ascii/A_Variable_List_Window.hpp | marvins/cli-cpp | 4f98a09d5cfeffe0d5c330cda3272ae207c511d1 | [
"MIT"
] | 4 | 2015-05-30T17:40:46.000Z | 2015-07-01T01:10:16.000Z | src/lib/cli_cpp/render/ascii/A_Variable_List_Window.hpp | marvins/cli-cpp | 4f98a09d5cfeffe0d5c330cda3272ae207c511d1 | [
"MIT"
] | 2 | 2015-06-02T20:07:39.000Z | 2020-12-16T09:25:38.000Z | /**
* @file A_Variable_List_Window.hpp
* @author Marvin Smith
* @date 7/20/2015
*/
#ifndef __CLI_CPP_RENDER_ASCII_A_VARIABLE_LIST_WINDOW_HPP__
#define __CLI_CPP_RENDER_ASCII_A_VARIABLE_LIST_WINDOW_HPP__
// CLI Libraries
#include "An_ASCII_Render_Window_Base.hpp"
#include "../../cmd/A_Command_Parser.hpp"
#include "../../utility/An_ASCII_Print_Table.hpp"
// C++ Standard Libraries
#include <memory>
#include <string>
#include <vector>
namespace CLI{
namespace RENDER{
/**
* @class A_Variable_List_Window
*/
class A_Variable_List_Window : public An_ASCII_Render_Window_Base
{
public:
/// Pointer Type
typedef std::shared_ptr<A_Variable_List_Window> ptr_t;
/**
* @brief Constructor
*
* @param[in] render_driver Rendering driver containing the window size.
* @param[in] command_parser Command-Parser containing the variable list.
*/
A_Variable_List_Window( A_Render_Driver_Context_ASCII::ptr_t render_driver,
const CMD::A_Command_Parser::ptr_t command_parser );
/**
* @brief Get the Window Title
*
* @return Window-Title.
*/
inline virtual std::string Get_Window_Title()const{
return "CLI Variable List Window";
}
/**
* @brief Update the Buffer Data
*/
virtual void Update_Buffer_Data();
private:
/**
* @brief Initialize the Variable List Table.
*/
void Update_Variable_List_Table();
/// Class Name
std::string m_class_name;
/// Command Parser
CMD::A_Command_Parser::ptr_t m_command_parser;
/// Render Print Managers
UTILS::An_ASCII_Print_Table::ptr_t m_variable_print_table;
}; // End of A_Variable_List_Window Class
} // End of RENDER Namespace
} // End of CLI Namespace
#endif
| 22.556818 | 89 | 0.61864 | [
"render",
"vector"
] |
ff948caa18243450a1dd135f24955682c5a030f8 | 530 | cpp | C++ | tests/hackerrank/aho_corasick.two_two.test.cpp | Zeldacrafter/CompProg | 5367583f45b6fe30c4c84f3ae81accf14f8f7fd3 | [
"Unlicense"
] | 4 | 2020-02-06T15:44:57.000Z | 2020-12-21T03:51:21.000Z | tests/hackerrank/aho_corasick.two_two.test.cpp | Zeldacrafter/CompProg | 5367583f45b6fe30c4c84f3ae81accf14f8f7fd3 | [
"Unlicense"
] | null | null | null | tests/hackerrank/aho_corasick.two_two.test.cpp | Zeldacrafter/CompProg | 5367583f45b6fe30c4c84f3ae81accf14f8f7fd3 | [
"Unlicense"
] | null | null | null | #define PROBLEM "https://www.hackerrank.com/challenges/two-two/problem"
#include "../../code/strings/AHC.cc"
#include "../../code/utils/bigint.cc"
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
vector<pair<string, int>> strs;
bigint x = 1;
F0R(i, 801) {
strs.eb(to_string(x), 1);
x *= 2;
}
AHC<int, 10, char, '0'> ahc(0, strs);
int t;
cin >> t;
while(t--) {
string s;
cin >> s;
cout << ahc.query(s);
if(t) cout << endl;
}
}
| 18.275862 | 71 | 0.507547 | [
"vector"
] |
9111b946650b9f83c6ade5dfbfa70e53e61e1f2f | 2,685 | cpp | C++ | VoiceBridge/VoiceBridge/kaldi-win/src/bin/est-lda.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 18 | 2018-02-15T03:14:32.000Z | 2021-07-06T08:21:13.000Z | VoiceBridge/VoiceBridge/kaldi-win/src/bin/est-lda.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 3 | 2020-10-25T16:35:55.000Z | 2020-10-26T04:59:46.000Z | VoiceBridge/VoiceBridge/kaldi-win/src/bin/est-lda.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 7 | 2018-09-16T20:40:17.000Z | 2021-07-06T08:21:14.000Z | /*
Copyright 2017-present Zoltan Somogyi (AI-TOOLKIT), All Rights Reserved
You may use this file only if you agree to the software license:
AI-TOOLKIT Open Source Software License - Version 2.1 - February 22, 2018:
https://ai-toolkit.blogspot.com/p/ai-toolkit-open-source-software-license.html.
Also included with the source code distribution in AI-TOOLKIT-LICENSE.txt.
Based on:
*/
// Copyright 2009-2011 Microsoft Corporation
// See ../../COPYING for clarification regarding multiple authors
// 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
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "transform/lda-estimate.h"
#include "kaldi-win/src/kaldi_src.h"
/*
EstLda : Estimate LDA transform using stats obtained with acc-lda.
*/
int EstLda(int argc, char *argv[], fs::ofstream & file_log) {
using namespace kaldi;
typedef kaldi::int32 int32;
try {
const char *usage =
"Estimate LDA transform using stats obtained with acc-lda.\n"
"Usage: est-lda [options] <lda-matrix-out> <lda-acc-1> <lda-acc-2> ...\n";
bool binary = true;
std::string full_matrix_wxfilename;
LdaEstimateOptions opts;
ParseOptions po(usage);
po.Register("binary", &binary, "Write matrix in binary mode.");
po.Register("write-full-matrix", &full_matrix_wxfilename,
"Write full LDA matrix to this location.");
opts.Register(&po);
po.Read(argc, argv);
if (po.NumArgs() < 2) {
//po.PrintUsage();
//exit(1);
KALDI_ERR << "Wrong arguments.";
return -1;
}
LdaEstimate lda;
std::string lda_mat_wxfilename = po.GetArg(1);
for (int32 i = 2; i <= po.NumArgs(); i++) {
bool binary_in, add = true;
Input ki(po.GetArg(i), &binary_in);
lda.Read(ki.Stream(), binary_in, add);
}
Matrix<BaseFloat> lda_mat;
Matrix<BaseFloat> full_lda_mat;
lda.Estimate(opts, &lda_mat, &full_lda_mat);
WriteKaldiObject(lda_mat, lda_mat_wxfilename, binary);
if (full_matrix_wxfilename != "") {
Output ko(full_matrix_wxfilename, binary);
full_lda_mat.Write(ko.Stream(), binary);
}
return 0;
}
catch (const std::exception &e) {
KALDI_ERR << e.what();
return -1;
}
}
| 32.349398 | 80 | 0.713222 | [
"transform"
] |
9112788cdfa08b6c25331a2f7c3d461aac9ca740 | 159,205 | cpp | C++ | build/linux-build/Sources/src/zpp_nape/callbacks/ZPP_InteractionListener.cpp | HedgehogFog/TimeOfDeath | b78abacf940e1a88c8b987d99764ebb6876c5dc6 | [
"MIT"
] | null | null | null | build/linux-build/Sources/src/zpp_nape/callbacks/ZPP_InteractionListener.cpp | HedgehogFog/TimeOfDeath | b78abacf940e1a88c8b987d99764ebb6876c5dc6 | [
"MIT"
] | null | null | null | build/linux-build/Sources/src/zpp_nape/callbacks/ZPP_InteractionListener.cpp | HedgehogFog/TimeOfDeath | b78abacf940e1a88c8b987d99764ebb6876c5dc6 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.0.0-preview.5
#include <hxcpp.h>
#ifndef INCLUDED_nape_callbacks_Callback
#include <hxinc/nape/callbacks/Callback.h>
#endif
#ifndef INCLUDED_nape_callbacks_InteractionCallback
#include <hxinc/nape/callbacks/InteractionCallback.h>
#endif
#ifndef INCLUDED_nape_callbacks_InteractionListener
#include <hxinc/nape/callbacks/InteractionListener.h>
#endif
#ifndef INCLUDED_nape_callbacks_Listener
#include <hxinc/nape/callbacks/Listener.h>
#endif
#ifndef INCLUDED_nape_callbacks_OptionType
#include <hxinc/nape/callbacks/OptionType.h>
#endif
#ifndef INCLUDED_nape_callbacks_PreCallback
#include <hxinc/nape/callbacks/PreCallback.h>
#endif
#ifndef INCLUDED_nape_callbacks_PreFlag
#include <hxinc/nape/callbacks/PreFlag.h>
#endif
#ifndef INCLUDED_nape_callbacks_PreListener
#include <hxinc/nape/callbacks/PreListener.h>
#endif
#ifndef INCLUDED_zpp_nape_callbacks_ZPP_CbSet
#include <hxinc/zpp_nape/callbacks/ZPP_CbSet.h>
#endif
#ifndef INCLUDED_zpp_nape_callbacks_ZPP_CbSetPair
#include <hxinc/zpp_nape/callbacks/ZPP_CbSetPair.h>
#endif
#ifndef INCLUDED_zpp_nape_callbacks_ZPP_CbType
#include <hxinc/zpp_nape/callbacks/ZPP_CbType.h>
#endif
#ifndef INCLUDED_zpp_nape_callbacks_ZPP_InteractionListener
#include <hxinc/zpp_nape/callbacks/ZPP_InteractionListener.h>
#endif
#ifndef INCLUDED_zpp_nape_callbacks_ZPP_Listener
#include <hxinc/zpp_nape/callbacks/ZPP_Listener.h>
#endif
#ifndef INCLUDED_zpp_nape_callbacks_ZPP_OptionType
#include <hxinc/zpp_nape/callbacks/ZPP_OptionType.h>
#endif
#ifndef INCLUDED_zpp_nape_phys_ZPP_Interactor
#include <hxinc/zpp_nape/phys/ZPP_Interactor.h>
#endif
#ifndef INCLUDED_zpp_nape_space_ZPP_Space
#include <hxinc/zpp_nape/space/ZPP_Space.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZNPList_ZPP_CbSet
#include <hxinc/zpp_nape/util/ZNPList_ZPP_CbSet.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZNPList_ZPP_CbType
#include <hxinc/zpp_nape/util/ZNPList_ZPP_CbType.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZNPList_ZPP_InteractionListener
#include <hxinc/zpp_nape/util/ZNPList_ZPP_InteractionListener.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZNPList_ZPP_Interactor
#include <hxinc/zpp_nape/util/ZNPList_ZPP_Interactor.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZNPNode_ZPP_CbSet
#include <hxinc/zpp_nape/util/ZNPNode_ZPP_CbSet.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZNPNode_ZPP_CbType
#include <hxinc/zpp_nape/util/ZNPNode_ZPP_CbType.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZNPNode_ZPP_InteractionListener
#include <hxinc/zpp_nape/util/ZNPNode_ZPP_InteractionListener.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZNPNode_ZPP_Interactor
#include <hxinc/zpp_nape/util/ZNPNode_ZPP_Interactor.h>
#endif
#ifndef INCLUDED_zpp_nape_util_ZPP_Set_ZPP_CbSetPair
#include <hxinc/zpp_nape/util/ZPP_Set_ZPP_CbSetPair.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_02b7feea1016c80f_338_new,"zpp_nape.callbacks.ZPP_InteractionListener","new",0xf921f592,"zpp_nape.callbacks.ZPP_InteractionListener.new","zpp_nape/callbacks/Listener.hx",338,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_351_setInteractionType,"zpp_nape.callbacks.ZPP_InteractionListener","setInteractionType",0x9488fd38,"zpp_nape.callbacks.ZPP_InteractionListener.setInteractionType","zpp_nape/callbacks/Listener.hx",351,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_371_wake,"zpp_nape.callbacks.ZPP_InteractionListener","wake",0x0a84c2b2,"zpp_nape.callbacks.ZPP_InteractionListener.wake","zpp_nape/callbacks/Listener.hx",371,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_390_CbSetset,"zpp_nape.callbacks.ZPP_InteractionListener","CbSetset",0x162afeed,"zpp_nape.callbacks.ZPP_InteractionListener.CbSetset","zpp_nape/callbacks/Listener.hx",390,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_469_CbTypeset,"zpp_nape.callbacks.ZPP_InteractionListener","CbTypeset",0x215c02db,"zpp_nape.callbacks.ZPP_InteractionListener.CbTypeset","zpp_nape/callbacks/Listener.hx",469,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_543_with_uniquesets,"zpp_nape.callbacks.ZPP_InteractionListener","with_uniquesets",0x3718532d,"zpp_nape.callbacks.ZPP_InteractionListener.with_uniquesets","zpp_nape/callbacks/Listener.hx",543,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_613_with_union,"zpp_nape.callbacks.ZPP_InteractionListener","with_union",0xad4f2fe4,"zpp_nape.callbacks.ZPP_InteractionListener.with_union","zpp_nape/callbacks/Listener.hx",613,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_642_addedToSpace,"zpp_nape.callbacks.ZPP_InteractionListener","addedToSpace",0xd900e8f9,"zpp_nape.callbacks.ZPP_InteractionListener.addedToSpace","zpp_nape/callbacks/Listener.hx",642,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_661_removedFromSpace,"zpp_nape.callbacks.ZPP_InteractionListener","removedFromSpace",0xe92a46ca,"zpp_nape.callbacks.ZPP_InteractionListener.removedFromSpace","zpp_nape/callbacks/Listener.hx",661,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_680_invalidate_precedence,"zpp_nape.callbacks.ZPP_InteractionListener","invalidate_precedence",0x04144f40,"zpp_nape.callbacks.ZPP_InteractionListener.invalidate_precedence","zpp_nape/callbacks/Listener.hx",680,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_700_cbtype_change1,"zpp_nape.callbacks.ZPP_InteractionListener","cbtype_change1",0xd11af429,"zpp_nape.callbacks.ZPP_InteractionListener.cbtype_change1","zpp_nape/callbacks/Listener.hx",700,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_703_cbtype_change2,"zpp_nape.callbacks.ZPP_InteractionListener","cbtype_change2",0xd11af42a,"zpp_nape.callbacks.ZPP_InteractionListener.cbtype_change2","zpp_nape/callbacks/Listener.hx",703,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_705_cbtype_change,"zpp_nape.callbacks.ZPP_InteractionListener","cbtype_change",0x0461b308,"zpp_nape.callbacks.ZPP_InteractionListener.cbtype_change","zpp_nape/callbacks/Listener.hx",705,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_712_swapEvent,"zpp_nape.callbacks.ZPP_InteractionListener","swapEvent",0x2c1aef39,"zpp_nape.callbacks.ZPP_InteractionListener.swapEvent","zpp_nape/callbacks/Listener.hx",712,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_385_boot,"zpp_nape.callbacks.ZPP_InteractionListener","boot",0xfcadeac0,"zpp_nape.callbacks.ZPP_InteractionListener.boot","zpp_nape/callbacks/Listener.hx",385,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_386_boot,"zpp_nape.callbacks.ZPP_InteractionListener","boot",0xfcadeac0,"zpp_nape.callbacks.ZPP_InteractionListener.boot","zpp_nape/callbacks/Listener.hx",386,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_387_boot,"zpp_nape.callbacks.ZPP_InteractionListener","boot",0xfcadeac0,"zpp_nape.callbacks.ZPP_InteractionListener.boot","zpp_nape/callbacks/Listener.hx",387,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_464_boot,"zpp_nape.callbacks.ZPP_InteractionListener","boot",0xfcadeac0,"zpp_nape.callbacks.ZPP_InteractionListener.boot","zpp_nape/callbacks/Listener.hx",464,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_465_boot,"zpp_nape.callbacks.ZPP_InteractionListener","boot",0xfcadeac0,"zpp_nape.callbacks.ZPP_InteractionListener.boot","zpp_nape/callbacks/Listener.hx",465,0x87b155a7)
HX_LOCAL_STACK_FRAME(_hx_pos_02b7feea1016c80f_466_boot,"zpp_nape.callbacks.ZPP_InteractionListener","boot",0xfcadeac0,"zpp_nape.callbacks.ZPP_InteractionListener.boot","zpp_nape/callbacks/Listener.hx",466,0x87b155a7)
namespace zpp_nape{
namespace callbacks{
void ZPP_InteractionListener_obj::__construct( ::nape::callbacks::OptionType options1, ::nape::callbacks::OptionType options2,int event,int type){
HX_STACKFRAME(&_hx_pos_02b7feea1016c80f_338_new)
HXLINE( 347) this->handlerp = null();
HXLINE( 346) this->pure = false;
HXLINE( 345) this->allowSleepingCallbacks = false;
HXLINE( 344) this->handleri = null();
HXLINE( 343) this->options2 = null();
HXLINE( 342) this->options1 = null();
HXLINE( 341) this->itype = 0;
HXLINE( 340) this->outer_znp = null();
HXLINE( 339) this->outer_zni = null();
HXLINE( 354) super::__construct();
HXLINE( 355) this->type = type;
HXLINE( 356) this->interaction = hx::ObjectPtr<OBJ_>(this);
HXLINE( 357) this->event = event;
HXLINE( 358) this->options1 = options1->zpp_inner;
HXLINE( 359) this->options2 = options2->zpp_inner;
HXLINE( 360) this->allowSleepingCallbacks = false;
}
Dynamic ZPP_InteractionListener_obj::__CreateEmpty() { return new ZPP_InteractionListener_obj; }
void *ZPP_InteractionListener_obj::_hx_vtable = 0;
Dynamic ZPP_InteractionListener_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< ZPP_InteractionListener_obj > _hx_result = new ZPP_InteractionListener_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3]);
return _hx_result;
}
bool ZPP_InteractionListener_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x67e66328) {
return inClassId==(int)0x00000001 || inClassId==(int)0x67e66328;
} else {
return inClassId==(int)0x763b4a3a;
}
}
void ZPP_InteractionListener_obj::setInteractionType(int itype){
HX_STACKFRAME(&_hx_pos_02b7feea1016c80f_351_setInteractionType)
HXDLIN( 351) this->itype = itype;
}
HX_DEFINE_DYNAMIC_FUNC1(ZPP_InteractionListener_obj,setInteractionType,(void))
void ZPP_InteractionListener_obj::wake(){
HX_STACKFRAME(&_hx_pos_02b7feea1016c80f_371_wake)
HXDLIN( 371) ::zpp_nape::util::ZNPNode_ZPP_CbType ite1 = this->options1->includes->head;
HXDLIN( 371) ::zpp_nape::util::ZNPNode_ZPP_CbType ite2 = this->options2->includes->head;
HXDLIN( 371) while(true){
HXDLIN( 371) bool _hx_tmp;
HXDLIN( 371) if (hx::IsNotNull( ite1 )) {
HXDLIN( 371) _hx_tmp = hx::IsNotNull( ite2 );
}
else {
HXDLIN( 371) _hx_tmp = false;
}
HXDLIN( 371) if (!(_hx_tmp)) {
HXDLIN( 371) goto _hx_goto_2;
}
HXDLIN( 371) ::zpp_nape::callbacks::ZPP_CbType cb1 = ite1->elt;
HXDLIN( 371) ::zpp_nape::callbacks::ZPP_CbType cb2 = ite2->elt;
HXDLIN( 371) if (hx::IsEq( cb1,cb2 )) {
HXLINE( 372) {
HXLINE( 373) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite = cb1->interactors->head;
HXLINE( 374) while(hx::IsNotNull( cx_ite )){
HXLINE( 375) ::zpp_nape::phys::ZPP_Interactor i = cx_ite->elt;
HXLINE( 377) i->wake();
HXLINE( 379) cx_ite = cx_ite->next;
}
}
HXLINE( 371) ite1 = ite1->next;
HXDLIN( 371) ite2 = ite2->next;
}
else {
HXDLIN( 371) if ((cb1->id < cb2->id)) {
HXLINE( 372) {
HXLINE( 373) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite1 = cb1->interactors->head;
HXLINE( 374) while(hx::IsNotNull( cx_ite1 )){
HXLINE( 375) ::zpp_nape::phys::ZPP_Interactor i1 = cx_ite1->elt;
HXLINE( 377) i1->wake();
HXLINE( 379) cx_ite1 = cx_ite1->next;
}
}
HXLINE( 371) ite1 = ite1->next;
}
else {
HXLINE( 372) {
HXLINE( 373) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite2 = cb2->interactors->head;
HXLINE( 374) while(hx::IsNotNull( cx_ite2 )){
HXLINE( 375) ::zpp_nape::phys::ZPP_Interactor i2 = cx_ite2->elt;
HXLINE( 377) i2->wake();
HXLINE( 379) cx_ite2 = cx_ite2->next;
}
}
HXLINE( 371) ite2 = ite2->next;
}
}
}
_hx_goto_2:;
HXDLIN( 371) while(hx::IsNotNull( ite1 )){
HXLINE( 372) {
HXLINE( 373) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite3 = ite1->elt->interactors->head;
HXLINE( 374) while(hx::IsNotNull( cx_ite3 )){
HXLINE( 375) ::zpp_nape::phys::ZPP_Interactor i3 = cx_ite3->elt;
HXLINE( 377) i3->wake();
HXLINE( 379) cx_ite3 = cx_ite3->next;
}
}
HXLINE( 371) ite1 = ite1->next;
}
HXDLIN( 371) while(hx::IsNotNull( ite2 )){
HXLINE( 372) {
HXLINE( 373) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite4 = ite2->elt->interactors->head;
HXLINE( 374) while(hx::IsNotNull( cx_ite4 )){
HXLINE( 375) ::zpp_nape::phys::ZPP_Interactor i4 = cx_ite4->elt;
HXLINE( 377) i4->wake();
HXLINE( 379) cx_ite4 = cx_ite4->next;
}
}
HXLINE( 371) ite2 = ite2->next;
}
}
HX_DEFINE_DYNAMIC_FUNC0(ZPP_InteractionListener_obj,wake,(void))
void ZPP_InteractionListener_obj::CbSetset( ::zpp_nape::util::ZNPList_ZPP_CbSet A, ::zpp_nape::util::ZNPList_ZPP_CbSet B, ::Dynamic lambda){
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_390_CbSetset)
HXLINE( 391) ::zpp_nape::util::ZNPList_ZPP_CbSet U = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::UCbSet;
HXLINE( 392) ::zpp_nape::util::ZNPList_ZPP_CbSet V = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::VCbSet;
HXLINE( 393) ::zpp_nape::util::ZNPList_ZPP_CbSet W = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::WCbSet;
HXLINE( 394) ::zpp_nape::util::ZNPNode_ZPP_CbSet aite = A->head;
HXLINE( 395) ::zpp_nape::util::ZNPNode_ZPP_CbSet bite = B->head;
HXLINE( 396) while(true){
HXLINE( 396) bool _hx_tmp;
HXDLIN( 396) if (hx::IsNotNull( aite )) {
HXLINE( 396) _hx_tmp = hx::IsNotNull( bite );
}
else {
HXLINE( 396) _hx_tmp = false;
}
HXDLIN( 396) if (!(_hx_tmp)) {
HXLINE( 396) goto _hx_goto_11;
}
HXLINE( 397) ::zpp_nape::callbacks::ZPP_CbSet a = aite->elt;
HXLINE( 398) ::zpp_nape::callbacks::ZPP_CbSet b = bite->elt;
HXLINE( 399) if (hx::IsEq( a,b )) {
HXLINE( 400) {
HXLINE( 400) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret;
HXDLIN( 400) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 400) ret = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 400) ret = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 400) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret->next;
HXDLIN( 400) ret->next = null();
}
HXDLIN( 400) ret->elt = a;
HXDLIN( 400) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp = ret;
HXDLIN( 400) temp->next = W->head;
HXDLIN( 400) W->head = temp;
HXDLIN( 400) W->modified = true;
HXDLIN( 400) W->length++;
}
HXLINE( 401) aite = aite->next;
HXLINE( 402) bite = bite->next;
}
else {
HXLINE( 404) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(a,b)) {
HXLINE( 405) {
HXLINE( 405) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret1;
HXDLIN( 405) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 405) ret1 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 405) ret1 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 405) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret1->next;
HXDLIN( 405) ret1->next = null();
}
HXDLIN( 405) ret1->elt = a;
HXDLIN( 405) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp1 = ret1;
HXDLIN( 405) temp1->next = U->head;
HXDLIN( 405) U->head = temp1;
HXDLIN( 405) U->modified = true;
HXDLIN( 405) U->length++;
}
HXLINE( 406) aite = aite->next;
}
else {
HXLINE( 409) {
HXLINE( 409) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret2;
HXDLIN( 409) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 409) ret2 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 409) ret2 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 409) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret2->next;
HXDLIN( 409) ret2->next = null();
}
HXDLIN( 409) ret2->elt = b;
HXDLIN( 409) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp2 = ret2;
HXDLIN( 409) temp2->next = V->head;
HXDLIN( 409) V->head = temp2;
HXDLIN( 409) V->modified = true;
HXDLIN( 409) V->length++;
}
HXLINE( 410) bite = bite->next;
}
}
}
_hx_goto_11:;
HXLINE( 413) while(hx::IsNotNull( aite )){
HXLINE( 414) {
HXLINE( 414) ::zpp_nape::callbacks::ZPP_CbSet o = aite->elt;
HXDLIN( 414) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret3;
HXDLIN( 414) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 414) ret3 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 414) ret3 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 414) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret3->next;
HXDLIN( 414) ret3->next = null();
}
HXDLIN( 414) ret3->elt = o;
HXDLIN( 414) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp3 = ret3;
HXDLIN( 414) temp3->next = U->head;
HXDLIN( 414) U->head = temp3;
HXDLIN( 414) U->modified = true;
HXDLIN( 414) U->length++;
}
HXLINE( 415) aite = aite->next;
}
HXLINE( 417) while(hx::IsNotNull( bite )){
HXLINE( 418) {
HXLINE( 418) ::zpp_nape::callbacks::ZPP_CbSet o1 = bite->elt;
HXDLIN( 418) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret4;
HXDLIN( 418) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 418) ret4 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 418) ret4 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 418) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret4->next;
HXDLIN( 418) ret4->next = null();
}
HXDLIN( 418) ret4->elt = o1;
HXDLIN( 418) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp4 = ret4;
HXDLIN( 418) temp4->next = V->head;
HXDLIN( 418) V->head = temp4;
HXDLIN( 418) V->modified = true;
HXDLIN( 418) V->length++;
}
HXLINE( 419) bite = bite->next;
}
HXLINE( 422) while(hx::IsNotNull( U->head )){
HXLINE( 423) ::zpp_nape::callbacks::ZPP_CbSet x = U->pop_unsafe();
HXLINE( 424) {
HXLINE( 425) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite = B->head;
HXLINE( 426) while(hx::IsNotNull( cx_ite )){
HXLINE( 427) ::zpp_nape::callbacks::ZPP_CbSet y = cx_ite->elt;
HXLINE( 428) lambda(x,y);
HXLINE( 429) cx_ite = cx_ite->next;
}
}
}
HXLINE( 435) while(hx::IsNotNull( V->head )){
HXLINE( 436) ::zpp_nape::callbacks::ZPP_CbSet x1 = V->pop_unsafe();
HXLINE( 437) {
HXLINE( 438) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite1 = W->head;
HXLINE( 439) while(hx::IsNotNull( cx_ite1 )){
HXLINE( 440) ::zpp_nape::callbacks::ZPP_CbSet y1 = cx_ite1->elt;
HXLINE( 441) lambda(x1,y1);
HXLINE( 442) cx_ite1 = cx_ite1->next;
}
}
}
HXLINE( 448) while(hx::IsNotNull( W->head )){
HXLINE( 449) ::zpp_nape::callbacks::ZPP_CbSet x2 = W->pop_unsafe();
HXLINE( 450) {
HXLINE( 451) lambda(x2,x2);
HXLINE( 452) {
HXLINE( 453) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite2 = W->head;
HXLINE( 454) while(hx::IsNotNull( cx_ite2 )){
HXLINE( 455) ::zpp_nape::callbacks::ZPP_CbSet y2 = cx_ite2->elt;
HXLINE( 456) lambda(x2,y2);
HXLINE( 457) cx_ite2 = cx_ite2->next;
}
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC3(ZPP_InteractionListener_obj,CbSetset,(void))
void ZPP_InteractionListener_obj::CbTypeset( ::zpp_nape::util::ZNPList_ZPP_CbType A, ::zpp_nape::util::ZNPList_ZPP_CbType B, ::Dynamic lambda){
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_469_CbTypeset)
HXLINE( 470) ::zpp_nape::util::ZNPList_ZPP_CbType U = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::UCbType;
HXLINE( 471) ::zpp_nape::util::ZNPList_ZPP_CbType V = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::VCbType;
HXLINE( 472) ::zpp_nape::util::ZNPList_ZPP_CbType W = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::WCbType;
HXLINE( 473) ::zpp_nape::util::ZNPNode_ZPP_CbType aite = A->head;
HXLINE( 474) ::zpp_nape::util::ZNPNode_ZPP_CbType bite = B->head;
HXLINE( 475) while(true){
HXLINE( 475) bool _hx_tmp;
HXDLIN( 475) if (hx::IsNotNull( aite )) {
HXLINE( 475) _hx_tmp = hx::IsNotNull( bite );
}
else {
HXLINE( 475) _hx_tmp = false;
}
HXDLIN( 475) if (!(_hx_tmp)) {
HXLINE( 475) goto _hx_goto_21;
}
HXLINE( 476) ::zpp_nape::callbacks::ZPP_CbType a = aite->elt;
HXLINE( 477) ::zpp_nape::callbacks::ZPP_CbType b = bite->elt;
HXLINE( 478) if (hx::IsEq( a,b )) {
HXLINE( 479) {
HXLINE( 479) ::zpp_nape::util::ZNPNode_ZPP_CbType ret;
HXDLIN( 479) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 479) ret = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 479) ret = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 479) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret->next;
HXDLIN( 479) ret->next = null();
}
HXDLIN( 479) ret->elt = a;
HXDLIN( 479) ::zpp_nape::util::ZNPNode_ZPP_CbType temp = ret;
HXDLIN( 479) temp->next = W->head;
HXDLIN( 479) W->head = temp;
HXDLIN( 479) W->modified = true;
HXDLIN( 479) W->length++;
}
HXLINE( 480) aite = aite->next;
HXLINE( 481) bite = bite->next;
}
else {
HXLINE( 483) if ((a->id < b->id)) {
HXLINE( 484) {
HXLINE( 484) ::zpp_nape::util::ZNPNode_ZPP_CbType ret1;
HXDLIN( 484) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 484) ret1 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 484) ret1 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 484) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret1->next;
HXDLIN( 484) ret1->next = null();
}
HXDLIN( 484) ret1->elt = a;
HXDLIN( 484) ::zpp_nape::util::ZNPNode_ZPP_CbType temp1 = ret1;
HXDLIN( 484) temp1->next = U->head;
HXDLIN( 484) U->head = temp1;
HXDLIN( 484) U->modified = true;
HXDLIN( 484) U->length++;
}
HXLINE( 485) aite = aite->next;
}
else {
HXLINE( 488) {
HXLINE( 488) ::zpp_nape::util::ZNPNode_ZPP_CbType ret2;
HXDLIN( 488) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 488) ret2 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 488) ret2 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 488) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret2->next;
HXDLIN( 488) ret2->next = null();
}
HXDLIN( 488) ret2->elt = b;
HXDLIN( 488) ::zpp_nape::util::ZNPNode_ZPP_CbType temp2 = ret2;
HXDLIN( 488) temp2->next = V->head;
HXDLIN( 488) V->head = temp2;
HXDLIN( 488) V->modified = true;
HXDLIN( 488) V->length++;
}
HXLINE( 489) bite = bite->next;
}
}
}
_hx_goto_21:;
HXLINE( 492) while(hx::IsNotNull( aite )){
HXLINE( 493) {
HXLINE( 493) ::zpp_nape::callbacks::ZPP_CbType o = aite->elt;
HXDLIN( 493) ::zpp_nape::util::ZNPNode_ZPP_CbType ret3;
HXDLIN( 493) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 493) ret3 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 493) ret3 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 493) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret3->next;
HXDLIN( 493) ret3->next = null();
}
HXDLIN( 493) ret3->elt = o;
HXDLIN( 493) ::zpp_nape::util::ZNPNode_ZPP_CbType temp3 = ret3;
HXDLIN( 493) temp3->next = U->head;
HXDLIN( 493) U->head = temp3;
HXDLIN( 493) U->modified = true;
HXDLIN( 493) U->length++;
}
HXLINE( 494) aite = aite->next;
}
HXLINE( 496) while(hx::IsNotNull( bite )){
HXLINE( 497) {
HXLINE( 497) ::zpp_nape::callbacks::ZPP_CbType o1 = bite->elt;
HXDLIN( 497) ::zpp_nape::util::ZNPNode_ZPP_CbType ret4;
HXDLIN( 497) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 497) ret4 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 497) ret4 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 497) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret4->next;
HXDLIN( 497) ret4->next = null();
}
HXDLIN( 497) ret4->elt = o1;
HXDLIN( 497) ::zpp_nape::util::ZNPNode_ZPP_CbType temp4 = ret4;
HXDLIN( 497) temp4->next = V->head;
HXDLIN( 497) V->head = temp4;
HXDLIN( 497) V->modified = true;
HXDLIN( 497) V->length++;
}
HXLINE( 498) bite = bite->next;
}
HXLINE( 501) while(hx::IsNotNull( U->head )){
HXLINE( 502) ::zpp_nape::callbacks::ZPP_CbType x = U->pop_unsafe();
HXLINE( 503) {
HXLINE( 504) ::zpp_nape::util::ZNPNode_ZPP_CbType cx_ite = B->head;
HXLINE( 505) while(hx::IsNotNull( cx_ite )){
HXLINE( 506) ::zpp_nape::callbacks::ZPP_CbType y = cx_ite->elt;
HXLINE( 507) lambda(x,y);
HXLINE( 508) cx_ite = cx_ite->next;
}
}
}
HXLINE( 514) while(hx::IsNotNull( V->head )){
HXLINE( 515) ::zpp_nape::callbacks::ZPP_CbType x1 = V->pop_unsafe();
HXLINE( 516) {
HXLINE( 517) ::zpp_nape::util::ZNPNode_ZPP_CbType cx_ite1 = W->head;
HXLINE( 518) while(hx::IsNotNull( cx_ite1 )){
HXLINE( 519) ::zpp_nape::callbacks::ZPP_CbType y1 = cx_ite1->elt;
HXLINE( 520) lambda(x1,y1);
HXLINE( 521) cx_ite1 = cx_ite1->next;
}
}
}
HXLINE( 527) while(hx::IsNotNull( W->head )){
HXLINE( 528) ::zpp_nape::callbacks::ZPP_CbType x2 = W->pop_unsafe();
HXLINE( 529) {
HXLINE( 530) lambda(x2,x2);
HXLINE( 531) {
HXLINE( 532) ::zpp_nape::util::ZNPNode_ZPP_CbType cx_ite2 = W->head;
HXLINE( 533) while(hx::IsNotNull( cx_ite2 )){
HXLINE( 534) ::zpp_nape::callbacks::ZPP_CbType y2 = cx_ite2->elt;
HXLINE( 535) lambda(x2,y2);
HXLINE( 536) cx_ite2 = cx_ite2->next;
}
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC3(ZPP_InteractionListener_obj,CbTypeset,(void))
void ZPP_InteractionListener_obj::with_uniquesets(bool fresh){
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_543_with_uniquesets)
HXDLIN( 543) ::zpp_nape::callbacks::ZPP_InteractionListener _gthis = hx::ObjectPtr<OBJ_>(this);
HXLINE( 544) ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair set;
HXLINE( 546) if (hx::IsNull( ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 547) set = ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 553) set = ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair_obj::zpp_pool;
HXLINE( 554) ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair_obj::zpp_pool = set->next;
HXLINE( 555) set->next = null();
}
HXLINE( 562) set->lt = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::setlt_dyn();
HXLINE( 563) {
HXLINE( 563) ::zpp_nape::util::ZNPList_ZPP_CbType B = this->options2->includes;
HXDLIN( 563) ::zpp_nape::util::ZNPList_ZPP_CbType U = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::UCbType;
HXDLIN( 563) ::zpp_nape::util::ZNPList_ZPP_CbType V = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::VCbType;
HXDLIN( 563) ::zpp_nape::util::ZNPList_ZPP_CbType W = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::WCbType;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType aite = this->options1->includes->head;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType bite = B->head;
HXDLIN( 563) while(true){
HXLINE( 563) bool _hx_tmp;
HXDLIN( 563) if (hx::IsNotNull( aite )) {
HXLINE( 563) _hx_tmp = hx::IsNotNull( bite );
}
else {
HXLINE( 563) _hx_tmp = false;
}
HXDLIN( 563) if (!(_hx_tmp)) {
HXLINE( 563) goto _hx_goto_31;
}
HXDLIN( 563) ::zpp_nape::callbacks::ZPP_CbType a = aite->elt;
HXDLIN( 563) ::zpp_nape::callbacks::ZPP_CbType b = bite->elt;
HXDLIN( 563) if (hx::IsEq( a,b )) {
HXLINE( 563) {
HXLINE( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType ret;
HXDLIN( 563) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 563) ret = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 563) ret = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret->next;
HXDLIN( 563) ret->next = null();
}
HXDLIN( 563) ret->elt = a;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType temp = ret;
HXDLIN( 563) temp->next = W->head;
HXDLIN( 563) W->head = temp;
HXDLIN( 563) W->modified = true;
HXDLIN( 563) W->length++;
}
HXDLIN( 563) aite = aite->next;
HXDLIN( 563) bite = bite->next;
}
else {
HXLINE( 563) if ((a->id < b->id)) {
HXLINE( 563) {
HXLINE( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType ret1;
HXDLIN( 563) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 563) ret1 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 563) ret1 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret1->next;
HXDLIN( 563) ret1->next = null();
}
HXDLIN( 563) ret1->elt = a;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType temp1 = ret1;
HXDLIN( 563) temp1->next = U->head;
HXDLIN( 563) U->head = temp1;
HXDLIN( 563) U->modified = true;
HXDLIN( 563) U->length++;
}
HXDLIN( 563) aite = aite->next;
}
else {
HXLINE( 563) {
HXLINE( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType ret2;
HXDLIN( 563) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 563) ret2 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 563) ret2 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret2->next;
HXDLIN( 563) ret2->next = null();
}
HXDLIN( 563) ret2->elt = b;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType temp2 = ret2;
HXDLIN( 563) temp2->next = V->head;
HXDLIN( 563) V->head = temp2;
HXDLIN( 563) V->modified = true;
HXDLIN( 563) V->length++;
}
HXDLIN( 563) bite = bite->next;
}
}
}
_hx_goto_31:;
HXDLIN( 563) while(hx::IsNotNull( aite )){
HXLINE( 563) {
HXLINE( 563) ::zpp_nape::callbacks::ZPP_CbType o = aite->elt;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType ret3;
HXDLIN( 563) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 563) ret3 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 563) ret3 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret3->next;
HXDLIN( 563) ret3->next = null();
}
HXDLIN( 563) ret3->elt = o;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType temp3 = ret3;
HXDLIN( 563) temp3->next = U->head;
HXDLIN( 563) U->head = temp3;
HXDLIN( 563) U->modified = true;
HXDLIN( 563) U->length++;
}
HXDLIN( 563) aite = aite->next;
}
HXDLIN( 563) while(hx::IsNotNull( bite )){
HXLINE( 563) {
HXLINE( 563) ::zpp_nape::callbacks::ZPP_CbType o1 = bite->elt;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType ret4;
HXDLIN( 563) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 563) ret4 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 563) ret4 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret4->next;
HXDLIN( 563) ret4->next = null();
}
HXDLIN( 563) ret4->elt = o1;
HXDLIN( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType temp4 = ret4;
HXDLIN( 563) temp4->next = V->head;
HXDLIN( 563) V->head = temp4;
HXDLIN( 563) V->modified = true;
HXDLIN( 563) V->length++;
}
HXDLIN( 563) bite = bite->next;
}
HXDLIN( 563) while(hx::IsNotNull( U->head )){
HXLINE( 563) ::zpp_nape::callbacks::ZPP_CbType x = U->pop_unsafe();
HXDLIN( 563) {
HXLINE( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType cx_ite = B->head;
HXDLIN( 563) while(hx::IsNotNull( cx_ite )){
HXLINE( 563) ::zpp_nape::callbacks::ZPP_CbType y = cx_ite->elt;
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet B1 = y->cbsets;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet U1 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::UCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet V1 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::VCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet W1 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::WCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet aite1 = x->cbsets->head;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet bite1 = B1->head;
HXDLIN( 564) while(true){
HXLINE( 564) bool _hx_tmp1;
HXDLIN( 564) if (hx::IsNotNull( aite1 )) {
HXLINE( 564) _hx_tmp1 = hx::IsNotNull( bite1 );
}
else {
HXLINE( 564) _hx_tmp1 = false;
}
HXDLIN( 564) if (!(_hx_tmp1)) {
HXLINE( 564) goto _hx_goto_36;
}
HXDLIN( 564) ::zpp_nape::callbacks::ZPP_CbSet a1 = aite1->elt;
HXDLIN( 564) ::zpp_nape::callbacks::ZPP_CbSet b1 = bite1->elt;
HXDLIN( 564) if (hx::IsEq( a1,b1 )) {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret5;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret5 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret5 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret5->next;
HXDLIN( 564) ret5->next = null();
}
HXDLIN( 564) ret5->elt = a1;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp5 = ret5;
HXDLIN( 564) temp5->next = W1->head;
HXDLIN( 564) W1->head = temp5;
HXDLIN( 564) W1->modified = true;
HXDLIN( 564) W1->length++;
}
HXDLIN( 564) aite1 = aite1->next;
HXDLIN( 564) bite1 = bite1->next;
}
else {
HXLINE( 564) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(a1,b1)) {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret6;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret6 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret6 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret6->next;
HXDLIN( 564) ret6->next = null();
}
HXDLIN( 564) ret6->elt = a1;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp6 = ret6;
HXDLIN( 564) temp6->next = U1->head;
HXDLIN( 564) U1->head = temp6;
HXDLIN( 564) U1->modified = true;
HXDLIN( 564) U1->length++;
}
HXDLIN( 564) aite1 = aite1->next;
}
else {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret7;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret7 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret7 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret7->next;
HXDLIN( 564) ret7->next = null();
}
HXDLIN( 564) ret7->elt = b1;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp7 = ret7;
HXDLIN( 564) temp7->next = V1->head;
HXDLIN( 564) V1->head = temp7;
HXDLIN( 564) V1->modified = true;
HXDLIN( 564) V1->length++;
}
HXDLIN( 564) bite1 = bite1->next;
}
}
}
_hx_goto_36:;
HXDLIN( 564) while(hx::IsNotNull( aite1 )){
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet o2 = aite1->elt;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret8;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret8 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret8 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret8->next;
HXDLIN( 564) ret8->next = null();
}
HXDLIN( 564) ret8->elt = o2;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp8 = ret8;
HXDLIN( 564) temp8->next = U1->head;
HXDLIN( 564) U1->head = temp8;
HXDLIN( 564) U1->modified = true;
HXDLIN( 564) U1->length++;
}
HXDLIN( 564) aite1 = aite1->next;
}
HXDLIN( 564) while(hx::IsNotNull( bite1 )){
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet o3 = bite1->elt;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret9;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret9 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret9 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret9->next;
HXDLIN( 564) ret9->next = null();
}
HXDLIN( 564) ret9->elt = o3;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp9 = ret9;
HXDLIN( 564) temp9->next = V1->head;
HXDLIN( 564) V1->head = temp9;
HXDLIN( 564) V1->modified = true;
HXDLIN( 564) V1->length++;
}
HXDLIN( 564) bite1 = bite1->next;
}
HXDLIN( 564) while(hx::IsNotNull( U1->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x1 = U1->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite1 = B1->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite1 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y1 = cx_ite1->elt;
HXDLIN( 564) {
HXLINE( 565) x1->validate();
HXLINE( 566) y1->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x1,y1,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret10;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret10 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret10 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret10->next;
HXDLIN( 568) ret10->next = null();
}
HXDLIN( 568) ret10->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x1,y1)) {
HXLINE( 568) ret10->a = x1;
HXDLIN( 568) ret10->b = y1;
}
else {
HXLINE( 568) ret10->a = y1;
HXDLIN( 568) ret10->b = x1;
}
HXDLIN( 568) set->try_insert(ret10);
}
}
HXLINE( 564) cx_ite1 = cx_ite1->next;
}
}
}
HXDLIN( 564) while(hx::IsNotNull( V1->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x2 = V1->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite2 = W1->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite2 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y2 = cx_ite2->elt;
HXDLIN( 564) {
HXLINE( 565) x2->validate();
HXLINE( 566) y2->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x2,y2,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret11;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret11 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret11 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret11->next;
HXDLIN( 568) ret11->next = null();
}
HXDLIN( 568) ret11->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x2,y2)) {
HXLINE( 568) ret11->a = x2;
HXDLIN( 568) ret11->b = y2;
}
else {
HXLINE( 568) ret11->a = y2;
HXDLIN( 568) ret11->b = x2;
}
HXDLIN( 568) set->try_insert(ret11);
}
}
HXLINE( 564) cx_ite2 = cx_ite2->next;
}
}
}
HXDLIN( 564) while(hx::IsNotNull( W1->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x3 = W1->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) {
HXLINE( 565) x3->validate();
HXLINE( 566) x3->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x3,x3,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret12;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret12 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret12 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret12->next;
HXDLIN( 568) ret12->next = null();
}
HXDLIN( 568) ret12->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x3,x3)) {
HXLINE( 568) ret12->a = x3;
HXDLIN( 568) ret12->b = x3;
}
else {
HXLINE( 568) ret12->a = x3;
HXDLIN( 568) ret12->b = x3;
}
HXDLIN( 568) set->try_insert(ret12);
}
}
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite3 = W1->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite3 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y3 = cx_ite3->elt;
HXDLIN( 564) {
HXLINE( 565) x3->validate();
HXLINE( 566) y3->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x3,y3,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret13;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret13 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret13 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret13->next;
HXDLIN( 568) ret13->next = null();
}
HXDLIN( 568) ret13->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x3,y3)) {
HXLINE( 568) ret13->a = x3;
HXDLIN( 568) ret13->b = y3;
}
else {
HXLINE( 568) ret13->a = y3;
HXDLIN( 568) ret13->b = x3;
}
HXDLIN( 568) set->try_insert(ret13);
}
}
HXLINE( 564) cx_ite3 = cx_ite3->next;
}
}
}
}
}
HXLINE( 563) cx_ite = cx_ite->next;
}
}
}
HXDLIN( 563) while(hx::IsNotNull( V->head )){
HXLINE( 563) ::zpp_nape::callbacks::ZPP_CbType x4 = V->pop_unsafe();
HXDLIN( 563) {
HXLINE( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType cx_ite4 = W->head;
HXDLIN( 563) while(hx::IsNotNull( cx_ite4 )){
HXLINE( 563) ::zpp_nape::callbacks::ZPP_CbType y4 = cx_ite4->elt;
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet B2 = y4->cbsets;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet U2 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::UCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet V2 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::VCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet W2 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::WCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet aite2 = x4->cbsets->head;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet bite2 = B2->head;
HXDLIN( 564) while(true){
HXLINE( 564) bool _hx_tmp2;
HXDLIN( 564) if (hx::IsNotNull( aite2 )) {
HXLINE( 564) _hx_tmp2 = hx::IsNotNull( bite2 );
}
else {
HXLINE( 564) _hx_tmp2 = false;
}
HXDLIN( 564) if (!(_hx_tmp2)) {
HXLINE( 564) goto _hx_goto_47;
}
HXDLIN( 564) ::zpp_nape::callbacks::ZPP_CbSet a2 = aite2->elt;
HXDLIN( 564) ::zpp_nape::callbacks::ZPP_CbSet b2 = bite2->elt;
HXDLIN( 564) if (hx::IsEq( a2,b2 )) {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret14;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret14 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret14 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret14->next;
HXDLIN( 564) ret14->next = null();
}
HXDLIN( 564) ret14->elt = a2;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp10 = ret14;
HXDLIN( 564) temp10->next = W2->head;
HXDLIN( 564) W2->head = temp10;
HXDLIN( 564) W2->modified = true;
HXDLIN( 564) W2->length++;
}
HXDLIN( 564) aite2 = aite2->next;
HXDLIN( 564) bite2 = bite2->next;
}
else {
HXLINE( 564) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(a2,b2)) {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret15;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret15 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret15 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret15->next;
HXDLIN( 564) ret15->next = null();
}
HXDLIN( 564) ret15->elt = a2;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp11 = ret15;
HXDLIN( 564) temp11->next = U2->head;
HXDLIN( 564) U2->head = temp11;
HXDLIN( 564) U2->modified = true;
HXDLIN( 564) U2->length++;
}
HXDLIN( 564) aite2 = aite2->next;
}
else {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret16;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret16 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret16 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret16->next;
HXDLIN( 564) ret16->next = null();
}
HXDLIN( 564) ret16->elt = b2;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp12 = ret16;
HXDLIN( 564) temp12->next = V2->head;
HXDLIN( 564) V2->head = temp12;
HXDLIN( 564) V2->modified = true;
HXDLIN( 564) V2->length++;
}
HXDLIN( 564) bite2 = bite2->next;
}
}
}
_hx_goto_47:;
HXDLIN( 564) while(hx::IsNotNull( aite2 )){
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet o4 = aite2->elt;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret17;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret17 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret17 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret17->next;
HXDLIN( 564) ret17->next = null();
}
HXDLIN( 564) ret17->elt = o4;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp13 = ret17;
HXDLIN( 564) temp13->next = U2->head;
HXDLIN( 564) U2->head = temp13;
HXDLIN( 564) U2->modified = true;
HXDLIN( 564) U2->length++;
}
HXDLIN( 564) aite2 = aite2->next;
}
HXDLIN( 564) while(hx::IsNotNull( bite2 )){
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet o5 = bite2->elt;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret18;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret18 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret18 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret18->next;
HXDLIN( 564) ret18->next = null();
}
HXDLIN( 564) ret18->elt = o5;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp14 = ret18;
HXDLIN( 564) temp14->next = V2->head;
HXDLIN( 564) V2->head = temp14;
HXDLIN( 564) V2->modified = true;
HXDLIN( 564) V2->length++;
}
HXDLIN( 564) bite2 = bite2->next;
}
HXDLIN( 564) while(hx::IsNotNull( U2->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x5 = U2->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite5 = B2->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite5 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y5 = cx_ite5->elt;
HXDLIN( 564) {
HXLINE( 565) x5->validate();
HXLINE( 566) y5->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x5,y5,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret19;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret19 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret19 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret19->next;
HXDLIN( 568) ret19->next = null();
}
HXDLIN( 568) ret19->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x5,y5)) {
HXLINE( 568) ret19->a = x5;
HXDLIN( 568) ret19->b = y5;
}
else {
HXLINE( 568) ret19->a = y5;
HXDLIN( 568) ret19->b = x5;
}
HXDLIN( 568) set->try_insert(ret19);
}
}
HXLINE( 564) cx_ite5 = cx_ite5->next;
}
}
}
HXDLIN( 564) while(hx::IsNotNull( V2->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x6 = V2->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite6 = W2->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite6 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y6 = cx_ite6->elt;
HXDLIN( 564) {
HXLINE( 565) x6->validate();
HXLINE( 566) y6->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x6,y6,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret20;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret20 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret20 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret20->next;
HXDLIN( 568) ret20->next = null();
}
HXDLIN( 568) ret20->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x6,y6)) {
HXLINE( 568) ret20->a = x6;
HXDLIN( 568) ret20->b = y6;
}
else {
HXLINE( 568) ret20->a = y6;
HXDLIN( 568) ret20->b = x6;
}
HXDLIN( 568) set->try_insert(ret20);
}
}
HXLINE( 564) cx_ite6 = cx_ite6->next;
}
}
}
HXDLIN( 564) while(hx::IsNotNull( W2->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x7 = W2->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) {
HXLINE( 565) x7->validate();
HXLINE( 566) x7->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x7,x7,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret21;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret21 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret21 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret21->next;
HXDLIN( 568) ret21->next = null();
}
HXDLIN( 568) ret21->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x7,x7)) {
HXLINE( 568) ret21->a = x7;
HXDLIN( 568) ret21->b = x7;
}
else {
HXLINE( 568) ret21->a = x7;
HXDLIN( 568) ret21->b = x7;
}
HXDLIN( 568) set->try_insert(ret21);
}
}
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite7 = W2->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite7 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y7 = cx_ite7->elt;
HXDLIN( 564) {
HXLINE( 565) x7->validate();
HXLINE( 566) y7->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x7,y7,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret22;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret22 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret22 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret22->next;
HXDLIN( 568) ret22->next = null();
}
HXDLIN( 568) ret22->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x7,y7)) {
HXLINE( 568) ret22->a = x7;
HXDLIN( 568) ret22->b = y7;
}
else {
HXLINE( 568) ret22->a = y7;
HXDLIN( 568) ret22->b = x7;
}
HXDLIN( 568) set->try_insert(ret22);
}
}
HXLINE( 564) cx_ite7 = cx_ite7->next;
}
}
}
}
}
HXLINE( 563) cx_ite4 = cx_ite4->next;
}
}
}
HXDLIN( 563) while(hx::IsNotNull( W->head )){
HXLINE( 563) ::zpp_nape::callbacks::ZPP_CbType x8 = W->pop_unsafe();
HXDLIN( 563) {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet B3 = x8->cbsets;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet U3 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::UCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet V3 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::VCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet W3 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::WCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet aite3 = x8->cbsets->head;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet bite3 = B3->head;
HXDLIN( 564) while(true){
HXLINE( 564) bool _hx_tmp3;
HXDLIN( 564) if (hx::IsNotNull( aite3 )) {
HXLINE( 564) _hx_tmp3 = hx::IsNotNull( bite3 );
}
else {
HXLINE( 564) _hx_tmp3 = false;
}
HXDLIN( 564) if (!(_hx_tmp3)) {
HXLINE( 564) goto _hx_goto_57;
}
HXDLIN( 564) ::zpp_nape::callbacks::ZPP_CbSet a3 = aite3->elt;
HXDLIN( 564) ::zpp_nape::callbacks::ZPP_CbSet b3 = bite3->elt;
HXDLIN( 564) if (hx::IsEq( a3,b3 )) {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret23;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret23 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret23 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret23->next;
HXDLIN( 564) ret23->next = null();
}
HXDLIN( 564) ret23->elt = a3;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp15 = ret23;
HXDLIN( 564) temp15->next = W3->head;
HXDLIN( 564) W3->head = temp15;
HXDLIN( 564) W3->modified = true;
HXDLIN( 564) W3->length++;
}
HXDLIN( 564) aite3 = aite3->next;
HXDLIN( 564) bite3 = bite3->next;
}
else {
HXLINE( 564) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(a3,b3)) {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret24;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret24 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret24 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret24->next;
HXDLIN( 564) ret24->next = null();
}
HXDLIN( 564) ret24->elt = a3;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp16 = ret24;
HXDLIN( 564) temp16->next = U3->head;
HXDLIN( 564) U3->head = temp16;
HXDLIN( 564) U3->modified = true;
HXDLIN( 564) U3->length++;
}
HXDLIN( 564) aite3 = aite3->next;
}
else {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret25;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret25 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret25 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret25->next;
HXDLIN( 564) ret25->next = null();
}
HXDLIN( 564) ret25->elt = b3;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp17 = ret25;
HXDLIN( 564) temp17->next = V3->head;
HXDLIN( 564) V3->head = temp17;
HXDLIN( 564) V3->modified = true;
HXDLIN( 564) V3->length++;
}
HXDLIN( 564) bite3 = bite3->next;
}
}
}
_hx_goto_57:;
HXDLIN( 564) while(hx::IsNotNull( aite3 )){
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet o6 = aite3->elt;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret26;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret26 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret26 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret26->next;
HXDLIN( 564) ret26->next = null();
}
HXDLIN( 564) ret26->elt = o6;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp18 = ret26;
HXDLIN( 564) temp18->next = U3->head;
HXDLIN( 564) U3->head = temp18;
HXDLIN( 564) U3->modified = true;
HXDLIN( 564) U3->length++;
}
HXDLIN( 564) aite3 = aite3->next;
}
HXDLIN( 564) while(hx::IsNotNull( bite3 )){
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet o7 = bite3->elt;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret27;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret27 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret27 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret27->next;
HXDLIN( 564) ret27->next = null();
}
HXDLIN( 564) ret27->elt = o7;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp19 = ret27;
HXDLIN( 564) temp19->next = V3->head;
HXDLIN( 564) V3->head = temp19;
HXDLIN( 564) V3->modified = true;
HXDLIN( 564) V3->length++;
}
HXDLIN( 564) bite3 = bite3->next;
}
HXDLIN( 564) while(hx::IsNotNull( U3->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x9 = U3->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite8 = B3->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite8 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y8 = cx_ite8->elt;
HXDLIN( 564) {
HXLINE( 565) x9->validate();
HXLINE( 566) y8->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x9,y8,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret28;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret28 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret28 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret28->next;
HXDLIN( 568) ret28->next = null();
}
HXDLIN( 568) ret28->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x9,y8)) {
HXLINE( 568) ret28->a = x9;
HXDLIN( 568) ret28->b = y8;
}
else {
HXLINE( 568) ret28->a = y8;
HXDLIN( 568) ret28->b = x9;
}
HXDLIN( 568) set->try_insert(ret28);
}
}
HXLINE( 564) cx_ite8 = cx_ite8->next;
}
}
}
HXDLIN( 564) while(hx::IsNotNull( V3->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x10 = V3->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite9 = W3->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite9 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y9 = cx_ite9->elt;
HXDLIN( 564) {
HXLINE( 565) x10->validate();
HXLINE( 566) y9->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x10,y9,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret29;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret29 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret29 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret29->next;
HXDLIN( 568) ret29->next = null();
}
HXDLIN( 568) ret29->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x10,y9)) {
HXLINE( 568) ret29->a = x10;
HXDLIN( 568) ret29->b = y9;
}
else {
HXLINE( 568) ret29->a = y9;
HXDLIN( 568) ret29->b = x10;
}
HXDLIN( 568) set->try_insert(ret29);
}
}
HXLINE( 564) cx_ite9 = cx_ite9->next;
}
}
}
HXDLIN( 564) while(hx::IsNotNull( W3->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x11 = W3->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) {
HXLINE( 565) x11->validate();
HXLINE( 566) x11->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x11,x11,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret30;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret30 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret30 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret30->next;
HXDLIN( 568) ret30->next = null();
}
HXDLIN( 568) ret30->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x11,x11)) {
HXLINE( 568) ret30->a = x11;
HXDLIN( 568) ret30->b = x11;
}
else {
HXLINE( 568) ret30->a = x11;
HXDLIN( 568) ret30->b = x11;
}
HXDLIN( 568) set->try_insert(ret30);
}
}
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite10 = W3->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite10 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y10 = cx_ite10->elt;
HXDLIN( 564) {
HXLINE( 565) x11->validate();
HXLINE( 566) y10->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x11,y10,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret31;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret31 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret31 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret31->next;
HXDLIN( 568) ret31->next = null();
}
HXDLIN( 568) ret31->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x11,y10)) {
HXLINE( 568) ret31->a = x11;
HXDLIN( 568) ret31->b = y10;
}
else {
HXLINE( 568) ret31->a = y10;
HXDLIN( 568) ret31->b = x11;
}
HXDLIN( 568) set->try_insert(ret31);
}
}
HXLINE( 564) cx_ite10 = cx_ite10->next;
}
}
}
}
}
HXLINE( 563) {
HXLINE( 563) ::zpp_nape::util::ZNPNode_ZPP_CbType cx_ite11 = W->head;
HXDLIN( 563) while(hx::IsNotNull( cx_ite11 )){
HXLINE( 563) ::zpp_nape::callbacks::ZPP_CbType y11 = cx_ite11->elt;
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet B4 = y11->cbsets;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet U4 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::UCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet V4 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::VCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPList_ZPP_CbSet W4 = ::zpp_nape::callbacks::ZPP_InteractionListener_obj::WCbSet;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet aite4 = x8->cbsets->head;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet bite4 = B4->head;
HXDLIN( 564) while(true){
HXLINE( 564) bool _hx_tmp4;
HXDLIN( 564) if (hx::IsNotNull( aite4 )) {
HXLINE( 564) _hx_tmp4 = hx::IsNotNull( bite4 );
}
else {
HXLINE( 564) _hx_tmp4 = false;
}
HXDLIN( 564) if (!(_hx_tmp4)) {
HXLINE( 564) goto _hx_goto_67;
}
HXDLIN( 564) ::zpp_nape::callbacks::ZPP_CbSet a4 = aite4->elt;
HXDLIN( 564) ::zpp_nape::callbacks::ZPP_CbSet b4 = bite4->elt;
HXDLIN( 564) if (hx::IsEq( a4,b4 )) {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret32;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret32 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret32 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret32->next;
HXDLIN( 564) ret32->next = null();
}
HXDLIN( 564) ret32->elt = a4;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp20 = ret32;
HXDLIN( 564) temp20->next = W4->head;
HXDLIN( 564) W4->head = temp20;
HXDLIN( 564) W4->modified = true;
HXDLIN( 564) W4->length++;
}
HXDLIN( 564) aite4 = aite4->next;
HXDLIN( 564) bite4 = bite4->next;
}
else {
HXLINE( 564) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(a4,b4)) {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret33;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret33 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret33 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret33->next;
HXDLIN( 564) ret33->next = null();
}
HXDLIN( 564) ret33->elt = a4;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp21 = ret33;
HXDLIN( 564) temp21->next = U4->head;
HXDLIN( 564) U4->head = temp21;
HXDLIN( 564) U4->modified = true;
HXDLIN( 564) U4->length++;
}
HXDLIN( 564) aite4 = aite4->next;
}
else {
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret34;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret34 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret34 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret34->next;
HXDLIN( 564) ret34->next = null();
}
HXDLIN( 564) ret34->elt = b4;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp22 = ret34;
HXDLIN( 564) temp22->next = V4->head;
HXDLIN( 564) V4->head = temp22;
HXDLIN( 564) V4->modified = true;
HXDLIN( 564) V4->length++;
}
HXDLIN( 564) bite4 = bite4->next;
}
}
}
_hx_goto_67:;
HXDLIN( 564) while(hx::IsNotNull( aite4 )){
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet o8 = aite4->elt;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret35;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret35 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret35 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret35->next;
HXDLIN( 564) ret35->next = null();
}
HXDLIN( 564) ret35->elt = o8;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp23 = ret35;
HXDLIN( 564) temp23->next = U4->head;
HXDLIN( 564) U4->head = temp23;
HXDLIN( 564) U4->modified = true;
HXDLIN( 564) U4->length++;
}
HXDLIN( 564) aite4 = aite4->next;
}
HXDLIN( 564) while(hx::IsNotNull( bite4 )){
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet o9 = bite4->elt;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet ret36;
HXDLIN( 564) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool )) {
HXLINE( 564) ret36 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::__alloc( HX_CTX );
}
else {
HXLINE( 564) ret36 = ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet_obj::zpp_pool = ret36->next;
HXDLIN( 564) ret36->next = null();
}
HXDLIN( 564) ret36->elt = o9;
HXDLIN( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet temp24 = ret36;
HXDLIN( 564) temp24->next = V4->head;
HXDLIN( 564) V4->head = temp24;
HXDLIN( 564) V4->modified = true;
HXDLIN( 564) V4->length++;
}
HXDLIN( 564) bite4 = bite4->next;
}
HXDLIN( 564) while(hx::IsNotNull( U4->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x12 = U4->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite12 = B4->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite12 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y12 = cx_ite12->elt;
HXDLIN( 564) {
HXLINE( 565) x12->validate();
HXLINE( 566) y12->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x12,y12,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret37;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret37 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret37 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret37->next;
HXDLIN( 568) ret37->next = null();
}
HXDLIN( 568) ret37->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x12,y12)) {
HXLINE( 568) ret37->a = x12;
HXDLIN( 568) ret37->b = y12;
}
else {
HXLINE( 568) ret37->a = y12;
HXDLIN( 568) ret37->b = x12;
}
HXDLIN( 568) set->try_insert(ret37);
}
}
HXLINE( 564) cx_ite12 = cx_ite12->next;
}
}
}
HXDLIN( 564) while(hx::IsNotNull( V4->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x13 = V4->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite13 = W4->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite13 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y13 = cx_ite13->elt;
HXDLIN( 564) {
HXLINE( 565) x13->validate();
HXLINE( 566) y13->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x13,y13,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret38;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret38 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret38 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret38->next;
HXDLIN( 568) ret38->next = null();
}
HXDLIN( 568) ret38->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x13,y13)) {
HXLINE( 568) ret38->a = x13;
HXDLIN( 568) ret38->b = y13;
}
else {
HXLINE( 568) ret38->a = y13;
HXDLIN( 568) ret38->b = x13;
}
HXDLIN( 568) set->try_insert(ret38);
}
}
HXLINE( 564) cx_ite13 = cx_ite13->next;
}
}
}
HXDLIN( 564) while(hx::IsNotNull( W4->head )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet x14 = W4->pop_unsafe();
HXDLIN( 564) {
HXLINE( 564) {
HXLINE( 565) x14->validate();
HXLINE( 566) x14->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x14,x14,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret39;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret39 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret39 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret39->next;
HXDLIN( 568) ret39->next = null();
}
HXDLIN( 568) ret39->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x14,x14)) {
HXLINE( 568) ret39->a = x14;
HXDLIN( 568) ret39->b = x14;
}
else {
HXLINE( 568) ret39->a = x14;
HXDLIN( 568) ret39->b = x14;
}
HXDLIN( 568) set->try_insert(ret39);
}
}
HXLINE( 564) {
HXLINE( 564) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite14 = W4->head;
HXDLIN( 564) while(hx::IsNotNull( cx_ite14 )){
HXLINE( 564) ::zpp_nape::callbacks::ZPP_CbSet y14 = cx_ite14->elt;
HXDLIN( 564) {
HXLINE( 565) x14->validate();
HXLINE( 566) y14->validate();
HXLINE( 567) if (::zpp_nape::callbacks::ZPP_CbSet_obj::single_intersection(x14,y14,_gthis)) {
HXLINE( 568) ::zpp_nape::callbacks::ZPP_CbSetPair ret40;
HXDLIN( 568) {
HXLINE( 568) if (hx::IsNull( ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool )) {
HXLINE( 568) ret40 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::__alloc( HX_CTX );
}
else {
HXLINE( 568) ret40 = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 568) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = ret40->next;
HXDLIN( 568) ret40->next = null();
}
HXDLIN( 568) ret40->zip_listeners = true;
}
HXDLIN( 568) if (::zpp_nape::callbacks::ZPP_CbSet_obj::setlt(x14,y14)) {
HXLINE( 568) ret40->a = x14;
HXDLIN( 568) ret40->b = y14;
}
else {
HXLINE( 568) ret40->a = y14;
HXDLIN( 568) ret40->b = x14;
}
HXDLIN( 568) set->try_insert(ret40);
}
}
HXLINE( 564) cx_ite14 = cx_ite14->next;
}
}
}
}
}
HXLINE( 563) cx_ite11 = cx_ite11->next;
}
}
}
}
}
HXLINE( 572) if (hx::IsNotNull( set->parent )) {
HXLINE( 572) ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair cur = set->parent;
HXDLIN( 572) while(hx::IsNotNull( cur )){
HXLINE( 572) if (hx::IsNotNull( cur->prev )) {
HXLINE( 572) cur = cur->prev;
}
else {
HXLINE( 572) if (hx::IsNotNull( cur->next )) {
HXLINE( 572) cur = cur->next;
}
else {
HXLINE( 572) {
HXLINE( 572) ::zpp_nape::callbacks::ZPP_CbSetPair pair = cur->data;
HXLINE( 573) if (fresh) {
HXLINE( 573) _gthis->space->freshListenerType(pair->a,pair->b);
}
else {
HXLINE( 574) _gthis->space->nullListenerType(pair->a,pair->b);
}
HXLINE( 575) {
HXLINE( 576) ::zpp_nape::callbacks::ZPP_CbSetPair o10 = pair;
HXLINE( 585) {
HXLINE( 585) o10->a = (o10->b = null());
HXDLIN( 585) o10->listeners->clear();
}
HXLINE( 586) o10->next = ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool;
HXLINE( 587) ::zpp_nape::callbacks::ZPP_CbSetPair_obj::zpp_pool = o10;
}
}
HXLINE( 572) ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair ret41 = cur->parent;
HXDLIN( 572) if (hx::IsNotNull( ret41 )) {
HXLINE( 572) if (hx::IsEq( cur,ret41->prev )) {
HXLINE( 572) ret41->prev = null();
}
else {
HXLINE( 572) ret41->next = null();
}
HXDLIN( 572) cur->parent = null();
}
HXDLIN( 572) {
HXLINE( 572) ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair o11 = cur;
HXDLIN( 572) {
HXLINE( 572) o11->data = null();
HXDLIN( 572) o11->lt = null();
HXDLIN( 572) o11->swapped = null();
}
HXDLIN( 572) o11->next = ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair_obj::zpp_pool;
HXDLIN( 572) ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair_obj::zpp_pool = o11;
}
HXDLIN( 572) cur = ret41;
}
}
}
HXDLIN( 572) set->parent = null();
}
HXLINE( 593) {
HXLINE( 594) ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair o12 = set;
HXLINE( 603) {
HXLINE( 603) o12->data = null();
HXDLIN( 603) o12->lt = null();
HXDLIN( 603) o12->swapped = null();
}
HXLINE( 604) o12->next = ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair_obj::zpp_pool;
HXLINE( 605) ::zpp_nape::util::ZPP_Set_ZPP_CbSetPair_obj::zpp_pool = o12;
}
}
HX_DEFINE_DYNAMIC_FUNC1(ZPP_InteractionListener_obj,with_uniquesets,(void))
void ZPP_InteractionListener_obj::with_union( ::Dynamic lambda){
HX_STACKFRAME(&_hx_pos_02b7feea1016c80f_613_with_union)
HXLINE( 614) ::zpp_nape::util::ZNPNode_ZPP_CbType ite1 = this->options1->includes->head;
HXLINE( 615) ::zpp_nape::util::ZNPNode_ZPP_CbType ite2 = this->options2->includes->head;
HXLINE( 616) while(true){
HXLINE( 616) bool _hx_tmp;
HXDLIN( 616) if (hx::IsNotNull( ite1 )) {
HXLINE( 616) _hx_tmp = hx::IsNotNull( ite2 );
}
else {
HXLINE( 616) _hx_tmp = false;
}
HXDLIN( 616) if (!(_hx_tmp)) {
HXLINE( 616) goto _hx_goto_78;
}
HXLINE( 617) ::zpp_nape::callbacks::ZPP_CbType cb1 = ite1->elt;
HXLINE( 618) ::zpp_nape::callbacks::ZPP_CbType cb2 = ite2->elt;
HXLINE( 619) if (hx::IsEq( cb1,cb2 )) {
HXLINE( 620) lambda(cb1);
HXLINE( 621) ite1 = ite1->next;
HXLINE( 622) ite2 = ite2->next;
}
else {
HXLINE( 624) if ((cb1->id < cb2->id)) {
HXLINE( 625) lambda(cb1);
HXLINE( 626) ite1 = ite1->next;
}
else {
HXLINE( 629) lambda(cb2);
HXLINE( 630) ite2 = ite2->next;
}
}
}
_hx_goto_78:;
HXLINE( 633) while(hx::IsNotNull( ite1 )){
HXLINE( 634) lambda(ite1->elt);
HXLINE( 635) ite1 = ite1->next;
}
HXLINE( 637) while(hx::IsNotNull( ite2 )){
HXLINE( 638) lambda(ite2->elt);
HXLINE( 639) ite2 = ite2->next;
}
}
HX_DEFINE_DYNAMIC_FUNC1(ZPP_InteractionListener_obj,with_union,(void))
void ZPP_InteractionListener_obj::addedToSpace(){
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_642_addedToSpace)
HXDLIN( 642) ::zpp_nape::callbacks::ZPP_InteractionListener _gthis = hx::ObjectPtr<OBJ_>(this);
HXLINE( 643) bool pre = (this->type == 3);
HXLINE( 644) {
HXLINE( 644) ::zpp_nape::util::ZNPNode_ZPP_CbType ite1 = this->options1->includes->head;
HXDLIN( 644) ::zpp_nape::util::ZNPNode_ZPP_CbType ite2 = this->options2->includes->head;
HXDLIN( 644) while(true){
HXLINE( 644) bool _hx_tmp;
HXDLIN( 644) if (hx::IsNotNull( ite1 )) {
HXLINE( 644) _hx_tmp = hx::IsNotNull( ite2 );
}
else {
HXLINE( 644) _hx_tmp = false;
}
HXDLIN( 644) if (!(_hx_tmp)) {
HXLINE( 644) goto _hx_goto_82;
}
HXDLIN( 644) ::zpp_nape::callbacks::ZPP_CbType cb1 = ite1->elt;
HXDLIN( 644) ::zpp_nape::callbacks::ZPP_CbType cb2 = ite2->elt;
HXDLIN( 644) if (hx::IsEq( cb1,cb2 )) {
HXLINE( 644) {
HXLINE( 645) {
HXLINE( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener pre1 = null();
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener cx_ite = cb1->listeners->head;
HXDLIN( 645) while(hx::IsNotNull( cx_ite )){
HXLINE( 645) ::zpp_nape::callbacks::ZPP_InteractionListener j = cx_ite->elt;
HXDLIN( 645) {
HXLINE( 645) bool _hx_tmp1;
HXDLIN( 645) if ((_gthis->precedence <= j->precedence)) {
HXLINE( 645) if ((_gthis->precedence == j->precedence)) {
HXLINE( 645) _hx_tmp1 = (_gthis->id > j->id);
}
else {
HXLINE( 645) _hx_tmp1 = false;
}
}
else {
HXLINE( 645) _hx_tmp1 = true;
}
HXDLIN( 645) if (_hx_tmp1) {
HXLINE( 645) goto _hx_goto_83;
}
HXDLIN( 645) pre1 = cx_ite;
}
HXDLIN( 645) cx_ite = cx_ite->next;
}
_hx_goto_83:;
}
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPList_ZPP_InteractionListener _this = cb1->listeners;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener ret;
HXDLIN( 645) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool )) {
HXLINE( 645) ret = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::__alloc( HX_CTX );
}
else {
HXLINE( 645) ret = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool = ret->next;
HXDLIN( 645) ret->next = null();
}
HXDLIN( 645) ret->elt = _gthis;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener temp = ret;
HXDLIN( 645) if (hx::IsNull( pre1 )) {
HXLINE( 645) temp->next = _this->head;
HXDLIN( 645) _this->head = temp;
}
else {
HXLINE( 645) temp->next = pre1->next;
HXDLIN( 645) pre1->next = temp;
}
HXDLIN( 645) _this->pushmod = (_this->modified = true);
HXDLIN( 645) _this->length++;
}
}
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite1 = cb1->cbsets->head;
HXDLIN( 645) while(hx::IsNotNull( cx_ite1 )){
HXLINE( 645) ::zpp_nape::callbacks::ZPP_CbSet cb = cx_ite1->elt;
HXDLIN( 645) {
HXLINE( 645) cb->zip_listeners = true;
HXDLIN( 645) cb->invalidate_pairs();
}
HXDLIN( 645) cx_ite1 = cx_ite1->next;
}
}
}
HXLINE( 646) if (pre) {
HXLINE( 648) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite2 = cb1->interactors->head;
HXLINE( 649) while(hx::IsNotNull( cx_ite2 )){
HXLINE( 650) ::zpp_nape::phys::ZPP_Interactor i = cx_ite2->elt;
HXLINE( 651) i->wake();
HXLINE( 652) cx_ite2 = cx_ite2->next;
}
}
}
HXLINE( 644) ite1 = ite1->next;
HXDLIN( 644) ite2 = ite2->next;
}
else {
HXLINE( 644) if ((cb1->id < cb2->id)) {
HXLINE( 644) {
HXLINE( 645) {
HXLINE( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener pre2 = null();
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener cx_ite3 = cb1->listeners->head;
HXDLIN( 645) while(hx::IsNotNull( cx_ite3 )){
HXLINE( 645) ::zpp_nape::callbacks::ZPP_InteractionListener j1 = cx_ite3->elt;
HXDLIN( 645) {
HXLINE( 645) bool _hx_tmp2;
HXDLIN( 645) if ((_gthis->precedence <= j1->precedence)) {
HXLINE( 645) if ((_gthis->precedence == j1->precedence)) {
HXLINE( 645) _hx_tmp2 = (_gthis->id > j1->id);
}
else {
HXLINE( 645) _hx_tmp2 = false;
}
}
else {
HXLINE( 645) _hx_tmp2 = true;
}
HXDLIN( 645) if (_hx_tmp2) {
HXLINE( 645) goto _hx_goto_86;
}
HXDLIN( 645) pre2 = cx_ite3;
}
HXDLIN( 645) cx_ite3 = cx_ite3->next;
}
_hx_goto_86:;
}
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPList_ZPP_InteractionListener _this1 = cb1->listeners;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener ret1;
HXDLIN( 645) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool )) {
HXLINE( 645) ret1 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::__alloc( HX_CTX );
}
else {
HXLINE( 645) ret1 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool = ret1->next;
HXDLIN( 645) ret1->next = null();
}
HXDLIN( 645) ret1->elt = _gthis;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener temp1 = ret1;
HXDLIN( 645) if (hx::IsNull( pre2 )) {
HXLINE( 645) temp1->next = _this1->head;
HXDLIN( 645) _this1->head = temp1;
}
else {
HXLINE( 645) temp1->next = pre2->next;
HXDLIN( 645) pre2->next = temp1;
}
HXDLIN( 645) _this1->pushmod = (_this1->modified = true);
HXDLIN( 645) _this1->length++;
}
}
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite4 = cb1->cbsets->head;
HXDLIN( 645) while(hx::IsNotNull( cx_ite4 )){
HXLINE( 645) ::zpp_nape::callbacks::ZPP_CbSet cb3 = cx_ite4->elt;
HXDLIN( 645) {
HXLINE( 645) cb3->zip_listeners = true;
HXDLIN( 645) cb3->invalidate_pairs();
}
HXDLIN( 645) cx_ite4 = cx_ite4->next;
}
}
}
HXLINE( 646) if (pre) {
HXLINE( 648) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite5 = cb1->interactors->head;
HXLINE( 649) while(hx::IsNotNull( cx_ite5 )){
HXLINE( 650) ::zpp_nape::phys::ZPP_Interactor i1 = cx_ite5->elt;
HXLINE( 651) i1->wake();
HXLINE( 652) cx_ite5 = cx_ite5->next;
}
}
}
HXLINE( 644) ite1 = ite1->next;
}
else {
HXLINE( 644) {
HXLINE( 645) {
HXLINE( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener pre3 = null();
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener cx_ite6 = cb2->listeners->head;
HXDLIN( 645) while(hx::IsNotNull( cx_ite6 )){
HXLINE( 645) ::zpp_nape::callbacks::ZPP_InteractionListener j2 = cx_ite6->elt;
HXDLIN( 645) {
HXLINE( 645) bool _hx_tmp3;
HXDLIN( 645) if ((_gthis->precedence <= j2->precedence)) {
HXLINE( 645) if ((_gthis->precedence == j2->precedence)) {
HXLINE( 645) _hx_tmp3 = (_gthis->id > j2->id);
}
else {
HXLINE( 645) _hx_tmp3 = false;
}
}
else {
HXLINE( 645) _hx_tmp3 = true;
}
HXDLIN( 645) if (_hx_tmp3) {
HXLINE( 645) goto _hx_goto_89;
}
HXDLIN( 645) pre3 = cx_ite6;
}
HXDLIN( 645) cx_ite6 = cx_ite6->next;
}
_hx_goto_89:;
}
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPList_ZPP_InteractionListener _this2 = cb2->listeners;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener ret2;
HXDLIN( 645) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool )) {
HXLINE( 645) ret2 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::__alloc( HX_CTX );
}
else {
HXLINE( 645) ret2 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool = ret2->next;
HXDLIN( 645) ret2->next = null();
}
HXDLIN( 645) ret2->elt = _gthis;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener temp2 = ret2;
HXDLIN( 645) if (hx::IsNull( pre3 )) {
HXLINE( 645) temp2->next = _this2->head;
HXDLIN( 645) _this2->head = temp2;
}
else {
HXLINE( 645) temp2->next = pre3->next;
HXDLIN( 645) pre3->next = temp2;
}
HXDLIN( 645) _this2->pushmod = (_this2->modified = true);
HXDLIN( 645) _this2->length++;
}
}
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite7 = cb2->cbsets->head;
HXDLIN( 645) while(hx::IsNotNull( cx_ite7 )){
HXLINE( 645) ::zpp_nape::callbacks::ZPP_CbSet cb4 = cx_ite7->elt;
HXDLIN( 645) {
HXLINE( 645) cb4->zip_listeners = true;
HXDLIN( 645) cb4->invalidate_pairs();
}
HXDLIN( 645) cx_ite7 = cx_ite7->next;
}
}
}
HXLINE( 646) if (pre) {
HXLINE( 648) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite8 = cb2->interactors->head;
HXLINE( 649) while(hx::IsNotNull( cx_ite8 )){
HXLINE( 650) ::zpp_nape::phys::ZPP_Interactor i2 = cx_ite8->elt;
HXLINE( 651) i2->wake();
HXLINE( 652) cx_ite8 = cx_ite8->next;
}
}
}
HXLINE( 644) ite2 = ite2->next;
}
}
}
_hx_goto_82:;
HXDLIN( 644) while(hx::IsNotNull( ite1 )){
HXLINE( 644) {
HXLINE( 644) ::zpp_nape::callbacks::ZPP_CbType cb5 = ite1->elt;
HXLINE( 645) {
HXLINE( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener pre4 = null();
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener cx_ite9 = cb5->listeners->head;
HXDLIN( 645) while(hx::IsNotNull( cx_ite9 )){
HXLINE( 645) ::zpp_nape::callbacks::ZPP_InteractionListener j3 = cx_ite9->elt;
HXDLIN( 645) {
HXLINE( 645) bool _hx_tmp4;
HXDLIN( 645) if ((_gthis->precedence <= j3->precedence)) {
HXLINE( 645) if ((_gthis->precedence == j3->precedence)) {
HXLINE( 645) _hx_tmp4 = (_gthis->id > j3->id);
}
else {
HXLINE( 645) _hx_tmp4 = false;
}
}
else {
HXLINE( 645) _hx_tmp4 = true;
}
HXDLIN( 645) if (_hx_tmp4) {
HXLINE( 645) goto _hx_goto_93;
}
HXDLIN( 645) pre4 = cx_ite9;
}
HXDLIN( 645) cx_ite9 = cx_ite9->next;
}
_hx_goto_93:;
}
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPList_ZPP_InteractionListener _this3 = cb5->listeners;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener ret3;
HXDLIN( 645) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool )) {
HXLINE( 645) ret3 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::__alloc( HX_CTX );
}
else {
HXLINE( 645) ret3 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool = ret3->next;
HXDLIN( 645) ret3->next = null();
}
HXDLIN( 645) ret3->elt = _gthis;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener temp3 = ret3;
HXDLIN( 645) if (hx::IsNull( pre4 )) {
HXLINE( 645) temp3->next = _this3->head;
HXDLIN( 645) _this3->head = temp3;
}
else {
HXLINE( 645) temp3->next = pre4->next;
HXDLIN( 645) pre4->next = temp3;
}
HXDLIN( 645) _this3->pushmod = (_this3->modified = true);
HXDLIN( 645) _this3->length++;
}
}
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite10 = cb5->cbsets->head;
HXDLIN( 645) while(hx::IsNotNull( cx_ite10 )){
HXLINE( 645) ::zpp_nape::callbacks::ZPP_CbSet cb6 = cx_ite10->elt;
HXDLIN( 645) {
HXLINE( 645) cb6->zip_listeners = true;
HXDLIN( 645) cb6->invalidate_pairs();
}
HXDLIN( 645) cx_ite10 = cx_ite10->next;
}
}
}
HXLINE( 646) if (pre) {
HXLINE( 648) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite11 = cb5->interactors->head;
HXLINE( 649) while(hx::IsNotNull( cx_ite11 )){
HXLINE( 650) ::zpp_nape::phys::ZPP_Interactor i3 = cx_ite11->elt;
HXLINE( 651) i3->wake();
HXLINE( 652) cx_ite11 = cx_ite11->next;
}
}
}
HXLINE( 644) ite1 = ite1->next;
}
HXDLIN( 644) while(hx::IsNotNull( ite2 )){
HXLINE( 644) {
HXLINE( 644) ::zpp_nape::callbacks::ZPP_CbType cb7 = ite2->elt;
HXLINE( 645) {
HXLINE( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener pre5 = null();
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener cx_ite12 = cb7->listeners->head;
HXDLIN( 645) while(hx::IsNotNull( cx_ite12 )){
HXLINE( 645) ::zpp_nape::callbacks::ZPP_InteractionListener j4 = cx_ite12->elt;
HXDLIN( 645) {
HXLINE( 645) bool _hx_tmp5;
HXDLIN( 645) if ((_gthis->precedence <= j4->precedence)) {
HXLINE( 645) if ((_gthis->precedence == j4->precedence)) {
HXLINE( 645) _hx_tmp5 = (_gthis->id > j4->id);
}
else {
HXLINE( 645) _hx_tmp5 = false;
}
}
else {
HXLINE( 645) _hx_tmp5 = true;
}
HXDLIN( 645) if (_hx_tmp5) {
HXLINE( 645) goto _hx_goto_97;
}
HXDLIN( 645) pre5 = cx_ite12;
}
HXDLIN( 645) cx_ite12 = cx_ite12->next;
}
_hx_goto_97:;
}
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPList_ZPP_InteractionListener _this4 = cb7->listeners;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener ret4;
HXDLIN( 645) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool )) {
HXLINE( 645) ret4 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::__alloc( HX_CTX );
}
else {
HXLINE( 645) ret4 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool = ret4->next;
HXDLIN( 645) ret4->next = null();
}
HXDLIN( 645) ret4->elt = _gthis;
HXDLIN( 645) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener temp4 = ret4;
HXDLIN( 645) if (hx::IsNull( pre5 )) {
HXLINE( 645) temp4->next = _this4->head;
HXDLIN( 645) _this4->head = temp4;
}
else {
HXLINE( 645) temp4->next = pre5->next;
HXDLIN( 645) pre5->next = temp4;
}
HXDLIN( 645) _this4->pushmod = (_this4->modified = true);
HXDLIN( 645) _this4->length++;
}
}
HXDLIN( 645) {
HXLINE( 645) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite13 = cb7->cbsets->head;
HXDLIN( 645) while(hx::IsNotNull( cx_ite13 )){
HXLINE( 645) ::zpp_nape::callbacks::ZPP_CbSet cb8 = cx_ite13->elt;
HXDLIN( 645) {
HXLINE( 645) cb8->zip_listeners = true;
HXDLIN( 645) cb8->invalidate_pairs();
}
HXDLIN( 645) cx_ite13 = cx_ite13->next;
}
}
}
HXLINE( 646) if (pre) {
HXLINE( 648) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite14 = cb7->interactors->head;
HXLINE( 649) while(hx::IsNotNull( cx_ite14 )){
HXLINE( 650) ::zpp_nape::phys::ZPP_Interactor i4 = cx_ite14->elt;
HXLINE( 651) i4->wake();
HXLINE( 652) cx_ite14 = cx_ite14->next;
}
}
}
HXLINE( 644) ite2 = ite2->next;
}
}
HXLINE( 657) this->options1->handler = this->cbtype_change1_dyn();
HXLINE( 658) this->options2->handler = this->cbtype_change2_dyn();
HXLINE( 659) this->with_uniquesets(true);
}
void ZPP_InteractionListener_obj::removedFromSpace(){
HX_STACKFRAME(&_hx_pos_02b7feea1016c80f_661_removedFromSpace)
HXDLIN( 661) ::zpp_nape::callbacks::ZPP_InteractionListener _gthis = hx::ObjectPtr<OBJ_>(this);
HXLINE( 662) this->with_uniquesets(false);
HXLINE( 663) bool pre = (this->type == 3);
HXLINE( 664) {
HXLINE( 664) ::zpp_nape::util::ZNPNode_ZPP_CbType ite1 = this->options1->includes->head;
HXDLIN( 664) ::zpp_nape::util::ZNPNode_ZPP_CbType ite2 = this->options2->includes->head;
HXDLIN( 664) while(true){
HXLINE( 664) bool _hx_tmp;
HXDLIN( 664) if (hx::IsNotNull( ite1 )) {
HXLINE( 664) _hx_tmp = hx::IsNotNull( ite2 );
}
else {
HXLINE( 664) _hx_tmp = false;
}
HXDLIN( 664) if (!(_hx_tmp)) {
HXLINE( 664) goto _hx_goto_101;
}
HXDLIN( 664) ::zpp_nape::callbacks::ZPP_CbType cb1 = ite1->elt;
HXDLIN( 664) ::zpp_nape::callbacks::ZPP_CbType cb2 = ite2->elt;
HXDLIN( 664) if (hx::IsEq( cb1,cb2 )) {
HXLINE( 664) {
HXLINE( 665) {
HXLINE( 665) cb1->listeners->remove(_gthis);
HXDLIN( 665) {
HXLINE( 665) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite = cb1->cbsets->head;
HXDLIN( 665) while(hx::IsNotNull( cx_ite )){
HXLINE( 665) ::zpp_nape::callbacks::ZPP_CbSet cb = cx_ite->elt;
HXDLIN( 665) {
HXLINE( 665) cb->zip_listeners = true;
HXDLIN( 665) cb->invalidate_pairs();
}
HXDLIN( 665) cx_ite = cx_ite->next;
}
}
}
HXLINE( 666) if (pre) {
HXLINE( 668) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite1 = cb1->interactors->head;
HXLINE( 669) while(hx::IsNotNull( cx_ite1 )){
HXLINE( 670) ::zpp_nape::phys::ZPP_Interactor i = cx_ite1->elt;
HXLINE( 671) i->wake();
HXLINE( 672) cx_ite1 = cx_ite1->next;
}
}
}
HXLINE( 664) ite1 = ite1->next;
HXDLIN( 664) ite2 = ite2->next;
}
else {
HXLINE( 664) if ((cb1->id < cb2->id)) {
HXLINE( 664) {
HXLINE( 665) {
HXLINE( 665) cb1->listeners->remove(_gthis);
HXDLIN( 665) {
HXLINE( 665) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite2 = cb1->cbsets->head;
HXDLIN( 665) while(hx::IsNotNull( cx_ite2 )){
HXLINE( 665) ::zpp_nape::callbacks::ZPP_CbSet cb3 = cx_ite2->elt;
HXDLIN( 665) {
HXLINE( 665) cb3->zip_listeners = true;
HXDLIN( 665) cb3->invalidate_pairs();
}
HXDLIN( 665) cx_ite2 = cx_ite2->next;
}
}
}
HXLINE( 666) if (pre) {
HXLINE( 668) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite3 = cb1->interactors->head;
HXLINE( 669) while(hx::IsNotNull( cx_ite3 )){
HXLINE( 670) ::zpp_nape::phys::ZPP_Interactor i1 = cx_ite3->elt;
HXLINE( 671) i1->wake();
HXLINE( 672) cx_ite3 = cx_ite3->next;
}
}
}
HXLINE( 664) ite1 = ite1->next;
}
else {
HXLINE( 664) {
HXLINE( 665) {
HXLINE( 665) cb2->listeners->remove(_gthis);
HXDLIN( 665) {
HXLINE( 665) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite4 = cb2->cbsets->head;
HXDLIN( 665) while(hx::IsNotNull( cx_ite4 )){
HXLINE( 665) ::zpp_nape::callbacks::ZPP_CbSet cb4 = cx_ite4->elt;
HXDLIN( 665) {
HXLINE( 665) cb4->zip_listeners = true;
HXDLIN( 665) cb4->invalidate_pairs();
}
HXDLIN( 665) cx_ite4 = cx_ite4->next;
}
}
}
HXLINE( 666) if (pre) {
HXLINE( 668) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite5 = cb2->interactors->head;
HXLINE( 669) while(hx::IsNotNull( cx_ite5 )){
HXLINE( 670) ::zpp_nape::phys::ZPP_Interactor i2 = cx_ite5->elt;
HXLINE( 671) i2->wake();
HXLINE( 672) cx_ite5 = cx_ite5->next;
}
}
}
HXLINE( 664) ite2 = ite2->next;
}
}
}
_hx_goto_101:;
HXDLIN( 664) while(hx::IsNotNull( ite1 )){
HXLINE( 664) {
HXLINE( 664) ::zpp_nape::callbacks::ZPP_CbType cb5 = ite1->elt;
HXLINE( 665) {
HXLINE( 665) cb5->listeners->remove(_gthis);
HXDLIN( 665) {
HXLINE( 665) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite6 = cb5->cbsets->head;
HXDLIN( 665) while(hx::IsNotNull( cx_ite6 )){
HXLINE( 665) ::zpp_nape::callbacks::ZPP_CbSet cb6 = cx_ite6->elt;
HXDLIN( 665) {
HXLINE( 665) cb6->zip_listeners = true;
HXDLIN( 665) cb6->invalidate_pairs();
}
HXDLIN( 665) cx_ite6 = cx_ite6->next;
}
}
}
HXLINE( 666) if (pre) {
HXLINE( 668) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite7 = cb5->interactors->head;
HXLINE( 669) while(hx::IsNotNull( cx_ite7 )){
HXLINE( 670) ::zpp_nape::phys::ZPP_Interactor i3 = cx_ite7->elt;
HXLINE( 671) i3->wake();
HXLINE( 672) cx_ite7 = cx_ite7->next;
}
}
}
HXLINE( 664) ite1 = ite1->next;
}
HXDLIN( 664) while(hx::IsNotNull( ite2 )){
HXLINE( 664) {
HXLINE( 664) ::zpp_nape::callbacks::ZPP_CbType cb7 = ite2->elt;
HXLINE( 665) {
HXLINE( 665) cb7->listeners->remove(_gthis);
HXDLIN( 665) {
HXLINE( 665) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite8 = cb7->cbsets->head;
HXDLIN( 665) while(hx::IsNotNull( cx_ite8 )){
HXLINE( 665) ::zpp_nape::callbacks::ZPP_CbSet cb8 = cx_ite8->elt;
HXDLIN( 665) {
HXLINE( 665) cb8->zip_listeners = true;
HXDLIN( 665) cb8->invalidate_pairs();
}
HXDLIN( 665) cx_ite8 = cx_ite8->next;
}
}
}
HXLINE( 666) if (pre) {
HXLINE( 668) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite9 = cb7->interactors->head;
HXLINE( 669) while(hx::IsNotNull( cx_ite9 )){
HXLINE( 670) ::zpp_nape::phys::ZPP_Interactor i4 = cx_ite9->elt;
HXLINE( 671) i4->wake();
HXLINE( 672) cx_ite9 = cx_ite9->next;
}
}
}
HXLINE( 664) ite2 = ite2->next;
}
}
HXLINE( 677) this->options1->handler = null();
HXLINE( 678) this->options2->handler = null();
}
void ZPP_InteractionListener_obj::invalidate_precedence(){
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_680_invalidate_precedence)
HXDLIN( 680) ::zpp_nape::callbacks::ZPP_InteractionListener _gthis = hx::ObjectPtr<OBJ_>(this);
HXLINE( 681) if (hx::IsNotNull( this->space )) {
HXLINE( 682) bool pre = (this->type == 3);
HXLINE( 683) {
HXLINE( 683) ::zpp_nape::util::ZNPNode_ZPP_CbType ite1 = this->options1->includes->head;
HXDLIN( 683) ::zpp_nape::util::ZNPNode_ZPP_CbType ite2 = this->options2->includes->head;
HXDLIN( 683) while(true){
HXLINE( 683) bool _hx_tmp;
HXDLIN( 683) if (hx::IsNotNull( ite1 )) {
HXLINE( 683) _hx_tmp = hx::IsNotNull( ite2 );
}
else {
HXLINE( 683) _hx_tmp = false;
}
HXDLIN( 683) if (!(_hx_tmp)) {
HXLINE( 683) goto _hx_goto_115;
}
HXDLIN( 683) ::zpp_nape::callbacks::ZPP_CbType cb1 = ite1->elt;
HXDLIN( 683) ::zpp_nape::callbacks::ZPP_CbType cb2 = ite2->elt;
HXDLIN( 683) if (hx::IsEq( cb1,cb2 )) {
HXLINE( 683) {
HXLINE( 684) {
HXLINE( 684) cb1->listeners->remove(_gthis);
HXDLIN( 684) {
HXLINE( 684) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite = cb1->cbsets->head;
HXDLIN( 684) while(hx::IsNotNull( cx_ite )){
HXLINE( 684) ::zpp_nape::callbacks::ZPP_CbSet cb = cx_ite->elt;
HXDLIN( 684) {
HXLINE( 684) cb->zip_listeners = true;
HXDLIN( 684) cb->invalidate_pairs();
}
HXDLIN( 684) cx_ite = cx_ite->next;
}
}
}
HXLINE( 685) {
HXLINE( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener pre1 = null();
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener cx_ite1 = cb1->listeners->head;
HXDLIN( 685) while(hx::IsNotNull( cx_ite1 )){
HXLINE( 685) ::zpp_nape::callbacks::ZPP_InteractionListener j = cx_ite1->elt;
HXDLIN( 685) {
HXLINE( 685) bool _hx_tmp1;
HXDLIN( 685) if ((_gthis->precedence <= j->precedence)) {
HXLINE( 685) if ((_gthis->precedence == j->precedence)) {
HXLINE( 685) _hx_tmp1 = (_gthis->id > j->id);
}
else {
HXLINE( 685) _hx_tmp1 = false;
}
}
else {
HXLINE( 685) _hx_tmp1 = true;
}
HXDLIN( 685) if (_hx_tmp1) {
HXLINE( 685) goto _hx_goto_117;
}
HXDLIN( 685) pre1 = cx_ite1;
}
HXDLIN( 685) cx_ite1 = cx_ite1->next;
}
_hx_goto_117:;
}
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPList_ZPP_InteractionListener _this = cb1->listeners;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener ret;
HXDLIN( 685) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool )) {
HXLINE( 685) ret = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::__alloc( HX_CTX );
}
else {
HXLINE( 685) ret = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool = ret->next;
HXDLIN( 685) ret->next = null();
}
HXDLIN( 685) ret->elt = _gthis;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener temp = ret;
HXDLIN( 685) if (hx::IsNull( pre1 )) {
HXLINE( 685) temp->next = _this->head;
HXDLIN( 685) _this->head = temp;
}
else {
HXLINE( 685) temp->next = pre1->next;
HXDLIN( 685) pre1->next = temp;
}
HXDLIN( 685) _this->pushmod = (_this->modified = true);
HXDLIN( 685) _this->length++;
}
}
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite2 = cb1->cbsets->head;
HXDLIN( 685) while(hx::IsNotNull( cx_ite2 )){
HXLINE( 685) ::zpp_nape::callbacks::ZPP_CbSet cb3 = cx_ite2->elt;
HXDLIN( 685) {
HXLINE( 685) cb3->zip_listeners = true;
HXDLIN( 685) cb3->invalidate_pairs();
}
HXDLIN( 685) cx_ite2 = cx_ite2->next;
}
}
}
HXLINE( 686) if (pre) {
HXLINE( 688) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite3 = cb1->interactors->head;
HXLINE( 689) while(hx::IsNotNull( cx_ite3 )){
HXLINE( 690) ::zpp_nape::phys::ZPP_Interactor i = cx_ite3->elt;
HXLINE( 691) i->wake();
HXLINE( 692) cx_ite3 = cx_ite3->next;
}
}
}
HXLINE( 683) ite1 = ite1->next;
HXDLIN( 683) ite2 = ite2->next;
}
else {
HXLINE( 683) if ((cb1->id < cb2->id)) {
HXLINE( 683) {
HXLINE( 684) {
HXLINE( 684) cb1->listeners->remove(_gthis);
HXDLIN( 684) {
HXLINE( 684) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite4 = cb1->cbsets->head;
HXDLIN( 684) while(hx::IsNotNull( cx_ite4 )){
HXLINE( 684) ::zpp_nape::callbacks::ZPP_CbSet cb4 = cx_ite4->elt;
HXDLIN( 684) {
HXLINE( 684) cb4->zip_listeners = true;
HXDLIN( 684) cb4->invalidate_pairs();
}
HXDLIN( 684) cx_ite4 = cx_ite4->next;
}
}
}
HXLINE( 685) {
HXLINE( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener pre2 = null();
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener cx_ite5 = cb1->listeners->head;
HXDLIN( 685) while(hx::IsNotNull( cx_ite5 )){
HXLINE( 685) ::zpp_nape::callbacks::ZPP_InteractionListener j1 = cx_ite5->elt;
HXDLIN( 685) {
HXLINE( 685) bool _hx_tmp2;
HXDLIN( 685) if ((_gthis->precedence <= j1->precedence)) {
HXLINE( 685) if ((_gthis->precedence == j1->precedence)) {
HXLINE( 685) _hx_tmp2 = (_gthis->id > j1->id);
}
else {
HXLINE( 685) _hx_tmp2 = false;
}
}
else {
HXLINE( 685) _hx_tmp2 = true;
}
HXDLIN( 685) if (_hx_tmp2) {
HXLINE( 685) goto _hx_goto_121;
}
HXDLIN( 685) pre2 = cx_ite5;
}
HXDLIN( 685) cx_ite5 = cx_ite5->next;
}
_hx_goto_121:;
}
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPList_ZPP_InteractionListener _this1 = cb1->listeners;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener ret1;
HXDLIN( 685) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool )) {
HXLINE( 685) ret1 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::__alloc( HX_CTX );
}
else {
HXLINE( 685) ret1 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool = ret1->next;
HXDLIN( 685) ret1->next = null();
}
HXDLIN( 685) ret1->elt = _gthis;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener temp1 = ret1;
HXDLIN( 685) if (hx::IsNull( pre2 )) {
HXLINE( 685) temp1->next = _this1->head;
HXDLIN( 685) _this1->head = temp1;
}
else {
HXLINE( 685) temp1->next = pre2->next;
HXDLIN( 685) pre2->next = temp1;
}
HXDLIN( 685) _this1->pushmod = (_this1->modified = true);
HXDLIN( 685) _this1->length++;
}
}
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite6 = cb1->cbsets->head;
HXDLIN( 685) while(hx::IsNotNull( cx_ite6 )){
HXLINE( 685) ::zpp_nape::callbacks::ZPP_CbSet cb5 = cx_ite6->elt;
HXDLIN( 685) {
HXLINE( 685) cb5->zip_listeners = true;
HXDLIN( 685) cb5->invalidate_pairs();
}
HXDLIN( 685) cx_ite6 = cx_ite6->next;
}
}
}
HXLINE( 686) if (pre) {
HXLINE( 688) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite7 = cb1->interactors->head;
HXLINE( 689) while(hx::IsNotNull( cx_ite7 )){
HXLINE( 690) ::zpp_nape::phys::ZPP_Interactor i1 = cx_ite7->elt;
HXLINE( 691) i1->wake();
HXLINE( 692) cx_ite7 = cx_ite7->next;
}
}
}
HXLINE( 683) ite1 = ite1->next;
}
else {
HXLINE( 683) {
HXLINE( 684) {
HXLINE( 684) cb2->listeners->remove(_gthis);
HXDLIN( 684) {
HXLINE( 684) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite8 = cb2->cbsets->head;
HXDLIN( 684) while(hx::IsNotNull( cx_ite8 )){
HXLINE( 684) ::zpp_nape::callbacks::ZPP_CbSet cb6 = cx_ite8->elt;
HXDLIN( 684) {
HXLINE( 684) cb6->zip_listeners = true;
HXDLIN( 684) cb6->invalidate_pairs();
}
HXDLIN( 684) cx_ite8 = cx_ite8->next;
}
}
}
HXLINE( 685) {
HXLINE( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener pre3 = null();
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener cx_ite9 = cb2->listeners->head;
HXDLIN( 685) while(hx::IsNotNull( cx_ite9 )){
HXLINE( 685) ::zpp_nape::callbacks::ZPP_InteractionListener j2 = cx_ite9->elt;
HXDLIN( 685) {
HXLINE( 685) bool _hx_tmp3;
HXDLIN( 685) if ((_gthis->precedence <= j2->precedence)) {
HXLINE( 685) if ((_gthis->precedence == j2->precedence)) {
HXLINE( 685) _hx_tmp3 = (_gthis->id > j2->id);
}
else {
HXLINE( 685) _hx_tmp3 = false;
}
}
else {
HXLINE( 685) _hx_tmp3 = true;
}
HXDLIN( 685) if (_hx_tmp3) {
HXLINE( 685) goto _hx_goto_125;
}
HXDLIN( 685) pre3 = cx_ite9;
}
HXDLIN( 685) cx_ite9 = cx_ite9->next;
}
_hx_goto_125:;
}
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPList_ZPP_InteractionListener _this2 = cb2->listeners;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener ret2;
HXDLIN( 685) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool )) {
HXLINE( 685) ret2 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::__alloc( HX_CTX );
}
else {
HXLINE( 685) ret2 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool = ret2->next;
HXDLIN( 685) ret2->next = null();
}
HXDLIN( 685) ret2->elt = _gthis;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener temp2 = ret2;
HXDLIN( 685) if (hx::IsNull( pre3 )) {
HXLINE( 685) temp2->next = _this2->head;
HXDLIN( 685) _this2->head = temp2;
}
else {
HXLINE( 685) temp2->next = pre3->next;
HXDLIN( 685) pre3->next = temp2;
}
HXDLIN( 685) _this2->pushmod = (_this2->modified = true);
HXDLIN( 685) _this2->length++;
}
}
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite10 = cb2->cbsets->head;
HXDLIN( 685) while(hx::IsNotNull( cx_ite10 )){
HXLINE( 685) ::zpp_nape::callbacks::ZPP_CbSet cb7 = cx_ite10->elt;
HXDLIN( 685) {
HXLINE( 685) cb7->zip_listeners = true;
HXDLIN( 685) cb7->invalidate_pairs();
}
HXDLIN( 685) cx_ite10 = cx_ite10->next;
}
}
}
HXLINE( 686) if (pre) {
HXLINE( 688) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite11 = cb2->interactors->head;
HXLINE( 689) while(hx::IsNotNull( cx_ite11 )){
HXLINE( 690) ::zpp_nape::phys::ZPP_Interactor i2 = cx_ite11->elt;
HXLINE( 691) i2->wake();
HXLINE( 692) cx_ite11 = cx_ite11->next;
}
}
}
HXLINE( 683) ite2 = ite2->next;
}
}
}
_hx_goto_115:;
HXDLIN( 683) while(hx::IsNotNull( ite1 )){
HXLINE( 683) {
HXLINE( 683) ::zpp_nape::callbacks::ZPP_CbType cb8 = ite1->elt;
HXLINE( 684) {
HXLINE( 684) cb8->listeners->remove(_gthis);
HXDLIN( 684) {
HXLINE( 684) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite12 = cb8->cbsets->head;
HXDLIN( 684) while(hx::IsNotNull( cx_ite12 )){
HXLINE( 684) ::zpp_nape::callbacks::ZPP_CbSet cb9 = cx_ite12->elt;
HXDLIN( 684) {
HXLINE( 684) cb9->zip_listeners = true;
HXDLIN( 684) cb9->invalidate_pairs();
}
HXDLIN( 684) cx_ite12 = cx_ite12->next;
}
}
}
HXLINE( 685) {
HXLINE( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener pre4 = null();
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener cx_ite13 = cb8->listeners->head;
HXDLIN( 685) while(hx::IsNotNull( cx_ite13 )){
HXLINE( 685) ::zpp_nape::callbacks::ZPP_InteractionListener j3 = cx_ite13->elt;
HXDLIN( 685) {
HXLINE( 685) bool _hx_tmp4;
HXDLIN( 685) if ((_gthis->precedence <= j3->precedence)) {
HXLINE( 685) if ((_gthis->precedence == j3->precedence)) {
HXLINE( 685) _hx_tmp4 = (_gthis->id > j3->id);
}
else {
HXLINE( 685) _hx_tmp4 = false;
}
}
else {
HXLINE( 685) _hx_tmp4 = true;
}
HXDLIN( 685) if (_hx_tmp4) {
HXLINE( 685) goto _hx_goto_130;
}
HXDLIN( 685) pre4 = cx_ite13;
}
HXDLIN( 685) cx_ite13 = cx_ite13->next;
}
_hx_goto_130:;
}
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPList_ZPP_InteractionListener _this3 = cb8->listeners;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener ret3;
HXDLIN( 685) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool )) {
HXLINE( 685) ret3 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::__alloc( HX_CTX );
}
else {
HXLINE( 685) ret3 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool = ret3->next;
HXDLIN( 685) ret3->next = null();
}
HXDLIN( 685) ret3->elt = _gthis;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener temp3 = ret3;
HXDLIN( 685) if (hx::IsNull( pre4 )) {
HXLINE( 685) temp3->next = _this3->head;
HXDLIN( 685) _this3->head = temp3;
}
else {
HXLINE( 685) temp3->next = pre4->next;
HXDLIN( 685) pre4->next = temp3;
}
HXDLIN( 685) _this3->pushmod = (_this3->modified = true);
HXDLIN( 685) _this3->length++;
}
}
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite14 = cb8->cbsets->head;
HXDLIN( 685) while(hx::IsNotNull( cx_ite14 )){
HXLINE( 685) ::zpp_nape::callbacks::ZPP_CbSet cb10 = cx_ite14->elt;
HXDLIN( 685) {
HXLINE( 685) cb10->zip_listeners = true;
HXDLIN( 685) cb10->invalidate_pairs();
}
HXDLIN( 685) cx_ite14 = cx_ite14->next;
}
}
}
HXLINE( 686) if (pre) {
HXLINE( 688) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite15 = cb8->interactors->head;
HXLINE( 689) while(hx::IsNotNull( cx_ite15 )){
HXLINE( 690) ::zpp_nape::phys::ZPP_Interactor i3 = cx_ite15->elt;
HXLINE( 691) i3->wake();
HXLINE( 692) cx_ite15 = cx_ite15->next;
}
}
}
HXLINE( 683) ite1 = ite1->next;
}
HXDLIN( 683) while(hx::IsNotNull( ite2 )){
HXLINE( 683) {
HXLINE( 683) ::zpp_nape::callbacks::ZPP_CbType cb11 = ite2->elt;
HXLINE( 684) {
HXLINE( 684) cb11->listeners->remove(_gthis);
HXDLIN( 684) {
HXLINE( 684) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite16 = cb11->cbsets->head;
HXDLIN( 684) while(hx::IsNotNull( cx_ite16 )){
HXLINE( 684) ::zpp_nape::callbacks::ZPP_CbSet cb12 = cx_ite16->elt;
HXDLIN( 684) {
HXLINE( 684) cb12->zip_listeners = true;
HXDLIN( 684) cb12->invalidate_pairs();
}
HXDLIN( 684) cx_ite16 = cx_ite16->next;
}
}
}
HXLINE( 685) {
HXLINE( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener pre5 = null();
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener cx_ite17 = cb11->listeners->head;
HXDLIN( 685) while(hx::IsNotNull( cx_ite17 )){
HXLINE( 685) ::zpp_nape::callbacks::ZPP_InteractionListener j4 = cx_ite17->elt;
HXDLIN( 685) {
HXLINE( 685) bool _hx_tmp5;
HXDLIN( 685) if ((_gthis->precedence <= j4->precedence)) {
HXLINE( 685) if ((_gthis->precedence == j4->precedence)) {
HXLINE( 685) _hx_tmp5 = (_gthis->id > j4->id);
}
else {
HXLINE( 685) _hx_tmp5 = false;
}
}
else {
HXLINE( 685) _hx_tmp5 = true;
}
HXDLIN( 685) if (_hx_tmp5) {
HXLINE( 685) goto _hx_goto_135;
}
HXDLIN( 685) pre5 = cx_ite17;
}
HXDLIN( 685) cx_ite17 = cx_ite17->next;
}
_hx_goto_135:;
}
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPList_ZPP_InteractionListener _this4 = cb11->listeners;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener ret4;
HXDLIN( 685) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool )) {
HXLINE( 685) ret4 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::__alloc( HX_CTX );
}
else {
HXLINE( 685) ret4 = ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener_obj::zpp_pool = ret4->next;
HXDLIN( 685) ret4->next = null();
}
HXDLIN( 685) ret4->elt = _gthis;
HXDLIN( 685) ::zpp_nape::util::ZNPNode_ZPP_InteractionListener temp4 = ret4;
HXDLIN( 685) if (hx::IsNull( pre5 )) {
HXLINE( 685) temp4->next = _this4->head;
HXDLIN( 685) _this4->head = temp4;
}
else {
HXLINE( 685) temp4->next = pre5->next;
HXDLIN( 685) pre5->next = temp4;
}
HXDLIN( 685) _this4->pushmod = (_this4->modified = true);
HXDLIN( 685) _this4->length++;
}
}
HXDLIN( 685) {
HXLINE( 685) ::zpp_nape::util::ZNPNode_ZPP_CbSet cx_ite18 = cb11->cbsets->head;
HXDLIN( 685) while(hx::IsNotNull( cx_ite18 )){
HXLINE( 685) ::zpp_nape::callbacks::ZPP_CbSet cb13 = cx_ite18->elt;
HXDLIN( 685) {
HXLINE( 685) cb13->zip_listeners = true;
HXDLIN( 685) cb13->invalidate_pairs();
}
HXDLIN( 685) cx_ite18 = cx_ite18->next;
}
}
}
HXLINE( 686) if (pre) {
HXLINE( 688) ::zpp_nape::util::ZNPNode_ZPP_Interactor cx_ite19 = cb11->interactors->head;
HXLINE( 689) while(hx::IsNotNull( cx_ite19 )){
HXLINE( 690) ::zpp_nape::phys::ZPP_Interactor i4 = cx_ite19->elt;
HXLINE( 691) i4->wake();
HXLINE( 692) cx_ite19 = cx_ite19->next;
}
}
}
HXLINE( 683) ite2 = ite2->next;
}
}
}
}
void ZPP_InteractionListener_obj::cbtype_change1( ::zpp_nape::callbacks::ZPP_CbType cb,bool included,bool added){
HX_STACKFRAME(&_hx_pos_02b7feea1016c80f_700_cbtype_change1)
HXDLIN( 700) this->cbtype_change(this->options1,cb,included,added);
}
HX_DEFINE_DYNAMIC_FUNC3(ZPP_InteractionListener_obj,cbtype_change1,(void))
void ZPP_InteractionListener_obj::cbtype_change2( ::zpp_nape::callbacks::ZPP_CbType cb,bool included,bool added){
HX_STACKFRAME(&_hx_pos_02b7feea1016c80f_703_cbtype_change2)
HXDLIN( 703) this->cbtype_change(this->options2,cb,included,added);
}
HX_DEFINE_DYNAMIC_FUNC3(ZPP_InteractionListener_obj,cbtype_change2,(void))
void ZPP_InteractionListener_obj::cbtype_change( ::zpp_nape::callbacks::ZPP_OptionType options, ::zpp_nape::callbacks::ZPP_CbType cb,bool included,bool added){
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_705_cbtype_change)
HXLINE( 707) this->removedFromSpace();
HXLINE( 708) if (included) {
HXLINE( 708) if (added) {
HXLINE( 708) ::zpp_nape::util::ZNPNode_ZPP_CbType pre = null();
HXDLIN( 708) {
HXLINE( 708) ::zpp_nape::util::ZNPNode_ZPP_CbType cx_ite = options->includes->head;
HXDLIN( 708) while(hx::IsNotNull( cx_ite )){
HXLINE( 708) ::zpp_nape::callbacks::ZPP_CbType j = cx_ite->elt;
HXDLIN( 708) {
HXLINE( 708) if ((cb->id < j->id)) {
HXLINE( 708) goto _hx_goto_141;
}
HXDLIN( 708) pre = cx_ite;
}
HXDLIN( 708) cx_ite = cx_ite->next;
}
_hx_goto_141:;
}
HXDLIN( 708) {
HXLINE( 708) ::zpp_nape::util::ZNPList_ZPP_CbType _this = options->includes;
HXDLIN( 708) ::zpp_nape::util::ZNPNode_ZPP_CbType ret;
HXDLIN( 708) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 708) ret = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 708) ret = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 708) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret->next;
HXDLIN( 708) ret->next = null();
}
HXDLIN( 708) ret->elt = cb;
HXDLIN( 708) ::zpp_nape::util::ZNPNode_ZPP_CbType temp = ret;
HXDLIN( 708) if (hx::IsNull( pre )) {
HXLINE( 708) temp->next = _this->head;
HXDLIN( 708) _this->head = temp;
}
else {
HXLINE( 708) temp->next = pre->next;
HXDLIN( 708) pre->next = temp;
}
HXDLIN( 708) _this->pushmod = (_this->modified = true);
HXDLIN( 708) _this->length++;
}
}
else {
HXLINE( 708) options->includes->remove(cb);
}
}
else {
HXLINE( 708) if (added) {
HXLINE( 708) ::zpp_nape::util::ZNPNode_ZPP_CbType pre1 = null();
HXDLIN( 708) {
HXLINE( 708) ::zpp_nape::util::ZNPNode_ZPP_CbType cx_ite1 = options->excludes->head;
HXDLIN( 708) while(hx::IsNotNull( cx_ite1 )){
HXLINE( 708) ::zpp_nape::callbacks::ZPP_CbType j1 = cx_ite1->elt;
HXDLIN( 708) {
HXLINE( 708) if ((cb->id < j1->id)) {
HXLINE( 708) goto _hx_goto_142;
}
HXDLIN( 708) pre1 = cx_ite1;
}
HXDLIN( 708) cx_ite1 = cx_ite1->next;
}
_hx_goto_142:;
}
HXDLIN( 708) {
HXLINE( 708) ::zpp_nape::util::ZNPList_ZPP_CbType _this1 = options->excludes;
HXDLIN( 708) ::zpp_nape::util::ZNPNode_ZPP_CbType ret1;
HXDLIN( 708) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool )) {
HXLINE( 708) ret1 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::__alloc( HX_CTX );
}
else {
HXLINE( 708) ret1 = ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool;
HXDLIN( 708) ::zpp_nape::util::ZNPNode_ZPP_CbType_obj::zpp_pool = ret1->next;
HXDLIN( 708) ret1->next = null();
}
HXDLIN( 708) ret1->elt = cb;
HXDLIN( 708) ::zpp_nape::util::ZNPNode_ZPP_CbType temp1 = ret1;
HXDLIN( 708) if (hx::IsNull( pre1 )) {
HXLINE( 708) temp1->next = _this1->head;
HXDLIN( 708) _this1->head = temp1;
}
else {
HXLINE( 708) temp1->next = pre1->next;
HXDLIN( 708) pre1->next = temp1;
}
HXDLIN( 708) _this1->pushmod = (_this1->modified = true);
HXDLIN( 708) _this1->length++;
}
}
else {
HXLINE( 708) options->excludes->remove(cb);
}
}
HXLINE( 709) this->addedToSpace();
}
HX_DEFINE_DYNAMIC_FUNC4(ZPP_InteractionListener_obj,cbtype_change,(void))
void ZPP_InteractionListener_obj::swapEvent(int newev){
HX_STACKFRAME(&_hx_pos_02b7feea1016c80f_712_swapEvent)
HXLINE( 714) if ((this->type == 3)) {
HXLINE( 715) HX_STACK_DO_THROW(HX_("Error: PreListener event can only be PRE",ed,c3,53,5f));
}
else {
HXLINE( 717) bool _hx_tmp;
HXDLIN( 717) bool _hx_tmp1;
HXDLIN( 717) if ((newev != 0)) {
HXLINE( 717) _hx_tmp1 = (newev != 1);
}
else {
HXLINE( 717) _hx_tmp1 = false;
}
HXDLIN( 717) if (_hx_tmp1) {
HXLINE( 717) _hx_tmp = (newev != 6);
}
else {
HXLINE( 717) _hx_tmp = false;
}
HXDLIN( 717) if (_hx_tmp) {
HXLINE( 718) HX_STACK_DO_THROW(HX_("Error: InteractionListener event must be either BEGIN, END, ONGOING",82,8a,d3,e1));
}
}
HXLINE( 721) this->removedFromSpace();
HXLINE( 722) this->event = newev;
HXLINE( 723) this->addedToSpace();
}
::zpp_nape::util::ZNPList_ZPP_CbSet ZPP_InteractionListener_obj::UCbSet;
::zpp_nape::util::ZNPList_ZPP_CbSet ZPP_InteractionListener_obj::VCbSet;
::zpp_nape::util::ZNPList_ZPP_CbSet ZPP_InteractionListener_obj::WCbSet;
::zpp_nape::util::ZNPList_ZPP_CbType ZPP_InteractionListener_obj::UCbType;
::zpp_nape::util::ZNPList_ZPP_CbType ZPP_InteractionListener_obj::VCbType;
::zpp_nape::util::ZNPList_ZPP_CbType ZPP_InteractionListener_obj::WCbType;
hx::ObjectPtr< ZPP_InteractionListener_obj > ZPP_InteractionListener_obj::__new( ::nape::callbacks::OptionType options1, ::nape::callbacks::OptionType options2,int event,int type) {
hx::ObjectPtr< ZPP_InteractionListener_obj > __this = new ZPP_InteractionListener_obj();
__this->__construct(options1,options2,event,type);
return __this;
}
hx::ObjectPtr< ZPP_InteractionListener_obj > ZPP_InteractionListener_obj::__alloc(hx::Ctx *_hx_ctx, ::nape::callbacks::OptionType options1, ::nape::callbacks::OptionType options2,int event,int type) {
ZPP_InteractionListener_obj *__this = (ZPP_InteractionListener_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ZPP_InteractionListener_obj), true, "zpp_nape.callbacks.ZPP_InteractionListener"));
*(void **)__this = ZPP_InteractionListener_obj::_hx_vtable;
__this->__construct(options1,options2,event,type);
return __this;
}
ZPP_InteractionListener_obj::ZPP_InteractionListener_obj()
{
}
void ZPP_InteractionListener_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(ZPP_InteractionListener);
HX_MARK_MEMBER_NAME(outer_zni,"outer_zni");
HX_MARK_MEMBER_NAME(outer_znp,"outer_znp");
HX_MARK_MEMBER_NAME(itype,"itype");
HX_MARK_MEMBER_NAME(options1,"options1");
HX_MARK_MEMBER_NAME(options2,"options2");
HX_MARK_MEMBER_NAME(handleri,"handleri");
HX_MARK_MEMBER_NAME(allowSleepingCallbacks,"allowSleepingCallbacks");
HX_MARK_MEMBER_NAME(pure,"pure");
HX_MARK_MEMBER_NAME(handlerp,"handlerp");
::zpp_nape::callbacks::ZPP_Listener_obj::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void ZPP_InteractionListener_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(outer_zni,"outer_zni");
HX_VISIT_MEMBER_NAME(outer_znp,"outer_znp");
HX_VISIT_MEMBER_NAME(itype,"itype");
HX_VISIT_MEMBER_NAME(options1,"options1");
HX_VISIT_MEMBER_NAME(options2,"options2");
HX_VISIT_MEMBER_NAME(handleri,"handleri");
HX_VISIT_MEMBER_NAME(allowSleepingCallbacks,"allowSleepingCallbacks");
HX_VISIT_MEMBER_NAME(pure,"pure");
HX_VISIT_MEMBER_NAME(handlerp,"handlerp");
::zpp_nape::callbacks::ZPP_Listener_obj::__Visit(HX_VISIT_ARG);
}
hx::Val ZPP_InteractionListener_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"pure") ) { return hx::Val( pure ); }
if (HX_FIELD_EQ(inName,"wake") ) { return hx::Val( wake_dyn() ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"itype") ) { return hx::Val( itype ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"options1") ) { return hx::Val( options1 ); }
if (HX_FIELD_EQ(inName,"options2") ) { return hx::Val( options2 ); }
if (HX_FIELD_EQ(inName,"handleri") ) { return hx::Val( handleri ); }
if (HX_FIELD_EQ(inName,"handlerp") ) { return hx::Val( handlerp ); }
if (HX_FIELD_EQ(inName,"CbSetset") ) { return hx::Val( CbSetset_dyn() ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"outer_zni") ) { return hx::Val( outer_zni ); }
if (HX_FIELD_EQ(inName,"outer_znp") ) { return hx::Val( outer_znp ); }
if (HX_FIELD_EQ(inName,"CbTypeset") ) { return hx::Val( CbTypeset_dyn() ); }
if (HX_FIELD_EQ(inName,"swapEvent") ) { return hx::Val( swapEvent_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"with_union") ) { return hx::Val( with_union_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"addedToSpace") ) { return hx::Val( addedToSpace_dyn() ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"cbtype_change") ) { return hx::Val( cbtype_change_dyn() ); }
break;
case 14:
if (HX_FIELD_EQ(inName,"cbtype_change1") ) { return hx::Val( cbtype_change1_dyn() ); }
if (HX_FIELD_EQ(inName,"cbtype_change2") ) { return hx::Val( cbtype_change2_dyn() ); }
break;
case 15:
if (HX_FIELD_EQ(inName,"with_uniquesets") ) { return hx::Val( with_uniquesets_dyn() ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"removedFromSpace") ) { return hx::Val( removedFromSpace_dyn() ); }
break;
case 18:
if (HX_FIELD_EQ(inName,"setInteractionType") ) { return hx::Val( setInteractionType_dyn() ); }
break;
case 21:
if (HX_FIELD_EQ(inName,"invalidate_precedence") ) { return hx::Val( invalidate_precedence_dyn() ); }
break;
case 22:
if (HX_FIELD_EQ(inName,"allowSleepingCallbacks") ) { return hx::Val( allowSleepingCallbacks ); }
}
return super::__Field(inName,inCallProp);
}
bool ZPP_InteractionListener_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"UCbSet") ) { outValue = ( UCbSet ); return true; }
if (HX_FIELD_EQ(inName,"VCbSet") ) { outValue = ( VCbSet ); return true; }
if (HX_FIELD_EQ(inName,"WCbSet") ) { outValue = ( WCbSet ); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"UCbType") ) { outValue = ( UCbType ); return true; }
if (HX_FIELD_EQ(inName,"VCbType") ) { outValue = ( VCbType ); return true; }
if (HX_FIELD_EQ(inName,"WCbType") ) { outValue = ( WCbType ); return true; }
}
return false;
}
hx::Val ZPP_InteractionListener_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"pure") ) { pure=inValue.Cast< bool >(); return inValue; }
break;
case 5:
if (HX_FIELD_EQ(inName,"itype") ) { itype=inValue.Cast< int >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"options1") ) { options1=inValue.Cast< ::zpp_nape::callbacks::ZPP_OptionType >(); return inValue; }
if (HX_FIELD_EQ(inName,"options2") ) { options2=inValue.Cast< ::zpp_nape::callbacks::ZPP_OptionType >(); return inValue; }
if (HX_FIELD_EQ(inName,"handleri") ) { handleri=inValue.Cast< ::Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"handlerp") ) { handlerp=inValue.Cast< ::Dynamic >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"outer_zni") ) { outer_zni=inValue.Cast< ::nape::callbacks::InteractionListener >(); return inValue; }
if (HX_FIELD_EQ(inName,"outer_znp") ) { outer_znp=inValue.Cast< ::nape::callbacks::PreListener >(); return inValue; }
break;
case 22:
if (HX_FIELD_EQ(inName,"allowSleepingCallbacks") ) { allowSleepingCallbacks=inValue.Cast< bool >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
bool ZPP_InteractionListener_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"UCbSet") ) { UCbSet=ioValue.Cast< ::zpp_nape::util::ZNPList_ZPP_CbSet >(); return true; }
if (HX_FIELD_EQ(inName,"VCbSet") ) { VCbSet=ioValue.Cast< ::zpp_nape::util::ZNPList_ZPP_CbSet >(); return true; }
if (HX_FIELD_EQ(inName,"WCbSet") ) { WCbSet=ioValue.Cast< ::zpp_nape::util::ZNPList_ZPP_CbSet >(); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"UCbType") ) { UCbType=ioValue.Cast< ::zpp_nape::util::ZNPList_ZPP_CbType >(); return true; }
if (HX_FIELD_EQ(inName,"VCbType") ) { VCbType=ioValue.Cast< ::zpp_nape::util::ZNPList_ZPP_CbType >(); return true; }
if (HX_FIELD_EQ(inName,"WCbType") ) { WCbType=ioValue.Cast< ::zpp_nape::util::ZNPList_ZPP_CbType >(); return true; }
}
return false;
}
void ZPP_InteractionListener_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("outer_zni",31,4a,56,b7));
outFields->push(HX_("outer_znp",38,4a,56,b7));
outFields->push(HX_("itype",a3,db,1b,c2));
outFields->push(HX_("options1",13,bf,6e,1e));
outFields->push(HX_("options2",14,bf,6e,1e));
outFields->push(HX_("allowSleepingCallbacks",9a,0e,6b,5a));
outFields->push(HX_("pure",f8,10,61,4a));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static hx::StorageInfo ZPP_InteractionListener_obj_sMemberStorageInfo[] = {
{hx::fsObject /* ::nape::callbacks::InteractionListener */ ,(int)offsetof(ZPP_InteractionListener_obj,outer_zni),HX_("outer_zni",31,4a,56,b7)},
{hx::fsObject /* ::nape::callbacks::PreListener */ ,(int)offsetof(ZPP_InteractionListener_obj,outer_znp),HX_("outer_znp",38,4a,56,b7)},
{hx::fsInt,(int)offsetof(ZPP_InteractionListener_obj,itype),HX_("itype",a3,db,1b,c2)},
{hx::fsObject /* ::zpp_nape::callbacks::ZPP_OptionType */ ,(int)offsetof(ZPP_InteractionListener_obj,options1),HX_("options1",13,bf,6e,1e)},
{hx::fsObject /* ::zpp_nape::callbacks::ZPP_OptionType */ ,(int)offsetof(ZPP_InteractionListener_obj,options2),HX_("options2",14,bf,6e,1e)},
{hx::fsObject /* ::Dynamic */ ,(int)offsetof(ZPP_InteractionListener_obj,handleri),HX_("handleri",5f,21,24,d5)},
{hx::fsBool,(int)offsetof(ZPP_InteractionListener_obj,allowSleepingCallbacks),HX_("allowSleepingCallbacks",9a,0e,6b,5a)},
{hx::fsBool,(int)offsetof(ZPP_InteractionListener_obj,pure),HX_("pure",f8,10,61,4a)},
{hx::fsObject /* ::Dynamic */ ,(int)offsetof(ZPP_InteractionListener_obj,handlerp),HX_("handlerp",66,21,24,d5)},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo ZPP_InteractionListener_obj_sStaticStorageInfo[] = {
{hx::fsObject /* ::zpp_nape::util::ZNPList_ZPP_CbSet */ ,(void *) &ZPP_InteractionListener_obj::UCbSet,HX_("UCbSet",ae,c5,34,d1)},
{hx::fsObject /* ::zpp_nape::util::ZNPList_ZPP_CbSet */ ,(void *) &ZPP_InteractionListener_obj::VCbSet,HX_("VCbSet",0d,22,90,37)},
{hx::fsObject /* ::zpp_nape::util::ZNPList_ZPP_CbSet */ ,(void *) &ZPP_InteractionListener_obj::WCbSet,HX_("WCbSet",6c,7e,eb,9d)},
{hx::fsObject /* ::zpp_nape::util::ZNPList_ZPP_CbType */ ,(void *) &ZPP_InteractionListener_obj::UCbType,HX_("UCbType",2e,93,b0,3d)},
{hx::fsObject /* ::zpp_nape::util::ZNPList_ZPP_CbType */ ,(void *) &ZPP_InteractionListener_obj::VCbType,HX_("VCbType",ef,09,46,67)},
{hx::fsObject /* ::zpp_nape::util::ZNPList_ZPP_CbType */ ,(void *) &ZPP_InteractionListener_obj::WCbType,HX_("WCbType",b0,80,db,90)},
{ hx::fsUnknown, 0, null()}
};
#endif
static ::String ZPP_InteractionListener_obj_sMemberFields[] = {
HX_("outer_zni",31,4a,56,b7),
HX_("outer_znp",38,4a,56,b7),
HX_("itype",a3,db,1b,c2),
HX_("options1",13,bf,6e,1e),
HX_("options2",14,bf,6e,1e),
HX_("handleri",5f,21,24,d5),
HX_("allowSleepingCallbacks",9a,0e,6b,5a),
HX_("pure",f8,10,61,4a),
HX_("handlerp",66,21,24,d5),
HX_("setInteractionType",2a,7a,3d,98),
HX_("wake",24,5c,f2,4e),
HX_("CbSetset",5f,39,87,87),
HX_("CbTypeset",29,ec,b2,e0),
HX_("with_uniquesets",fb,2a,8e,cf),
HX_("with_union",d6,6a,04,5a),
HX_("addedToSpace",6b,44,b0,09),
HX_("removedFromSpace",3c,43,d1,b7),
HX_("invalidate_precedence",8e,f5,4a,df),
HX_("cbtype_change1",1b,90,ed,10),
HX_("cbtype_change2",1c,90,ed,10),
HX_("cbtype_change",56,5b,22,6d),
HX_("swapEvent",87,d8,71,eb),
::String(null()) };
static void ZPP_InteractionListener_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(ZPP_InteractionListener_obj::UCbSet,"UCbSet");
HX_MARK_MEMBER_NAME(ZPP_InteractionListener_obj::VCbSet,"VCbSet");
HX_MARK_MEMBER_NAME(ZPP_InteractionListener_obj::WCbSet,"WCbSet");
HX_MARK_MEMBER_NAME(ZPP_InteractionListener_obj::UCbType,"UCbType");
HX_MARK_MEMBER_NAME(ZPP_InteractionListener_obj::VCbType,"VCbType");
HX_MARK_MEMBER_NAME(ZPP_InteractionListener_obj::WCbType,"WCbType");
};
#ifdef HXCPP_VISIT_ALLOCS
static void ZPP_InteractionListener_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(ZPP_InteractionListener_obj::UCbSet,"UCbSet");
HX_VISIT_MEMBER_NAME(ZPP_InteractionListener_obj::VCbSet,"VCbSet");
HX_VISIT_MEMBER_NAME(ZPP_InteractionListener_obj::WCbSet,"WCbSet");
HX_VISIT_MEMBER_NAME(ZPP_InteractionListener_obj::UCbType,"UCbType");
HX_VISIT_MEMBER_NAME(ZPP_InteractionListener_obj::VCbType,"VCbType");
HX_VISIT_MEMBER_NAME(ZPP_InteractionListener_obj::WCbType,"WCbType");
};
#endif
hx::Class ZPP_InteractionListener_obj::__mClass;
static ::String ZPP_InteractionListener_obj_sStaticFields[] = {
HX_("UCbSet",ae,c5,34,d1),
HX_("VCbSet",0d,22,90,37),
HX_("WCbSet",6c,7e,eb,9d),
HX_("UCbType",2e,93,b0,3d),
HX_("VCbType",ef,09,46,67),
HX_("WCbType",b0,80,db,90),
::String(null())
};
void ZPP_InteractionListener_obj::__register()
{
ZPP_InteractionListener_obj _hx_dummy;
ZPP_InteractionListener_obj::_hx_vtable = *(void **)&_hx_dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_("zpp_nape.callbacks.ZPP_InteractionListener",a0,84,37,ee);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &ZPP_InteractionListener_obj::__GetStatic;
__mClass->mSetStaticField = &ZPP_InteractionListener_obj::__SetStatic;
__mClass->mMarkFunc = ZPP_InteractionListener_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(ZPP_InteractionListener_obj_sStaticFields);
__mClass->mMembers = hx::Class_obj::dupFunctions(ZPP_InteractionListener_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< ZPP_InteractionListener_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = ZPP_InteractionListener_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = ZPP_InteractionListener_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = ZPP_InteractionListener_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void ZPP_InteractionListener_obj::__boot()
{
{
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_385_boot)
HXDLIN( 385) UCbSet = ::zpp_nape::util::ZNPList_ZPP_CbSet_obj::__alloc( HX_CTX );
}
{
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_386_boot)
HXDLIN( 386) VCbSet = ::zpp_nape::util::ZNPList_ZPP_CbSet_obj::__alloc( HX_CTX );
}
{
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_387_boot)
HXDLIN( 387) WCbSet = ::zpp_nape::util::ZNPList_ZPP_CbSet_obj::__alloc( HX_CTX );
}
{
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_464_boot)
HXDLIN( 464) UCbType = ::zpp_nape::util::ZNPList_ZPP_CbType_obj::__alloc( HX_CTX );
}
{
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_465_boot)
HXDLIN( 465) VCbType = ::zpp_nape::util::ZNPList_ZPP_CbType_obj::__alloc( HX_CTX );
}
{
HX_GC_STACKFRAME(&_hx_pos_02b7feea1016c80f_466_boot)
HXDLIN( 466) WCbType = ::zpp_nape::util::ZNPList_ZPP_CbType_obj::__alloc( HX_CTX );
}
}
} // end namespace zpp_nape
} // end namespace callbacks
| 45.552217 | 267 | 0.564467 | [
"3d"
] |
9112ee7861135c710723d112afe85d33bca829e5 | 40,406 | cpp | C++ | ovr_sdk_mobile/VrAppFramework/Src/GlTexture.cpp | ejeinc/Meganekko | c62d82e8a5d2eb67af056282f4ff7c90cbd73494 | [
"Apache-2.0"
] | 25 | 2015-10-08T09:35:35.000Z | 2018-09-14T06:53:39.000Z | ovr_sdk_mobile/VrAppFramework/Src/GlTexture.cpp | ejeinc/Meganekko | c62d82e8a5d2eb67af056282f4ff7c90cbd73494 | [
"Apache-2.0"
] | 16 | 2015-09-28T07:21:55.000Z | 2017-04-25T02:31:57.000Z | ovr_sdk_mobile/VrAppFramework/Src/GlTexture.cpp | ejeinc/Meganekko | c62d82e8a5d2eb67af056282f4ff7c90cbd73494 | [
"Apache-2.0"
] | 11 | 2016-03-17T02:34:17.000Z | 2022-01-19T08:10:35.000Z | /************************************************************************************
Filename : GlTexture.cpp
Content : OpenGL texture loading.
Created : September 30, 2013
Authors : John Carmack
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
*************************************************************************************/
// Make sure we get PRIu64
#define __STDC_FORMAT_MACROS 1
#include "GlTexture.h"
#include "OVR_GlUtils.h"
#include "Kernel/OVR_LogUtils.h"
#include "VrApi.h"
#include "stb_image.h"
#include "PackageFiles.h"
#include "OVR_FileSys.h"
//#define OVR_USE_PERF_TIMER
#include "OVR_PerfTimer.h"
#include <algorithm>
#if defined( OVR_OS_ANDROID )
#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0
#define GL_COMPRESSED_RGBA_ASTC_5x4_KHR 0x93B1
#define GL_COMPRESSED_RGBA_ASTC_5x5_KHR 0x93B2
#define GL_COMPRESSED_RGBA_ASTC_6x5_KHR 0x93B3
#define GL_COMPRESSED_RGBA_ASTC_6x6_KHR 0x93B4
#define GL_COMPRESSED_RGBA_ASTC_8x5_KHR 0x93B5
#define GL_COMPRESSED_RGBA_ASTC_8x6_KHR 0x93B6
#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7
#define GL_COMPRESSED_RGBA_ASTC_10x5_KHR 0x93B8
#define GL_COMPRESSED_RGBA_ASTC_10x6_KHR 0x93B9
#define GL_COMPRESSED_RGBA_ASTC_10x8_KHR 0x93BA
#define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB
#define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC
#define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD
#endif
namespace OVR {
// Not declared inline in the header to avoid having to use GL_TEXTURE_2D
GlTexture::GlTexture( const unsigned texture_, const int w, const int h )
: texture( texture_ )
, target( GL_TEXTURE_2D )
, Width( w )
, Height( h )
{
}
static int RoundUpToPow2( int i )
{
if ( i == 0 )
{
return 0;
}
return static_cast<int>( pow( 2, ceil( log( double( i ) ) / log( 2 ) ) ) );
}
static int IntegerLog2( int i )
{
if ( i == 0 )
{
return 0;
}
return static_cast<int>( log( double( i ) ) / log( 2.0 ) );
}
int ComputeFullMipChainNumLevels( const int width, const int height )
{
return IntegerLog2( RoundUpToPow2( std::max( width, height ) ) );
}
static bool IsCompressedFormat( const eTextureFormat format )
{
switch( format )
{
case Texture_None:
case Texture_R:
case Texture_RGB:
case Texture_RGBA:
return false;
case Texture_DXT1:
case Texture_DXT3:
case Texture_DXT5:
case Texture_PVR4bRGB:
case Texture_PVR4bRGBA:
case Texture_ATC_RGB:
case Texture_ATC_RGBA:
case Texture_ETC1:
case Texture_ETC2_RGB:
case Texture_ETC2_RGBA:
case Texture_ASTC_4x4:
case Texture_ASTC_5x4:
case Texture_ASTC_5x5:
case Texture_ASTC_6x5:
case Texture_ASTC_6x6:
case Texture_ASTC_8x5:
case Texture_ASTC_8x6:
case Texture_ASTC_8x8:
case Texture_ASTC_10x5:
case Texture_ASTC_10x6:
case Texture_ASTC_10x8:
case Texture_ASTC_10x10:
case Texture_ASTC_12x10:
case Texture_ASTC_12x12:
case Texture_ASTC_SRGB_4x4:
case Texture_ASTC_SRGB_5x4:
case Texture_ASTC_SRGB_5x5:
case Texture_ASTC_SRGB_6x5:
case Texture_ASTC_SRGB_6x6:
case Texture_ASTC_SRGB_8x5:
case Texture_ASTC_SRGB_8x6:
case Texture_ASTC_SRGB_8x8:
case Texture_ASTC_SRGB_10x5:
case Texture_ASTC_SRGB_10x6:
case Texture_ASTC_SRGB_10x8:
case Texture_ASTC_SRGB_10x10:
case Texture_ASTC_SRGB_12x10:
case Texture_ASTC_SRGB_12x12:
return true;
default:
OVR_ASSERT( false );
return false;
}
}
static int GetASTCIndex( const eTextureFormat format )
{
int const formatType = format & Texture_TypeMask;
int const index = ( formatType - Texture_ASTC_Start ) >> 8;
return index;
}
GLenum GetASTCInternalFormat( eTextureFormat const format )
{
int const NUM_ASTC_FORMATS = ( Texture_ASTC_End - Texture_ASTC_Start ) >> 8;
int const index = GetASTCIndex( format );
GLenum internalFormats[NUM_ASTC_FORMATS] =
{
GL_COMPRESSED_RGBA_ASTC_4x4_KHR,
GL_COMPRESSED_RGBA_ASTC_5x4_KHR,
GL_COMPRESSED_RGBA_ASTC_5x5_KHR,
GL_COMPRESSED_RGBA_ASTC_6x5_KHR,
GL_COMPRESSED_RGBA_ASTC_6x6_KHR,
GL_COMPRESSED_RGBA_ASTC_8x5_KHR,
GL_COMPRESSED_RGBA_ASTC_8x6_KHR,
GL_COMPRESSED_RGBA_ASTC_8x8_KHR,
GL_COMPRESSED_RGBA_ASTC_10x5_KHR,
GL_COMPRESSED_RGBA_ASTC_10x6_KHR,
GL_COMPRESSED_RGBA_ASTC_10x8_KHR,
GL_COMPRESSED_RGBA_ASTC_10x10_KHR,
GL_COMPRESSED_RGBA_ASTC_12x10_KHR,
GL_COMPRESSED_RGBA_ASTC_12x12_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR
};
return internalFormats[index];
}
static int GetASTCTextureSize( const eTextureFormat format, const int w, const int h, const int depth )
{
struct blockDims_t
{
int x;
int y;
int z;
};
int const NUM_ASTC_FORMATS = ( Texture_ASTC_End - Texture_ASTC_Start ) >> 8;
blockDims_t const blockDims[NUM_ASTC_FORMATS] =
{
{ 4, 4, 1 },
{ 5, 4, 1 },
{ 5, 5, 1 },
{ 6, 5, 1 },
{ 6, 6, 1 },
{ 8, 5, 1 },
{ 8, 6, 1 },
{ 8, 8, 1 },
{ 10, 5, 1 },
{ 10, 6, 1 },
{ 10, 8, 1 },
{ 10, 10, 1 },
{ 12, 10, 1 },
{ 12, 12, 1 },
{ 4, 4, 1 },
{ 5, 4, 1 },
{ 5, 5, 1 },
{ 6, 5, 1 },
{ 6, 6, 1 },
{ 8, 5, 1 },
{ 8, 6, 1 },
{ 8, 8, 1 },
{ 10, 5, 1 },
{ 10, 6, 1 },
{ 10, 8, 1 },
{ 10, 10, 1 },
{ 12, 10, 1 },
{ 12, 12, 1 }
};
int const index = GetASTCIndex( format );
blockDims_t const & dims = blockDims[index];
// Compute number of blocks in each direction
int const xblocks = ( w + dims.x - 1 ) / dims.x;
int const yblocks = ( h + dims.y - 1 ) / dims.y;
int const zblocks = ( depth + dims.z - 1 ) / dims.z;
// Each block is encoded on 16 bytes, so calculate total compressed image data size.
int const numBytes = xblocks * yblocks * zblocks * 16;
return numBytes;
}
static int32_t GetOvrTextureSize( const eTextureFormat format, const int w, const int h )
{
switch ( format & Texture_TypeMask )
{
case Texture_R: return w*h;
case Texture_RGB: return w*h*3;
case Texture_RGBA: return w*h*4;
case Texture_ATC_RGB:
case Texture_ETC1:
case Texture_ETC2_RGB:
case Texture_DXT1:
{
int bw = (w+3)/4, bh = (h+3)/4;
return bw * bh * 8;
}
case Texture_ATC_RGBA:
case Texture_ETC2_RGBA:
case Texture_DXT3:
case Texture_DXT5:
{
int bw = (w+3)/4, bh = (h+3)/4;
return bw * bh * 16;
}
case Texture_PVR4bRGB:
case Texture_PVR4bRGBA:
{
unsigned int width = (unsigned int)w;
unsigned int height = (unsigned int)h;
unsigned int min_width = 8;
unsigned int min_height = 8;
// pad the dimensions
width = width + ((-1*width) % min_width);
height = height + ((-1*height) % min_height);
unsigned int depth = 1;
unsigned int bpp = 4;
unsigned int bits = bpp * width * height * depth;
return (int)(bits / 8);
}
case Texture_ASTC_4x4:
case Texture_ASTC_5x4:
case Texture_ASTC_5x5:
case Texture_ASTC_6x5:
case Texture_ASTC_6x6:
case Texture_ASTC_8x5:
case Texture_ASTC_8x6:
case Texture_ASTC_8x8:
case Texture_ASTC_10x5:
case Texture_ASTC_10x6:
case Texture_ASTC_10x8:
case Texture_ASTC_10x10:
case Texture_ASTC_12x10:
case Texture_ASTC_12x12:
case Texture_ASTC_SRGB_4x4:
case Texture_ASTC_SRGB_5x4:
case Texture_ASTC_SRGB_5x5:
case Texture_ASTC_SRGB_6x5:
case Texture_ASTC_SRGB_6x6:
case Texture_ASTC_SRGB_8x5:
case Texture_ASTC_SRGB_8x6:
case Texture_ASTC_SRGB_8x8:
case Texture_ASTC_SRGB_10x5:
case Texture_ASTC_SRGB_10x6:
case Texture_ASTC_SRGB_10x8:
case Texture_ASTC_SRGB_10x10:
case Texture_ASTC_SRGB_12x10:
case Texture_ASTC_SRGB_12x12:
{
return GetASTCTextureSize( format, w, h, 1 );
}
default:
{
OVR_ASSERT( false );
break;
}
}
return 0;
}
static GlTexture CreateGlTexture( const char * fileName, const eTextureFormat format, const int width, const int height,
const void * data, const size_t dataSize,
const int mipcount, const bool useSrgbFormat, const bool imageSizeStored )
{
#if defined( OVR_USE_PERF_TIMER )
LOG( "Loading '%s', w = %i, h = %i, mipcount = %i", fileName, width, height, mipcount );
#endif
GL_CheckErrors( "pre-CreateGlTexture" );
OVR_PERF_TIMER( CreateGlTexture );
// LOG( "CreateGLTexture(): format %s", NameForTextureFormat( static_cast< TextureFormat >( format ) ) );
GLenum glFormat;
GLenum glInternalFormat;
if ( !TextureFormatToGlFormat( format, useSrgbFormat, glFormat, glInternalFormat ) )
{
return GlTexture( 0, 0, 0 );
}
if ( mipcount <= 0 )
{
LOG( "%s: Invalid mip count %d", fileName, mipcount );
return GlTexture( 0, 0, 0 );
}
// larger than this would require mipSize below to be a larger type
if ( width <= 0 || width > 32768 || height <= 0 || height > 32768 )
{
LOG( "%s: Invalid texture size (%dx%d)", fileName, width, height );
return GlTexture( 0, 0, 0 );
}
GLuint texId;
glGenTextures( 1, &texId );
glBindTexture( GL_TEXTURE_2D, texId );
const unsigned char * level = (const unsigned char*)data;
const unsigned char * endOfBuffer = level + dataSize;
int w = width;
int h = height;
for ( int i = 0; i < mipcount; i++ )
{
int32_t mipSize = GetOvrTextureSize( format, w, h );
if ( imageSizeStored )
{
mipSize = static_cast<int32_t>( *(const size_t *)level );
level += 4;
if ( level > endOfBuffer )
{
LOG( "%s: Image data exceeds buffer size", fileName );
glBindTexture( GL_TEXTURE_2D, 0 );
return GlTexture( texId, GL_TEXTURE_2D, width, height );
}
}
if ( mipSize <= 0 || mipSize > endOfBuffer - level )
{
LOG( "%s: Mip level %d exceeds buffer size (%d > %td)", fileName, i, mipSize, ptrdiff_t( endOfBuffer - level ) );
glBindTexture( GL_TEXTURE_2D, 0 );
return GlTexture( texId, GL_TEXTURE_2D, width, height );
}
if ( IsCompressedFormat( format ) )
{
OVR_PERF_TIMER( CreateGlTexture_CompressedTexImage2D );
glCompressedTexImage2D( GL_TEXTURE_2D, i, glInternalFormat, w, h, 0, mipSize, level );
GL_CheckErrors( "Texture_Compressed" );
}
else
{
OVR_PERF_TIMER( CreateGlTexture_TexImage2D );
glTexImage2D( GL_TEXTURE_2D, i, glInternalFormat, w, h, 0, glFormat, GL_UNSIGNED_BYTE, level );
}
level += mipSize;
if ( imageSizeStored )
{
level += 3 - ( ( mipSize + 3 ) % 4 );
if ( level > endOfBuffer )
{
LOG( "%s: Image data exceeds buffer size", fileName );
glBindTexture( GL_TEXTURE_2D, 0 );
return GlTexture( texId, GL_TEXTURE_2D, width, height );
}
}
w >>= 1;
h >>= 1;
if ( w < 1 ) { w = 1; }
if ( h < 1 ) { h = 1; }
}
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
// Surfaces look pretty terrible without trilinear filtering
if ( mipcount <= 1 )
{
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
}
else
{
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
}
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
GL_CheckErrors( "Texture load" );
glBindTexture( GL_TEXTURE_2D, 0 );
return GlTexture( texId, GL_TEXTURE_2D, width, height );
}
static GlTexture CreateGlCubeTexture( const char * fileName, const eTextureFormat format, const int width, const int height,
const void * data, const size_t dataSize,
const int mipcount, const bool useSrgbFormat, const bool imageSizeStored )
{
OVR_ASSERT( width == height );
GL_CheckErrors("Pre Cube Texture load");
if ( mipcount <= 0 )
{
LOG( "%s: Invalid mip count %d", fileName, mipcount );
return GlTexture( 0, 0, 0 );
}
// larger than this would require mipSize below to be a larger type
if ( width <= 0 || width > 32768 || height <= 0 || height > 32768 )
{
LOG( "%s: Invalid texture size (%dx%d)", fileName, width, height );
return GlTexture( 0, 0, 0 );
}
GLenum glFormat;
GLenum glInternalFormat;
if ( !TextureFormatToGlFormat( format, useSrgbFormat, glFormat, glInternalFormat ) )
{
LOG( "%s: TextureFormatToGlFormat 0x%x %s failed", fileName, (int)format, useSrgbFormat ? "true" : "false");
return GlTexture( 0, 0, 0 );
}
GLuint texId;
glGenTextures( 1, &texId );
glBindTexture( GL_TEXTURE_CUBE_MAP, texId );
const unsigned char * level = (const unsigned char*)data;
const unsigned char * endOfBuffer = level + dataSize;
for ( int i = 0; i < mipcount; i++ )
{
const int w = width >> i;
int32_t mipSize = GetOvrTextureSize( format, w, w );
if ( imageSizeStored )
{
mipSize = static_cast<int32_t>( *(const size_t *)level );
level += 4;
if ( level > endOfBuffer )
{
LOG( "%s: Image data exceeds buffer size: %p > %p", fileName, level, endOfBuffer );
glBindTexture( GL_TEXTURE_CUBE_MAP, 0 );
return GlTexture( texId, GL_TEXTURE_CUBE_MAP, width, height );
}
}
for ( int side = 0; side < 6; side++ )
{
if ( mipSize <= 0 || mipSize > endOfBuffer - level )
{
LOG( "%s: Mip level %d exceeds buffer size (%u > %td)", fileName, i, mipSize, ptrdiff_t( endOfBuffer - level ) );
glBindTexture( GL_TEXTURE_CUBE_MAP, 0 );
return GlTexture( texId, GL_TEXTURE_CUBE_MAP, width, height );
}
if ( IsCompressedFormat( format ) )
{
glCompressedTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X + side, i, glInternalFormat, w, w, 0, mipSize, level );
}
else
{
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X + side, i, glInternalFormat, w, w, 0, glFormat, GL_UNSIGNED_BYTE, level );
}
level += mipSize;
if ( imageSizeStored )
{
level += 3 - ( ( mipSize + 3 ) % 4 );
if ( level > endOfBuffer )
{
LOG( "%s: Image data exceeds buffer size", fileName );
glBindTexture( GL_TEXTURE_CUBE_MAP, 0 );
return GlTexture( texId, GL_TEXTURE_CUBE_MAP, width, height );
}
}
}
}
// Surfaces look pretty terrible without trilinear filtering
if ( mipcount <= 1 )
{
glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
}
else
{
glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
}
glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
GL_CheckErrors( "Cube Texture load" );
glBindTexture( GL_TEXTURE_CUBE_MAP, 0 );
return GlTexture( texId, GL_TEXTURE_CUBE_MAP, width, height );
}
GlTexture LoadRGBATextureFromMemory( const uint8_t * texture, const int width, const int height, const bool useSrgbFormat )
{
const size_t dataSize = GetOvrTextureSize( Texture_RGBA, width, height );
return CreateGlTexture( "memory-RGBA", Texture_RGBA, width, height, texture, dataSize, 1, useSrgbFormat, false );
}
GlTexture LoadRGBACubeTextureFromMemory( const uint8_t * texture, const int dim, const bool useSrgbFormat )
{
const size_t dataSize = GetOvrTextureSize( Texture_RGBA, dim, dim ) * 6;
return CreateGlCubeTexture( "memory-CubeRGBA", Texture_RGBA, dim, dim, texture, dataSize, 1, useSrgbFormat, false );
}
GlTexture LoadRGBTextureFromMemory( const uint8_t * texture, const int width, const int height, const bool useSrgbFormat )
{
const size_t dataSize = GetOvrTextureSize( Texture_RGB, width, height );
return CreateGlTexture( "memory-RGB", Texture_RGB, width, height, texture, dataSize, 1, useSrgbFormat, false );
}
GlTexture LoadRTextureFromMemory( const uint8_t * texture, const int width, const int height )
{
const size_t dataSize = GetOvrTextureSize( Texture_R, width, height );
return CreateGlTexture( "memory-R", Texture_R, width, height, texture, dataSize, 1, false, false );
}
// .astc files are created by the reference Mali compression tool.
// As of 9/17/2016, it appears to automatically flip y, which is a good
// reason to avoid it.
struct astcHeader
{
unsigned char magic[4];
unsigned char blockDim_x;
unsigned char blockDim_y;
unsigned char blockDim_z;
unsigned char xsize[3];
unsigned char ysize[3];
unsigned char zsize[3];
};
GlTexture LoadASTCTextureFromMemory( uint8_t const * buffer, const size_t bufferSize, const int numPlanes, const bool useSrgbFormat )
{
astcHeader const * header = reinterpret_cast< astcHeader const * >( buffer );
int const w = ( (int)header->xsize[2] << 16 ) | ( (int)header->xsize[1] << 8 ) | ( (int)header->xsize[0] );
int const h = ( (int)header->ysize[2] << 16 ) | ( (int)header->ysize[1] << 8 ) | ( (int)header->ysize[0] );
OVR_ASSERT( numPlanes == 1 || numPlanes == 4 );
OVR_UNUSED( numPlanes );
if ( header->blockDim_z != 1 )
{
OVR_ASSERT( header->blockDim_z == 1 );
LOG( "Only 2D ASTC textures are supported" );
return GlTexture();
}
eTextureFormat format = Texture_None;
if ( header->blockDim_x == 4 )
{
if ( header->blockDim_y == 4 )
{
format = Texture_ASTC_4x4;
}
}
else if ( header->blockDim_x == 5 )
{
if ( header->blockDim_y == 4 )
{
format = Texture_ASTC_5x4;
}
else if ( header->blockDim_y == 5 )
{
format = Texture_ASTC_5x5;
}
}
else if ( header->blockDim_x == 6 )
{
if ( header->blockDim_y == 5 )
{
format = Texture_ASTC_6x5;
}
else if ( header->blockDim_y == 6 )
{
format = Texture_ASTC_6x6;
}
}
else if ( header->blockDim_x == 8 )
{
if ( header->blockDim_y == 5 )
{
format = Texture_ASTC_8x5;
}
else if ( header->blockDim_y == 6 )
{
format = Texture_ASTC_8x6;
}
else if ( header->blockDim_y == 8 )
{
format = Texture_ASTC_8x8;
}
}
else if ( header->blockDim_x == 10 )
{
if ( header->blockDim_y == 5 )
{
format = Texture_ASTC_10x5;
}
else if ( header->blockDim_y == 6 )
{
format = Texture_ASTC_10x6;
}
else if ( header->blockDim_y == 8 )
{
format = Texture_ASTC_10x8;
}
else if ( header->blockDim_y == 10 )
{
format = Texture_ASTC_10x10;
}
}
else if ( header->blockDim_x == 12 )
{
if ( header->blockDim_y == 10 )
{
format = Texture_ASTC_12x10;
}
else if ( header->blockDim_y == 12 )
{
format = Texture_ASTC_12x12;
}
}
if ( format == Texture_None )
{
OVR_ASSERT( format != Texture_None );
LOG( "Unhandled ASTC block size: %i x %i", header->blockDim_x, header->blockDim_y );
return GlTexture();
}
return CreateGlTexture("memory-ASTC", format, w, h, buffer + sizeof(struct astcHeader),
bufferSize - sizeof(struct astcHeader), 1, useSrgbFormat, false);
}
/*
PVR Container Format
Offset Size Name Description
0x0000 4 [DWORD] Version 0x03525650
0x0004 4 [DWORD] Flags 0x0000 if no flags set
0x0002 if colors within the texture
0x0008 8 [Union] Pixel Format This can either be one of several predetermined enumerated
values (a DWORD) or a 4-character array and a 4-byte array (8 bytes).
If the most significant 4 bytes of the 64-bit (8-byte) value are all zero,
then it indicates that it is the enumeration with the following values:
Value Pixel Type
0 PVRTC 2bpp RGB
1 PVRTC 2bpp RGBA
2 PVRTC 4bpp RGB
3 PVRTC 4bpp RGBA
4 PVRTC-II 2bpp
5 PVRTC-II 4bpp
6 ETC1
7 DXT1 / BC1
8 DXT2
9 DXT3 / BC2
10 DXT4
11 DXT5 / BC3
12 BC4
13 BC5
14 BC6
15 BC7
16 UYVY
17 YUY2
18 BW1bpp
19 R9G9B9E5 Shared Exponent
20 RGBG8888
21 GRGB8888
22 ETC2 RGB
23 ETC2 RGBA
24 ETC2 RGB A1
25 EAC R11 Unsigned
26 EAC R11 Signed
27 EAC RG11 Unsigned
28 EAC RG11 Signed
If the most significant 4 bytes are not zero then the 8-byte character array
indicates the pixel format as follows:
The least significant 4 bytes indicate channel order, such as:
{ 'b', 'g', 'r', 'a' } or { 'b', 'g', 'r', '\0' }
The most significant 4 bytes indicate the width of each channel in bits, as follows:
{ 4, 4, 4, 4 } or { 2, 2, 2, 2 }, or {5, 5, 5, 0 }
0x0010 4 [DWORD] Color Space This is an enumerated field, currently two values:
Value Color Space
0 Linear RGB
1 Standard RGB
0x0014 4 [DWORD] Channel Type This is another enumerated field:
Value Data Type
0 Unsigned Byte Normalized
1 Signed Byte Normalized
2 Unsigned Byte
3 Signed Byte
4 Unsigned Short Normalized
5 Signed Short Normalized
6 Unsigned Short
7 Signed Short
8 Unsigned Integer Normalized
9 Signed Integer Normalized
10 Unsigned Integer
11 Signed Integer
12 Float (no size specified)
0x0018 4 [DWORD] Height Height of the image.
0x001C 4 [DWORD] Width Width of the image.
0x0020 4 [DWORD] Depth Depth of the image, in pixels.
0x0024 4 [DWORD] Surface Count The number of surfaces to this texture, used for texture arrays.
0x0028 4 [DWORD] Face Count The number of faces to this texture, used for cube maps.
0x002C 4 [DWORD] MIP-Map Count The number of MIP-Map levels, including a top level.
0x0030 4 [DWORD] Metadata Size The size, in bytes, of meta data that immediately follows this header.
*/
#pragma pack(1)
struct OVR_PVR_HEADER
{
UInt32 Version;
UInt32 Flags;
UInt64 PixelFormat;
UInt32 ColorSpace;
UInt32 ChannelType;
UInt32 Height;
UInt32 Width;
UInt32 Depth;
UInt32 NumSurfaces;
UInt32 NumFaces;
UInt32 MipMapCount;
UInt32 MetaDataSize;
};
#pragma pack()
GlTexture LoadTexturePVR( const char * fileName, const unsigned char * buffer, const int bufferLength,
bool useSrgbFormat, bool noMipMaps, int & width, int & height )
{
width = 0;
height = 0;
if ( bufferLength < ( int )( sizeof( OVR_PVR_HEADER ) ) )
{
LOG( "%s: Invalid PVR file", fileName );
return GlTexture( 0, 0, 0 );
}
const OVR_PVR_HEADER & header = *( OVR_PVR_HEADER * )buffer;
if ( header.Version != 0x03525650 )
{
LOG( "%s: Invalid PVR file version", fileName );
return GlTexture( 0, 0, 0 );
}
eTextureFormat format = Texture_None;
switch ( header.PixelFormat )
{
case 2: format = Texture_PVR4bRGB; break;
case 3: format = Texture_PVR4bRGBA; break;
case 6: format = Texture_ETC1; break;
case 22: format = Texture_ETC2_RGB; break;
case 23: format = Texture_ETC2_RGBA; break;
case 578721384203708274llu: format = Texture_RGBA; break;
default:
LOG( "%s: Unknown PVR texture format %" PRIu64 ", size %ix%i", fileName, header.PixelFormat, width, height );
return GlTexture( 0, 0, 0 );
}
// skip the metadata
const UInt32 startTex = sizeof( OVR_PVR_HEADER ) + header.MetaDataSize;
if ( ( startTex < sizeof( OVR_PVR_HEADER ) ) || ( startTex >= static_cast< size_t >( bufferLength ) ) )
{
LOG( "%s: Invalid PVR header sizes", fileName );
return GlTexture( 0, 0, 0 );
}
const UInt32 mipCount = ( noMipMaps ) ? 1 : OVR::Alg::Max( static_cast<UInt32>( 1u ), header.MipMapCount );
width = header.Width;
height = header.Height;
if ( header.NumFaces == 1 )
{
return CreateGlTexture( fileName, format, width, height, buffer + startTex, bufferLength - startTex, mipCount, useSrgbFormat, false );
}
else if ( header.NumFaces == 6 )
{
return CreateGlCubeTexture( fileName, format, width, height, buffer + startTex, bufferLength - startTex, mipCount, useSrgbFormat, false );
}
else
{
LOG( "%s: PVR file has unsupported number of faces %d", fileName, header.NumFaces );
}
width = 0;
height = 0;
return GlTexture( 0, 0, 0 );
}
unsigned char * LoadPVRBuffer( const char * fileName, int & width, int & height )
{
width = 0;
height = 0;
MemBufferFile bufferFile( fileName );
MemBuffer buffer = bufferFile.ToMemBuffer();
if ( buffer.Length < ( int )( sizeof( OVR_PVR_HEADER ) ) )
{
LOG( "Invalid PVR file" );
buffer.FreeData();
return NULL;
}
const OVR_PVR_HEADER & header = *( OVR_PVR_HEADER * )buffer.Buffer;
if ( header.Version != 0x03525650 )
{
LOG( "Invalid PVR file version" );
buffer.FreeData();
return NULL;
}
eTextureFormat format = Texture_None;
switch ( header.PixelFormat )
{
case 578721384203708274llu: format = Texture_RGBA; break;
default:
LOG( "Unknown PVR texture format %" PRIu64 ", size %ix%i", header.PixelFormat, width, height );
buffer.FreeData();
return NULL;
}
// skip the metadata
const UInt32 startTex = sizeof( OVR_PVR_HEADER ) + header.MetaDataSize;
if ( ( startTex < sizeof( OVR_PVR_HEADER ) ) || ( startTex >= static_cast< size_t >( buffer.Length ) ) )
{
LOG( "Invalid PVR header sizes" );
buffer.FreeData();
return NULL;
}
size_t mipSize = GetOvrTextureSize( format, header.Width, header.Height );
const int outBufferSizeBytes = buffer.Length - startTex;
if ( outBufferSizeBytes < 0 || mipSize > static_cast< size_t >( outBufferSizeBytes ) )
{
buffer.FreeData();
return NULL;
}
width = header.Width;
height = header.Height;
// skip the metadata
unsigned char * outBuffer = ( unsigned char * )malloc( outBufferSizeBytes );
memcpy( outBuffer, ( unsigned char * )buffer.Buffer + startTex, outBufferSizeBytes );
buffer.FreeData();
return outBuffer;
}
/*
KTX Container Format
KTX is a format for storing textures for OpenGL and OpenGL ES applications.
It is distinguished by the simplicity of the loader required to instantiate
a GL texture object from the file contents.
Byte[12] identifier
UInt32 endianness
UInt32 glType
UInt32 glTypeSize
UInt32 glFormat
Uint32 glInternalFormat
Uint32 glBaseInternalFormat
UInt32 pixelWidth
UInt32 pixelHeight
UInt32 pixelDepth
UInt32 numberOfArrayElements
UInt32 numberOfFaces
UInt32 numberOfMipmapLevels
UInt32 bytesOfKeyValueData
for each keyValuePair that fits in bytesOfKeyValueData
UInt32 keyAndValueByteSize
Byte keyAndValue[keyAndValueByteSize]
Byte valuePadding[3 - ((keyAndValueByteSize + 3) % 4)]
end
for each mipmap_level in numberOfMipmapLevels*
UInt32 imageSize;
for each array_element in numberOfArrayElements*
for each face in numberOfFaces
for each z_slice in pixelDepth*
for each row or row_of_blocks in pixelHeight*
for each pixel or block_of_pixels in pixelWidth
Byte data[format-specific-number-of-bytes]**
end
end
end
Byte cubePadding[0-3]
end
end
Byte mipPadding[3 - ((imageSize + 3) % 4)]
end
*/
#pragma pack(1)
struct OVR_KTX_HEADER
{
UByte identifier[12];
UInt32 endianness;
UInt32 glType;
UInt32 glTypeSize;
UInt32 glFormat;
UInt32 glInternalFormat;
UInt32 glBaseInternalFormat;
UInt32 pixelWidth;
UInt32 pixelHeight;
UInt32 pixelDepth;
UInt32 numberOfArrayElements;
UInt32 numberOfFaces;
UInt32 numberOfMipmapLevels;
UInt32 bytesOfKeyValueData;
};
#pragma pack()
GlTexture LoadTextureKTX( const char * fileName, const unsigned char * buffer, const int bufferLength,
bool useSrgbFormat, bool noMipMaps, int & width, int & height )
{
width = 0;
height = 0;
if ( bufferLength < (int)( sizeof( OVR_KTX_HEADER ) ) )
{
LOG( "%s: Invalid KTX file", fileName );
return GlTexture( 0, 0, 0 );
}
const char fileIdentifier[12] =
{
'\xAB', 'K', 'T', 'X', ' ', '1', '1', '\xBB', '\r', '\n', '\x1A', '\n'
};
const OVR_KTX_HEADER & header = *(OVR_KTX_HEADER *)buffer;
if ( memcmp( header.identifier, fileIdentifier, sizeof( fileIdentifier ) ) != 0 )
{
LOG( "%s: Invalid KTX file", fileName );
return GlTexture( 0, 0, 0 );
}
// only support little endian
if ( header.endianness != 0x04030201 )
{
LOG( "%s: KTX file has wrong endianess", fileName );
return GlTexture( 0, 0, 0 );
}
// only support compressed or unsigned byte
if ( header.glType != 0 && header.glType != GL_UNSIGNED_BYTE )
{
LOG( "%s: KTX file has unsupported glType %d", fileName, header.glType );
return GlTexture( 0, 0, 0 );
}
// no support for texture arrays
if ( header.numberOfArrayElements != 0 )
{
LOG( "%s: KTX file has unsupported number of array elements %d", fileName, header.numberOfArrayElements );
return GlTexture( 0, 0, 0 );
}
// derive the texture format from the GL format
eTextureFormat format = Texture_None;
if ( !GlFormatToTextureFormat( format, header.glFormat, header.glInternalFormat ) )
{
LOG( "%s: KTX file has unsupported glFormat %d, glInternalFormat %d", fileName, header.glFormat, header.glInternalFormat );
return GlTexture( 0, 0, 0 );
}
// skip the key value data
const uintptr_t startTex = sizeof( OVR_KTX_HEADER ) + header.bytesOfKeyValueData;
if ( ( startTex < sizeof( OVR_KTX_HEADER ) ) || ( startTex >= static_cast< size_t >( bufferLength ) ) )
{
LOG( "%s: Invalid KTX header sizes", fileName );
return GlTexture( 0, 0, 0 );
}
width = header.pixelWidth;
height = header.pixelHeight;
const UInt32 mipCount = ( noMipMaps ) ? 1 : OVR::Alg::Max( static_cast<UInt32>( 1u ), header.numberOfMipmapLevels );
if ( header.numberOfFaces == 1 )
{
return CreateGlTexture( fileName, format, width, height, buffer + startTex, bufferLength - startTex, mipCount, useSrgbFormat, true );
}
else if ( header.numberOfFaces == 6 )
{
return CreateGlCubeTexture( fileName, format, width, height, buffer + startTex, bufferLength - startTex, mipCount, useSrgbFormat, true );
}
else
{
LOG( "%s: KTX file has unsupported number of faces %d", fileName, header.numberOfFaces );
}
width = 0;
height = 0;
return GlTexture( 0, 0, 0 );
}
unsigned char * LoadImageToRGBABuffer( const char * fileName, const unsigned char * inBuffer, const size_t inBufferLen,
int & width, int & height )
{
const String ext = String( fileName ).GetExtension().ToLower();
width = 0;
height = 0;
if ( ext == ".jpg" || ext == ".tga" ||
ext == ".png" || ext == ".bmp" ||
ext == ".psd" || ext == ".gif" ||
ext == ".hdr" || ext == ".pic" )
{
// Uncompressed files loaded by stb_image
int comp;
stbi_uc * image = stbi_load_from_memory( (unsigned char *)inBuffer, (int)inBufferLen, &width, &height, &comp, 4 );
return image;
}
return nullptr;
}
void FreeRGBABuffer( const unsigned char * buffer )
{
stbi_image_free( (void*)buffer );
}
static int MipLevelsForSize( int width, int height )
{
int levels = 1;
while ( width > 1 || height > 1 )
{
levels++;
width >>= 1;
height >>= 1;
}
return levels;
}
GlTexture LoadTextureFromBuffer( const char * fileName, const MemBuffer & buffer,
const TextureFlags_t & flags, int & width, int & height )
{
const String ext = String( fileName ).GetExtension().ToLower();
// LOG( "Loading texture buffer %s (%s), length %i", fileName, ext.ToCStr(), buffer.Length );
GlTexture texId;
width = 0;
height = 0;
if ( fileName == NULL || buffer.Buffer == NULL || buffer.Length < 1 )
{
// can't load anything from an empty buffer
}
else if ( ext == ".jpg" || ext == ".tga" ||
ext == ".png" || ext == ".bmp" ||
ext == ".psd" || ext == ".gif" ||
ext == ".hdr" || ext == ".pic" )
{
// Uncompressed files loaded by stb_image
int comp;
stbi_uc * image = stbi_load_from_memory( (unsigned char *)buffer.Buffer, buffer.Length, &width, &height, &comp, 4 );
if ( image != NULL )
{
// Optionally outline the border alpha.
if ( flags & TEXTUREFLAG_ALPHA_BORDER )
{
for ( int i = 0 ; i < width ; i++ )
{
image[i*4+3] = 0;
image[((height-1)*width+i)*4+3] = 0;
}
for ( int i = 0 ; i < height ; i++ )
{
image[i*width*4+3] = 0;
image[(i*width+width-1)*4+3] = 0;
}
}
const size_t dataSize = GetOvrTextureSize( Texture_RGBA, width, height );
texId = CreateGlTexture( fileName, Texture_RGBA, width, height, image, dataSize,
( flags & TEXTUREFLAG_NO_MIPMAPS ) ? 1 : MipLevelsForSize( width, height ),
flags & TEXTUREFLAG_USE_SRGB, false );
free( image );
if ( !( flags & TEXTUREFLAG_NO_MIPMAPS ) )
{
glBindTexture( texId.target, texId.texture );
glGenerateMipmap( texId.target );
glTexParameteri( texId.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
}
}
else
{
LOG( "stbi_load_from_memory() failed!" );
}
}
else if ( ext == ".pvr" )
{
texId = LoadTexturePVR( fileName, (const unsigned char *)buffer.Buffer, buffer.Length,
( flags & TEXTUREFLAG_USE_SRGB ),
( flags & TEXTUREFLAG_NO_MIPMAPS ),
width, height );
}
else if ( ext == ".ktx" )
{
texId = LoadTextureKTX( fileName, (const unsigned char *)buffer.Buffer, buffer.Length,
( flags & TEXTUREFLAG_USE_SRGB ),
( flags & TEXTUREFLAG_NO_MIPMAPS ),
width, height );
}
else if ( ext == ".astc" )
{
texId = LoadASTCTextureFromMemory( (const unsigned char*)buffer.Buffer, buffer.Length, 4, flags & TEXTUREFLAG_USE_SRGB );
}
else if ( ext == ".pkm" )
{
LOG( "PKM format not supported" );
}
else
{
LOG( "unsupported file extension '%s', for file '%s'", ext.ToCStr(), fileName );
}
// Create a default texture if the load failed
if ( texId.texture == 0 )
{
WARN( "Failed to load %s", fileName );
if ( ( flags & TEXTUREFLAG_NO_DEFAULT ) == 0 )
{
static uint8_t defaultTexture[8 * 8 * 3] =
{
255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255,
255,255,255, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 255,255,255,
255,255,255, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 255,255,255,
255,255,255, 64, 64, 64, 64, 64, 64, 255,255,255, 255,255,255, 64, 64, 64, 64, 64, 64, 255,255,255,
255,255,255, 64, 64, 64, 64, 64, 64, 255,255,255, 255,255,255, 64, 64, 64, 64, 64, 64, 255,255,255,
255,255,255, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 255,255,255,
255,255,255, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 255,255,255,
255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255
};
texId = LoadRGBTextureFromMemory( defaultTexture, 8, 8, flags & TEXTUREFLAG_USE_SRGB );
}
}
return texId;
}
GlTexture LoadTextureFromOtherApplicationPackage( void * zipFile, const char * nameInZip,
const TextureFlags_t & flags, int & width, int & height )
{
width = 0;
height = 0;
if ( zipFile == 0 )
{
return GlTexture( 0, 0, 0 );
}
void * buffer;
int bufferLength;
ovr_ReadFileFromOtherApplicationPackage( zipFile, nameInZip, bufferLength, buffer );
if ( !buffer )
{
return GlTexture( 0, 0, 0 );
}
GlTexture texId = LoadTextureFromBuffer( nameInZip, MemBuffer( buffer, bufferLength ),
flags, width, height );
free( buffer );
return texId;
}
GlTexture LoadTextureFromApplicationPackage( const char * nameInZip,
const TextureFlags_t & flags, int & width, int & height )
{
return LoadTextureFromOtherApplicationPackage( ovr_GetApplicationPackageFile(), nameInZip, flags, width, height );
}
GlTexture LoadTextureFromUri( class ovrFileSys & fileSys, const char * uri,
const TextureFlags_t & flags, int & width, int & height )
{
MemBufferT< uint8_t > buffer;
if ( !fileSys.ReadFile( uri, buffer ) )
{
return GlTexture();
}
return LoadTextureFromBuffer( uri, MemBuffer( buffer, static_cast< int >( buffer.GetSize() ) ),
flags, width, height );
}
void FreeTexture( GlTexture texId )
{
if ( texId.texture )
{
glDeleteTextures( 1, &texId.texture );
}
}
void DeleteTexture( GlTexture & texture )
{
if ( texture.texture != 0 )
{
glDeleteTextures( 1, &texture.texture );
texture.texture = 0;
texture.target = 0;
texture.Width = 0;
texture.Height = 0;
}
}
void MakeTextureClamped( GlTexture texId )
{
glBindTexture( texId.target, texId.texture );
glTexParameteri( texId.target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( texId.target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glBindTexture( texId.target, 0 );
}
void MakeTextureLodClamped( GlTexture texId, int maxLod )
{
glBindTexture( texId.target, texId.texture );
glTexParameteri( texId.target, GL_TEXTURE_MAX_LEVEL, maxLod );
glBindTexture( texId.target, 0 );
}
void MakeTextureTrilinear( GlTexture texId )
{
glBindTexture( texId.target, texId.texture );
glTexParameteri( texId.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
glTexParameteri( texId.target, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glBindTexture( texId.target, 0 );
}
void MakeTextureLinearNearest( GlTexture texId )
{
glBindTexture( texId.target, texId.texture );
glTexParameteri( texId.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
glTexParameteri( texId.target, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glBindTexture( texId.target, 0 );
}
void MakeTextureLinear( GlTexture texId )
{
glBindTexture( texId.target, texId.texture );
glTexParameteri( texId.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( texId.target, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glBindTexture( texId.target, 0 );
}
void MakeTextureAniso( GlTexture texId, float maxAniso )
{
glBindTexture( texId.target, texId.texture );
glTexParameterf( texId.target, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAniso );
glBindTexture( texId.target, 0 );
}
void BuildTextureMipmaps( GlTexture texId )
{
glBindTexture( texId.target, texId.texture );
glGenerateMipmap( texId.target );
glBindTexture( texId.target, 0 );
}
} // namespace OVR
| 30.357626 | 140 | 0.647528 | [
"object"
] |
9116f174e5235727cbce82094d8bdce2db84e748 | 2,311 | cpp | C++ | generator/generator.cpp | Rheel17/glwr | 163857d937698ed65b99af3b7e1fcfd34f932c68 | [
"MIT"
] | 1 | 2020-06-17T22:11:35.000Z | 2020-06-17T22:11:35.000Z | generator/generator.cpp | Rheel17/glwr | 163857d937698ed65b99af3b7e1fcfd34f932c68 | [
"MIT"
] | null | null | null | generator/generator.cpp | Rheel17/glwr | 163857d937698ed65b99af3b7e1fcfd34f932c68 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020 Levi van Rheenen
*/
#include <ctre.hpp>
#include <cstring>
#include <fstream>
#include "Refpage.h"
constexpr static auto glfwHeaderHead = R"(#ifndef OPENGL_GLWR_H_
#define OPENGL_GLWR_H_
#include <GL/glew.h>
#if defined(__GNUC__) || defined(__clang__)
#define GLWR_INLINE __attribute__((always_inline)) inline
#elif defined(_MSC_VER)
#define GLWR_INLINE __forceinline
#else
#define GLWR_INLINE inline
#endif
using DEBUGPROC = GLDEBUGPROC;
)";
constexpr static auto glfwHeaderTail = R"(
#endif
)";
std::vector<std::string> getFunctionFiles(const std::filesystem::path& dir) {
std::vector<std::string> functionFiles;
for (const auto& p : std::filesystem::directory_iterator(dir)) {
std::string filename = p.path().filename().string();
if (ctre::match<"gl[A-Z]\\w*\\.xml">(filename)) {
functionFiles.push_back(std::move(filename));
}
}
// on some systems the directory_iterator doesn't sort by name, so do it
// manually here.
std::sort(functionFiles.begin(), functionFiles.end());
return functionFiles;
}
void writeGlwrHeader(const std::filesystem::path& path, const std::vector<std::string>& declarationNames) {
std::ofstream file(path.string());
file << glfwHeaderHead;
for (const auto& declarationName : declarationNames) {
file << "#include \"func/" << declarationName << ".h\"" << std::endl;
}
file << glfwHeaderTail;
}
int main(int argc, char* argv[]) {
if (argc != 4) {
return -1;
}
auto gl4 = std::filesystem::current_path() / "opengl-refpages" / "gl4";
auto dir = std::filesystem::path(argv[1]);
include.Parse(argv[2]);
verbose = std::strcmp(argv[3], "ON") == 0;
std::vector<std::string> functions = getFunctionFiles(gl4);
std::vector<std::string> declarationNames;
for (const auto& function : functions) {
std::string name(function.begin(), function.end() - 4);
declarationNames.push_back(name);
if (verbose) {
std::cout << "Generating " << name << ".h" << std::endl;
}
std::ifstream file(gl4 / function, std::ios::binary);
Refpage refpage(gl4, file, name);
std::filesystem::path functionHeaderPath = dir / "func" / (name + ".h");
std::ofstream functionHeader(functionHeaderPath.string());
refpage.GenerateHeader(functionHeader);
}
writeGlwrHeader(dir / "glwr.h", declarationNames);
return 0;
}
| 24.849462 | 107 | 0.692341 | [
"vector"
] |
912cc8ba51e629cd1f23411c1168695879d30f48 | 295,217 | cpp | C++ | NLEigenSolver/vendor/Blaze/blazetest/src/mathtest/views/rows/DenseGeneralTest1.cpp | capnrenan/NLEigenJacobiDavidsonModified | 91bc61f868bb2cf9dd42931fdeb4e33903e3369c | [
"MIT"
] | 3 | 2021-02-16T02:33:06.000Z | 2021-03-13T14:34:19.000Z | NLEigenSolver/vendor/Blaze/blazetest/src/mathtest/views/rows/DenseGeneralTest1.cpp | capnrenan/NLEigenJacobiDavidsonModified | 91bc61f868bb2cf9dd42931fdeb4e33903e3369c | [
"MIT"
] | null | null | null | NLEigenSolver/vendor/Blaze/blazetest/src/mathtest/views/rows/DenseGeneralTest1.cpp | capnrenan/NLEigenJacobiDavidsonModified | 91bc61f868bb2cf9dd42931fdeb4e33903e3369c | [
"MIT"
] | null | null | null | //=================================================================================================
/*!
// \file src/mathtest/views/rows/DenseGeneralTest1.cpp
// \brief Source file for the Rows dense general test (part 1)
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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 HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <memory>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/CustomMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/DynamicVector.h>
#include <blaze/util/Memory.h>
#include <blaze/util/policies/Deallocate.h>
#include <blazetest/mathtest/views/rows/DenseGeneralTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
namespace blazetest {
namespace mathtest {
namespace views {
namespace rows {
//=================================================================================================
//
// CONSTRUCTORS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Constructor for the Rows dense general test.
//
// \exception std::runtime_error Operation error detected.
*/
DenseGeneralTest::DenseGeneralTest()
: mat_ ( 5UL, 4UL )
, tmat_( 5UL, 4UL )
{
testConstructors();
testAssignment();
testAddAssign();
testSubAssign();
testSchurAssign();
testMultAssign();
}
//*************************************************************************************************
//=================================================================================================
//
// TEST FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Test of the Rows constructors.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of all constructors of the Rows specialization. In case
// an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseGeneralTest::testConstructors()
{
using blaze::index_sequence;
using blaze::initializer_list;
//=====================================================================================
// Row-major setup via index_sequence
//=====================================================================================
{
test_ = "Row-major Rows constructor (index_sequence)";
initialize();
// Setup of a regular row selection
{
auto rs = blaze::rows( mat_, index_sequence<0,4,2>() );
if( rs.rows() != 3UL || rs.columns() != mat_.columns() ||
rs(0,0) != mat_(0,0) || rs(0,1) != mat_(0,1) || rs(0,2) != mat_(0,2) || rs(0,3) != mat_(0,3) ||
rs(1,0) != mat_(4,0) || rs(1,1) != mat_(4,1) || rs(1,2) != mat_(4,2) || rs(1,3) != mat_(4,3) ||
rs(2,0) != mat_(2,0) || rs(2,1) != mat_(2,1) || rs(2,2) != mat_(2,2) || rs(2,3) != mat_(2,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds row selection
try {
auto rs = blaze::rows( mat_, index_sequence<5>() );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a row selection on a compile-time row selection
{
auto rs1 = blaze::rows( mat_, index_sequence<0,4,2>() );
auto rs2 = blaze::rows( rs1, index_sequence<2,1>() );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an explicit row selection
{
auto rs1 = blaze::rows( mat_, { 0, 4, 2 } );
auto rs2 = blaze::rows( rs1, index_sequence<2,1>() );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an implicit row selection
{
const std::array<size_t,3UL> indices{ 0, 4, 2 };
auto rs1 = blaze::rows( mat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
auto rs2 = blaze::rows( rs1, index_sequence<2,1>() );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major setup via initializer_list
//=====================================================================================
{
test_ = "Row-major Rows constructor (initializer_list)";
initialize();
// Setup of empty row selection
{
std::initializer_list<size_t> indices{};
auto rs = blaze::rows( mat_, indices );
if( rs.rows() != 0UL || rs.columns() != mat_.columns() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular row selection
{
auto rs = blaze::rows( mat_, { 0, 4, 2 } );
if( rs.rows() != 3UL || rs.columns() != mat_.columns() ||
rs(0,0) != mat_(0,0) || rs(0,1) != mat_(0,1) || rs(0,2) != mat_(0,2) || rs(0,3) != mat_(0,3) ||
rs(1,0) != mat_(4,0) || rs(1,1) != mat_(4,1) || rs(1,2) != mat_(4,2) || rs(1,3) != mat_(4,3) ||
rs(2,0) != mat_(2,0) || rs(2,1) != mat_(2,1) || rs(2,2) != mat_(2,2) || rs(2,3) != mat_(2,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds row selection
try {
auto rs = blaze::rows( mat_, { 5 } );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a row selection on a compile-time row selection
{
auto rs1 = blaze::rows( mat_, index_sequence<0,4,2>() );
auto rs2 = blaze::rows( rs1, { 2, 1 } );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an explicit row selection
{
auto rs1 = blaze::rows( mat_, { 0, 4, 2 } );
auto rs2 = blaze::rows( rs1, { 2, 1 } );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an implicit row selection
{
const std::array<size_t,3UL> indices{ 0, 4, 2 };
auto rs1 = blaze::rows( mat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
auto rs2 = blaze::rows( rs1, { 2, 1 } );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major setup via std::vector
//=====================================================================================
{
test_ = "Row-major Rows constructor (std::vector)";
initialize();
// Setup of empty row selection
{
std::vector<size_t> indices;
auto rs = blaze::rows( mat_, indices );
if( rs.rows() != 0UL || rs.columns() != mat_.columns() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular row selection
{
std::vector<size_t> indices{ 0, 4, 2 };
auto rs = blaze::rows( mat_, indices );
if( rs.rows() != 3UL || rs.columns() != mat_.columns() ||
rs(0,0) != mat_(0,0) || rs(0,1) != mat_(0,1) || rs(0,2) != mat_(0,2) || rs(0,3) != mat_(0,3) ||
rs(1,0) != mat_(4,0) || rs(1,1) != mat_(4,1) || rs(1,2) != mat_(4,2) || rs(1,3) != mat_(4,3) ||
rs(2,0) != mat_(2,0) || rs(2,1) != mat_(2,1) || rs(2,2) != mat_(2,2) || rs(2,3) != mat_(2,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds row selection
try {
std::vector<size_t> indices{ 5 };
auto rs = blaze::rows( mat_, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a row selection on a compile-time row selection
{
auto rs1 = blaze::rows( mat_, index_sequence<0,4,2>() );
const std::vector<size_t> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an explicit row selection
{
auto rs1 = blaze::rows( mat_, { 0, 4, 2 } );
const std::vector<size_t> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an implicit row selection
{
const std::array<size_t,3UL> indices1{ 0, 4, 2 };
auto rs1 = blaze::rows( mat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::vector<size_t> indices2{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices2 );;
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major setup via std::array
//=====================================================================================
{
test_ = "Row-major Rows constructor (std::array)";
initialize();
// Setup of a regular row selection
{
std::array<size_t,3UL> indices{ 0, 4, 2 };
auto rs = blaze::rows( mat_, indices );
if( rs.rows() != 3UL || rs.columns() != mat_.columns() ||
rs(0,0) != mat_(0,0) || rs(0,1) != mat_(0,1) || rs(0,2) != mat_(0,2) || rs(0,3) != mat_(0,3) ||
rs(1,0) != mat_(4,0) || rs(1,1) != mat_(4,1) || rs(1,2) != mat_(4,2) || rs(1,3) != mat_(4,3) ||
rs(2,0) != mat_(2,0) || rs(2,1) != mat_(2,1) || rs(2,2) != mat_(2,2) || rs(2,3) != mat_(2,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds row selection
try {
std::array<size_t,1UL> indices{ 5 };
auto rs = blaze::rows( mat_, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a row selection on a compile-time row selection
{
auto rs1 = blaze::rows( mat_, index_sequence<0,4,2>() );
const std::array<size_t,2UL> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an explicit row selection
{
auto rs1 = blaze::rows( mat_, { 0, 4, 2 } );
const std::array<size_t,2UL> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an implicit row selection
{
const std::array<size_t,3UL> indices1{ 0, 4, 2 };
auto rs1 = blaze::rows( mat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::array<size_t,2UL> indices2{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices2 );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major setup via lambda expression
//=====================================================================================
{
test_ = "Row-major Rows constructor (lambda expression)";
initialize();
// Setup of empty row selection
{
auto rs = blaze::rows( mat_, []( size_t ){ return 0UL; }, 0UL );
if( rs.rows() != 0UL || rs.columns() != mat_.columns() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular row selection
{
const std::array<size_t,3UL> indices{ 0, 4, 2 };
auto rs = blaze::rows( mat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
if( rs.rows() != 3UL || rs.columns() != mat_.columns() ||
rs(0,0) != mat_(0,0) || rs(0,1) != mat_(0,1) || rs(0,2) != mat_(0,2) || rs(0,3) != mat_(0,3) ||
rs(1,0) != mat_(4,0) || rs(1,1) != mat_(4,1) || rs(1,2) != mat_(4,2) || rs(1,3) != mat_(4,3) ||
rs(2,0) != mat_(2,0) || rs(2,1) != mat_(2,1) || rs(2,2) != mat_(2,2) || rs(2,3) != mat_(2,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds row selection
try {
auto rs = blaze::rows( mat_, []( size_t ){ return 5UL; }, 1UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a row selection on a compile-time row selection
{
auto rs1 = blaze::rows( mat_, index_sequence<0,4,2>() );
const std::array<size_t,2UL> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, [indices]( size_t i ){ return indices[i]; }, 2UL );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an explicit row selection
{
auto rs1 = blaze::rows( mat_, { 0, 4, 2 } );
const std::array<size_t,2UL> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, [indices]( size_t i ){ return indices[i]; }, 2UL );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an implicit row selection
{
const std::array<size_t,3UL> indices1{ 0, 4, 2 };
auto rs1 = blaze::rows( mat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::array<size_t,2UL> indices2{ 2, 1 };
auto rs2 = blaze::rows( rs1, [indices2]( size_t i ){ return indices2[i]; }, 2UL );
if( rs2.rows() != 2UL || rs2.columns() != mat_.columns() ||
rs2(0,0) != mat_(2,0) || rs2(0,1) != mat_(2,1) || rs2(0,2) != mat_(2,2) || rs2(0,3) != mat_(2,3) ||
rs2(1,0) != mat_(4,0) || rs2(1,1) != mat_(4,1) || rs2(1,2) != mat_(4,2) || rs2(1,3) != mat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major setup of random in-bounds element selection
//=====================================================================================
{
test_ = "Row-major Rows constructor (stress test)";
initialize();
for( size_t rep=0UL; rep<100UL; ++rep )
{
blaze::DynamicVector<size_t> indices( blaze::rand<size_t>( 1UL, 20UL ) );
randomize( indices, 0UL, mat_.rows()-1UL );
auto rs = blaze::rows( mat_, indices.data(), indices.size() );
for( size_t i=0UL; i<rs.rows(); ++i ) {
for( size_t j=0UL; j<rs.columns(); ++j ) {
if( rs(i,j) != mat_(indices[i],j) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Indices:\n" << indices << "\n"
<< " Row selection:\n" << rs << "\n"
<< " Matrix:\n" << mat_ << "\n";
throw std::runtime_error( oss.str() );
}
}
}
}
}
//=====================================================================================
// Column-major setup via index_sequence
//=====================================================================================
{
test_ = "Column-major Rows constructor (index_sequence)";
initialize();
// Setup of a regular row selection
{
auto rs = blaze::rows( tmat_, index_sequence<0,4,2>() );
if( rs.rows() != 3UL || rs.columns() != tmat_.columns() ||
rs(0,0) != tmat_(0,0) || rs(0,1) != tmat_(0,1) || rs(0,2) != tmat_(0,2) || rs(0,3) != tmat_(0,3) ||
rs(1,0) != tmat_(4,0) || rs(1,1) != tmat_(4,1) || rs(1,2) != tmat_(4,2) || rs(1,3) != tmat_(4,3) ||
rs(2,0) != tmat_(2,0) || rs(2,1) != tmat_(2,1) || rs(2,2) != tmat_(2,2) || rs(2,3) != tmat_(2,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds row selection
try {
auto rs = blaze::rows( tmat_, index_sequence<5>() );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a row selection on a compile-time row selection
{
auto rs1 = blaze::rows( tmat_, index_sequence<0,4,2>() );
auto rs2 = blaze::rows( rs1, index_sequence<2,1>() );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an explicit row selection
{
auto rs1 = blaze::rows( tmat_, { 0, 4, 2 } );
auto rs2 = blaze::rows( rs1, index_sequence<2,1>() );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an implicit row selection
{
const std::array<size_t,3UL> indices{ 0, 4, 2 };
auto rs1 = blaze::rows( tmat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
auto rs2 = blaze::rows( rs1, index_sequence<2,1>() );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major setup via initializer_list
//=====================================================================================
{
test_ = "Column-major Rows constructor (initializer_list)";
initialize();
// Setup of empty row selection
{
std::initializer_list<size_t> indices{};
auto rs = blaze::rows( tmat_, indices );
if( rs.rows() != 0UL || rs.columns() != tmat_.columns() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular row selection
{
auto rs = blaze::rows( tmat_, { 0, 4, 2 } );
if( rs.rows() != 3UL || rs.columns() != tmat_.columns() ||
rs(0,0) != tmat_(0,0) || rs(0,1) != tmat_(0,1) || rs(0,2) != tmat_(0,2) || rs(0,3) != tmat_(0,3) ||
rs(1,0) != tmat_(4,0) || rs(1,1) != tmat_(4,1) || rs(1,2) != tmat_(4,2) || rs(1,3) != tmat_(4,3) ||
rs(2,0) != tmat_(2,0) || rs(2,1) != tmat_(2,1) || rs(2,2) != tmat_(2,2) || rs(2,3) != tmat_(2,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds row selection
try {
auto rs = blaze::rows( tmat_, { 5 } );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a row selection on a compile-time row selection
{
auto rs1 = blaze::rows( tmat_, index_sequence<0,4,2>() );
auto rs2 = blaze::rows( rs1, { 2, 1 } );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an explicit row selection
{
auto rs1 = blaze::rows( tmat_, { 0, 4, 2 } );
auto rs2 = blaze::rows( rs1, { 2, 1 } );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an implicit row selection
{
const std::array<size_t,3UL> indices{ 0, 4, 2 };
auto rs1 = blaze::rows( tmat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
auto rs2 = blaze::rows( rs1, { 2, 1 } );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major setup via std::vector
//=====================================================================================
{
test_ = "Column-major Rows constructor (std::vector)";
initialize();
// Setup of empty row selection
{
std::vector<size_t> indices;
auto rs = blaze::rows( tmat_, indices );
if( rs.rows() != 0UL || rs.columns() != tmat_.columns() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular row selection
{
std::vector<size_t> indices{ 0, 4, 2 };
auto rs = blaze::rows( tmat_, indices );
if( rs.rows() != 3UL || rs.columns() != tmat_.columns() ||
rs(0,0) != tmat_(0,0) || rs(0,1) != tmat_(0,1) || rs(0,2) != tmat_(0,2) || rs(0,3) != tmat_(0,3) ||
rs(1,0) != tmat_(4,0) || rs(1,1) != tmat_(4,1) || rs(1,2) != tmat_(4,2) || rs(1,3) != tmat_(4,3) ||
rs(2,0) != tmat_(2,0) || rs(2,1) != tmat_(2,1) || rs(2,2) != tmat_(2,2) || rs(2,3) != tmat_(2,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds row selection
try {
std::vector<size_t> indices{ 5 };
auto rs = blaze::rows( tmat_, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a row selection on a compile-time row selection
{
auto rs1 = blaze::rows( tmat_, index_sequence<0,4,2>() );
const std::vector<size_t> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an explicit row selection
{
auto rs1 = blaze::rows( tmat_, { 0, 4, 2 } );
const std::vector<size_t> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an implicit row selection
{
const std::array<size_t,3UL> indices1{ 0, 4, 2 };
auto rs1 = blaze::rows( tmat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::vector<size_t> indices2{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices2 );;
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major setup via std::array
//=====================================================================================
{
test_ = "Column-major Rows constructor (std::array)";
initialize();
// Setup of a regular row selection
{
std::array<size_t,3UL> indices{ 0, 4, 2 };
auto rs = blaze::rows( tmat_, indices );
if( rs.rows() != 3UL || rs.columns() != tmat_.columns() ||
rs(0,0) != tmat_(0,0) || rs(0,1) != tmat_(0,1) || rs(0,2) != tmat_(0,2) || rs(0,3) != tmat_(0,3) ||
rs(1,0) != tmat_(4,0) || rs(1,1) != tmat_(4,1) || rs(1,2) != tmat_(4,2) || rs(1,3) != tmat_(4,3) ||
rs(2,0) != tmat_(2,0) || rs(2,1) != tmat_(2,1) || rs(2,2) != tmat_(2,2) || rs(2,3) != tmat_(2,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds row selection
try {
std::array<size_t,1UL> indices{ 5 };
auto rs = blaze::rows( tmat_, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a row selection on a compile-time row selection
{
auto rs1 = blaze::rows( tmat_, index_sequence<0,4,2>() );
const std::array<size_t,2UL> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an explicit row selection
{
auto rs1 = blaze::rows( tmat_, { 0, 4, 2 } );
const std::array<size_t,2UL> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an implicit row selection
{
const std::array<size_t,3UL> indices1{ 0, 4, 2 };
auto rs1 = blaze::rows( tmat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::array<size_t,2UL> indices2{ 2, 1 };
auto rs2 = blaze::rows( rs1, indices2 );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major setup via lambda expression
//=====================================================================================
{
test_ = "Column-major Rows constructor (lambda expression)";
initialize();
// Setup of empty row selection
{
auto rs = blaze::rows( tmat_, []( size_t ){ return 0UL; }, 0UL );
if( rs.rows() != 0UL || rs.columns() != tmat_.columns() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular row selection
{
const std::array<size_t,3UL> indices{ 0, 4, 2 };
auto rs = blaze::rows( tmat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
if( rs.rows() != 3UL || rs.columns() != tmat_.columns() ||
rs(0,0) != tmat_(0,0) || rs(0,1) != tmat_(0,1) || rs(0,2) != tmat_(0,2) || rs(0,3) != tmat_(0,3) ||
rs(1,0) != tmat_(4,0) || rs(1,1) != tmat_(4,1) || rs(1,2) != tmat_(4,2) || rs(1,3) != tmat_(4,3) ||
rs(2,0) != tmat_(2,0) || rs(2,1) != tmat_(2,1) || rs(2,2) != tmat_(2,2) || rs(2,3) != tmat_(2,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds row selection
try {
auto rs = blaze::rows( tmat_, []( size_t ){ return 5UL; }, 1UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a row selection on a compile-time row selection
{
auto rs1 = blaze::rows( tmat_, index_sequence<0,4,2>() );
const std::array<size_t,2UL> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, [indices]( size_t i ){ return indices[i]; }, 2UL );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an explicit row selection
{
auto rs1 = blaze::rows( tmat_, { 0, 4, 2 } );
const std::array<size_t,2UL> indices{ 2, 1 };
auto rs2 = blaze::rows( rs1, [indices]( size_t i ){ return indices[i]; }, 2UL );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a row selection on an implicit row selection
{
const std::array<size_t,3UL> indices1{ 0, 4, 2 };
auto rs1 = blaze::rows( tmat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::array<size_t,2UL> indices2{ 2, 1 };
auto rs2 = blaze::rows( rs1, [indices2]( size_t i ){ return indices2[i]; }, 2UL );
if( rs2.rows() != 2UL || rs2.columns() != tmat_.columns() ||
rs2(0,0) != tmat_(2,0) || rs2(0,1) != tmat_(2,1) || rs2(0,2) != tmat_(2,2) || rs2(0,3) != tmat_(2,3) ||
rs2(1,0) != tmat_(4,0) || rs2(1,1) != tmat_(4,1) || rs2(1,2) != tmat_(4,2) || rs2(1,3) != tmat_(4,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Result:\n" << rs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major setup of random in-bounds element selection
//=====================================================================================
{
test_ = "Column-major Rows constructor (stress test)";
initialize();
for( size_t rep=0UL; rep<100UL; ++rep )
{
blaze::DynamicVector<size_t> indices( blaze::rand<size_t>( 1UL, 20UL ) );
randomize( indices, 0UL, tmat_.rows()-1UL );
auto rs = blaze::rows( tmat_, indices.data(), indices.size() );
for( size_t i=0UL; i<rs.rows(); ++i ) {
for( size_t j=0UL; j<rs.columns(); ++j ) {
if( rs(i,j) != tmat_(indices[i],j) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of row selection failed\n"
<< " Details:\n"
<< " Indices:\n" << indices << "\n"
<< " Row selection:\n" << rs << "\n"
<< " Matrix:\n" << tmat_ << "\n";
throw std::runtime_error( oss.str() );
}
}
}
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the Rows assignment operators.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of all assignment operators of the Rows specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseGeneralTest::testAssignment()
{
using blaze::aligned;
using blaze::unaligned;
using blaze::padded;
using blaze::unpadded;
using blaze::rowMajor;
using blaze::columnMajor;
//=====================================================================================
// Row-major homogeneous assignment
//=====================================================================================
{
test_ = "Row-major Rows homogeneous assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
rs = 12;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 14UL );
if( rs(0,0) != 12 || rs(0,1) != 12 || rs(0,2) != 12 || rs(0,3) != 12 ||
rs(1,0) != 12 || rs(1,1) != 12 || rs(1,2) != 12 || rs(1,3) != 12 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 12 12 12 12 )\n( 12 12 12 12 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 12 || mat_(1,1) != 12 || mat_(1,2) != 12 || mat_(1,3) != 12 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 12 || mat_(3,1) != 12 || mat_(3,2) != 12 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 12 12 12 12 )\n"
"( -2 0 -3 0 )\n"
"( 12 12 12 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major list assignment
//=====================================================================================
{
test_ = "Row-major Rows list assignment (complete list)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
rs = { { 11, 0, 0, 12 }, { 0, 13, 14, 0 } };
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 13 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major Rows list assignment (incomplete list)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
rs = { { 11, 0, 0, 12 }, { 0, 13, 14 } };
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 13 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major copy assignment
//=====================================================================================
{
test_ = "Row-major Rows copy assignment (no aliasing)";
initialize();
MT mat{ { 0, 0, 0, 0 },
{ 11, 0, 12, 0 },
{ 0, 0, 0, 0 },
{ 13, 14, 15, 16 },
{ 0, 0, 0, 0 } };
auto rs = blaze::rows( mat, { 3UL, 1UL } );
rs = blaze::rows( mat_, { 3UL, 1UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 4UL );
if( rs(0,0) != 0 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -6 ||
rs(1,0) != 0 || rs(1,1) != 1 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 4 5 -6 )\n( 0 1 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 || mat(0,3) != 0 ||
mat(1,0) != 0 || mat(1,1) != 1 || mat(1,2) != 0 || mat(1,3) != 0 ||
mat(2,0) != 0 || mat(2,1) != 0 || mat(2,2) != 0 || mat(2,3) != 0 ||
mat(3,0) != 0 || mat(3,1) != 4 || mat(3,2) != 5 || mat(3,3) != -6 ||
mat(4,0) != 0 || mat(4,1) != 0 || mat(4,2) != 0 || mat(4,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 4 5 -6 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major Rows copy assignment (aliasing)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 4UL } );
rs = blaze::rows( mat_, { 2UL, 3UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 5UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 8UL );
if( rs(0,0) != -2 || rs(0,1) != 0 || rs(0,2) != -3 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 4 || rs(1,2) != 5 || rs(1,3) != -6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -2 0 -3 0 )\n( 0 4 5 -6 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 1 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -2 || mat_(3,1) != 0 || mat_(3,2) != -3 || mat_(3,3) != 0 ||
mat_(4,0) != 0 || mat_(4,1) != 4 || mat_(4,2) != 5 || mat_(4,3) != -6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 0 0 )\n"
"( -2 0 -3 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 4 5 -6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major dense matrix assignment
//=====================================================================================
{
test_ = "Row-major/row-major dense matrix assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 13 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major dense matrix assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 32UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 13 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major dense matrix assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 13 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 13 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 13 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 13 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major sparse matrix assignment
//=====================================================================================
{
test_ = "Row-major/row-major sparse matrix assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 13 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major sparse matrix assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 13 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major homogeneous assignment
//=====================================================================================
{
test_ = "Column-major Rows homogeneous assignment";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
rs = 12;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 14UL );
if( rs(0,0) != 12 || rs(0,1) != 12 || rs(0,2) != 12 || rs(0,3) != 12 ||
rs(1,0) != 12 || rs(1,1) != 12 || rs(1,2) != 12 || rs(1,3) != 12 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 12 12 12 12 )\n( 12 12 12 12 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 12 || tmat_(1,1) != 12 || tmat_(1,2) != 12 || tmat_(1,3) != 12 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 12 || tmat_(3,1) != 12 || tmat_(3,2) != 12 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 12 12 12 12 )\n"
"( -2 0 -3 0 )\n"
"( 12 12 12 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major list assignment
//=====================================================================================
{
test_ = "Column-major Rows list assignment (complete list)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
rs = { { 11, 0, 0, 12 }, { 0, 13, 14, 0 } };
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 13 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major Rows list assignment (incomplete list)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
rs = { { 11, 0, 0, 12 }, { 0, 13, 14 } };
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 13 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major copy assignment
//=====================================================================================
{
test_ = "Column-major Rows copy assignment (no aliasing)";
initialize();
OMT mat{ { 0, 0, 0, 0 },
{ 11, 0, 12, 0 },
{ 0, 0, 0, 0 },
{ 13, 14, 15, 16 },
{ 0, 0, 0, 0 } };
auto rs = blaze::rows( mat, { 3UL, 1UL } );
rs = blaze::rows( tmat_, { 3UL, 1UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 4UL );
if( rs(0,0) != 0 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -6 ||
rs(1,0) != 0 || rs(1,1) != 1 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 4 5 -6 )\n( 0 1 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 || mat(0,3) != 0 ||
mat(1,0) != 0 || mat(1,1) != 1 || mat(1,2) != 0 || mat(1,3) != 0 ||
mat(2,0) != 0 || mat(2,1) != 0 || mat(2,2) != 0 || mat(2,3) != 0 ||
mat(3,0) != 0 || mat(3,1) != 4 || mat(3,2) != 5 || mat(3,3) != -6 ||
mat(4,0) != 0 || mat(4,1) != 0 || mat(4,2) != 0 || mat(4,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 4 5 -6 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major Rows copy assignment (aliasing)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 4UL } );
rs = blaze::rows( tmat_, { 2UL, 3UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 5UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 8UL );
if( rs(0,0) != -2 || rs(0,1) != 0 || rs(0,2) != -3 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 4 || rs(1,2) != 5 || rs(1,3) != -6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -2 0 -3 0 )\n( 0 4 5 -6 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 1 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != -2 || tmat_(3,1) != 0 || tmat_(3,2) != -3 || tmat_(3,3) != 0 ||
tmat_(4,0) != 0 || tmat_(4,1) != 4 || tmat_(4,2) != 5 || tmat_(4,3) != -6 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 0 0 )\n"
"( -2 0 -3 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 4 5 -6 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major dense matrix assignment
//=====================================================================================
{
test_ = "Column-major/row-major dense matrix assignment (mixed type)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 13 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major dense matrix assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 32UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 13 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major dense matrix assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 13 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix assignment (mixed type)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 13 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 13 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 13 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major sparse matrix assignment
//=====================================================================================
{
test_ = "Column-major/row-major sparse matrix assignment";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 13 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major sparse matrix assignment";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs = mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 10UL );
if( rs(0,0) != 11 || rs(0,1) != 0 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 13 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 0 0 12 )\n( 0 13 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 13 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 13 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 0 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the Rows addition assignment operators.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the addition assignment operators of the Rows specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseGeneralTest::testAddAssign()
{
using blaze::aligned;
using blaze::unaligned;
using blaze::padded;
using blaze::unpadded;
using blaze::rowMajor;
using blaze::columnMajor;
//=====================================================================================
// Row-major Rows addition assignment
//=====================================================================================
{
test_ = "Row-major Rows addition assignment (no aliasing)";
initialize();
MT mat{ { 0, 0, 0, 0 },
{ 11, 0, 12, 0 },
{ 0, 0, 0, 0 },
{ 13, 14, 15, 16 },
{ 0, 0, 0, 0 } };
auto rs = blaze::rows( mat, { 3UL, 1UL } );
rs += blaze::rows( mat_, { 3UL, 1UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 7UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 7UL );
if( rs(0,0) != 13 || rs(0,1) != 18 || rs(0,2) != 20 || rs(0,3) != 10 ||
rs(1,0) != 11 || rs(1,1) != 1 || rs(1,2) != 12 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 13 18 20 10 )\n( 11 1 12 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 || mat(0,3) != 0 ||
mat(1,0) != 11 || mat(1,1) != 1 || mat(1,2) != 12 || mat(1,3) != 0 ||
mat(2,0) != 0 || mat(2,1) != 0 || mat(2,2) != 0 || mat(2,3) != 0 ||
mat(3,0) != 13 || mat(3,1) != 18 || mat(3,2) != 20 || mat(3,3) != 10 ||
mat(4,0) != 0 || mat(4,1) != 0 || mat(4,2) != 0 || mat(4,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 11 1 12 0 )\n"
"( 0 0 0 0 )\n"
"( 13 18 20 10 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major Rows addition assignment (aliasing)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 4UL } );
rs += blaze::rows( mat_, { 2UL, 3UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 11UL );
if( rs(0,0) != -2 || rs(0,1) != 4 || rs(0,2) != 2 || rs(0,3) != -6 ||
rs(1,0) != 7 || rs(1,1) != -4 || rs(1,2) != 14 || rs(1,3) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -2 4 2 -6 )\n( 7 -4 14 4 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 1 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -2 || mat_(3,1) != 4 || mat_(3,2) != 2 || mat_(3,3) != -6 ||
mat_(4,0) != 7 || mat_(4,1) != -4 || mat_(4,2) != 14 || mat_(4,3) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 0 0 )\n"
"( -2 0 -3 0 )\n"
"( -2 4 2 -6 )\n"
"( 7 -4 14 4 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major dense matrix addition assignment
//=====================================================================================
{
test_ = "Row-major/row-major dense matrix addition assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 14 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != 6 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major dense matrix addition assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 32UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 14 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != 6 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major dense matrix addition assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 14 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != 6 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix addition assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 14 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != 6 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix addition assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 14 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != 6 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix addition assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 14 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != 6 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major sparse matrix addition assignment
//=====================================================================================
{
test_ = "Row-major/row-major sparse matrix addition assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 14 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != 6 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major sparse matrix addition assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 14 || mat_(1,2) != 14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != 6 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major Rows addition assignment
//=====================================================================================
{
test_ = "Column-major Rows addition assignment (no aliasing)";
initialize();
OMT mat{ { 0, 0, 0, 0 },
{ 11, 0, 12, 0 },
{ 0, 0, 0, 0 },
{ 13, 14, 15, 16 },
{ 0, 0, 0, 0 } };
auto rs = blaze::rows( mat, { 3UL, 1UL } );
rs += blaze::rows( tmat_, { 3UL, 1UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 7UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 7UL );
if( rs(0,0) != 13 || rs(0,1) != 18 || rs(0,2) != 20 || rs(0,3) != 10 ||
rs(1,0) != 11 || rs(1,1) != 1 || rs(1,2) != 12 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 13 18 20 10 )\n( 11 1 12 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 || mat(0,3) != 0 ||
mat(1,0) != 11 || mat(1,1) != 1 || mat(1,2) != 12 || mat(1,3) != 0 ||
mat(2,0) != 0 || mat(2,1) != 0 || mat(2,2) != 0 || mat(2,3) != 0 ||
mat(3,0) != 13 || mat(3,1) != 18 || mat(3,2) != 20 || mat(3,3) != 10 ||
mat(4,0) != 0 || mat(4,1) != 0 || mat(4,2) != 0 || mat(4,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 11 1 12 0 )\n"
"( 0 0 0 0 )\n"
"( 13 18 20 10 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major Rows addition assignment (aliasing)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 4UL } );
rs += blaze::rows( tmat_, { 2UL, 3UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 11UL );
if( rs(0,0) != -2 || rs(0,1) != 4 || rs(0,2) != 2 || rs(0,3) != -6 ||
rs(1,0) != 7 || rs(1,1) != -4 || rs(1,2) != 14 || rs(1,3) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -2 4 2 -6 )\n( 7 -4 14 4 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 1 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != -2 || tmat_(3,1) != 4 || tmat_(3,2) != 2 || tmat_(3,3) != -6 ||
tmat_(4,0) != 7 || tmat_(4,1) != -4 || tmat_(4,2) != 14 || tmat_(4,3) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 0 0 )\n"
"( -2 0 -3 0 )\n"
"( -2 4 2 -6 )\n"
"( 7 -4 14 4 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major dense matrix addition assignment
//=====================================================================================
{
test_ = "Column-major/row-major dense matrix addition assignment (mixed type)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 14 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 4 || tmat_(3,2) != 5 || tmat_(3,3) != 6 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major dense matrix addition assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 32UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 14 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 4 || tmat_(3,2) != 5 || tmat_(3,3) != 6 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major dense matrix addition assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 14 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 4 || tmat_(3,2) != 5 || tmat_(3,3) != 6 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix addition assignment (mixed type)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 14 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 4 || tmat_(3,2) != 5 || tmat_(3,3) != 6 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix addition assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 14 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 4 || tmat_(3,2) != 5 || tmat_(3,3) != 6 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix addition assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 14 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 4 || tmat_(3,2) != 5 || tmat_(3,3) != 6 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major sparse matrix addition assignment
//=====================================================================================
{
test_ = "Column-major/row-major sparse matrix addition assignment";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 14 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 4 || tmat_(3,2) != 5 || tmat_(3,3) != 6 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major sparse matrix addition assignment";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs += mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != 6 ||
rs(1,0) != 0 || rs(1,1) != 14 || rs(1,2) != 14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 11 4 17 -6 )\n( 0 14 14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 14 || tmat_(1,2) != 14 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 11 || tmat_(3,1) != 4 || tmat_(3,2) != 5 || tmat_(3,3) != 6 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Addition assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 14 14 0 )\n"
"( -2 0 -3 0 )\n"
"( 11 4 5 6 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the Rows subtraction assignment operators.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the subtraction assignment operators of the Rows
// specialization. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseGeneralTest::testSubAssign()
{
using blaze::aligned;
using blaze::unaligned;
using blaze::padded;
using blaze::unpadded;
using blaze::rowMajor;
using blaze::columnMajor;
//=====================================================================================
// Row-major Rows subtraction assignment
//=====================================================================================
{
test_ = "Row-major Rows subtraction assignment (no aliasing)";
initialize();
MT mat{ { 0, 0, 0, 0 },
{ 11, 0, 12, 0 },
{ 0, 0, 0, 0 },
{ 13, 14, 15, 16 },
{ 0, 0, 0, 0 } };
auto rs = blaze::rows( mat, { 3UL, 1UL } );
rs -= blaze::rows( mat_, { 3UL, 1UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 7UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 7UL );
if( rs(0,0) != 13 || rs(0,1) != 10 || rs(0,2) != 10 || rs(0,3) != 22 ||
rs(1,0) != 11 || rs(1,1) != -1 || rs(1,2) != 12 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 13 10 10 22 )\n( 11 -1 12 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 || mat(0,3) != 0 ||
mat(1,0) != 11 || mat(1,1) != -1 || mat(1,2) != 12 || mat(1,3) != 0 ||
mat(2,0) != 0 || mat(2,1) != 0 || mat(2,2) != 0 || mat(2,3) != 0 ||
mat(3,0) != 13 || mat(3,1) != 10 || mat(3,2) != 10 || mat(3,3) != 22 ||
mat(4,0) != 0 || mat(4,1) != 0 || mat(4,2) != 0 || mat(4,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 11 -1 12 0 )\n"
"( 0 0 0 0 )\n"
"( 13 10 10 22 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major Rows subtraction assignment (aliasing)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 4UL } );
rs -= blaze::rows( mat_, { 2UL, 3UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 11UL );
if( rs(0,0) != 2 || rs(0,1) != 4 || rs(0,2) != 8 || rs(0,3) != -6 ||
rs(1,0) != 7 || rs(1,1) != -12 || rs(1,2) != 4 || rs(1,3) != 16 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 2 4 8 -6 )\n( 7 -12 4 16 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 1 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 2 || mat_(3,1) != 4 || mat_(3,2) != 8 || mat_(3,3) != -6 ||
mat_(4,0) != 7 || mat_(4,1) != -12 || mat_(4,2) != 4 || mat_(4,3) != 16 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 2 4 8 -6 )\n"
"( 7 -12 4 16 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major dense matrix subtraction assignment
//=====================================================================================
{
test_ = "Row-major/row-major dense matrix subtraction assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major dense matrix subtraction assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 32UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major dense matrix subtraction assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix subtraction assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix subtraction assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix subtraction assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major sparse matrix subtraction assignment
//=====================================================================================
{
test_ = "Row-major/row-major sparse matrix subtraction assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major sparse matrix subtraction assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major Rows subtraction assignment
//=====================================================================================
{
test_ = "Column-major Rows subtraction assignment (no aliasing)";
initialize();
MT mat{ { 0, 0, 0, 0 },
{ 11, 0, 12, 0 },
{ 0, 0, 0, 0 },
{ 13, 14, 15, 16 },
{ 0, 0, 0, 0 } };
auto rs = blaze::rows( mat, { 3UL, 1UL } );
rs -= blaze::rows( mat_, { 3UL, 1UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 7UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 7UL );
if( rs(0,0) != 13 || rs(0,1) != 10 || rs(0,2) != 10 || rs(0,3) != 22 ||
rs(1,0) != 11 || rs(1,1) != -1 || rs(1,2) != 12 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 13 10 10 22 )\n( 11 -1 12 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 || mat(0,3) != 0 ||
mat(1,0) != 11 || mat(1,1) != -1 || mat(1,2) != 12 || mat(1,3) != 0 ||
mat(2,0) != 0 || mat(2,1) != 0 || mat(2,2) != 0 || mat(2,3) != 0 ||
mat(3,0) != 13 || mat(3,1) != 10 || mat(3,2) != 10 || mat(3,3) != 22 ||
mat(4,0) != 0 || mat(4,1) != 0 || mat(4,2) != 0 || mat(4,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 11 -1 12 0 )\n"
"( 0 0 0 0 )\n"
"( 13 10 10 22 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major Rows subtraction assignment (aliasing)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 4UL } );
rs -= blaze::rows( mat_, { 2UL, 3UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 11UL );
if( rs(0,0) != 2 || rs(0,1) != 4 || rs(0,2) != 8 || rs(0,3) != -6 ||
rs(1,0) != 7 || rs(1,1) != -12 || rs(1,2) != 4 || rs(1,3) != 16 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 2 4 8 -6 )\n( 7 -12 4 16 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 1 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 2 || mat_(3,1) != 4 || mat_(3,2) != 8 || mat_(3,3) != -6 ||
mat_(4,0) != 7 || mat_(4,1) != -12 || mat_(4,2) != 4 || mat_(4,3) != 16 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 2 4 8 -6 )\n"
"( 7 -12 4 16 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major dense matrix subtraction assignment
//=====================================================================================
{
test_ = "Column-major/row-major dense matrix subtraction assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major dense matrix subtraction assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 32UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major dense matrix subtraction assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix subtraction assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix subtraction assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix subtraction assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,0) = 11;
mat(0,3) = 12;
mat(1,1) = 13;
mat(1,2) = 14;
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major sparse matrix subtraction assignment
//=====================================================================================
{
test_ = "Column-major/row-major sparse matrix subtraction assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,rowMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major sparse matrix subtraction assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,columnMajor> mat{ { 11, 0, 0, 12 },
{ 0, 13, 14, 0 } };
rs -= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 6UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != -11 || rs(0,1) != 4 || rs(0,2) != 5 || rs(0,3) != -18 ||
rs(1,0) != 0 || rs(1,1) != -12 || rs(1,2) != -14 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( -11 4 5 -18 )\n( 0 -12 -14 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != -12 || mat_(1,2) != -14 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != -11 || mat_(3,1) != 4 || mat_(3,2) != 5 || mat_(3,3) != -18 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subtraction assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 -12 -14 0 )\n"
"( -2 0 -3 0 )\n"
"( -11 4 5 -18 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the Rows Schur product assignment operators.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the Schur product assignment operators of the Rows
// specialization. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseGeneralTest::testSchurAssign()
{
using blaze::aligned;
using blaze::unaligned;
using blaze::padded;
using blaze::unpadded;
using blaze::rowMajor;
using blaze::columnMajor;
//=====================================================================================
// Row-major Rows Schur product assignment
//=====================================================================================
{
test_ = "Row-major Rows Schur product assignment (no aliasing)";
initialize();
MT mat{ { 0, 0, 0, 0 },
{ 1, 2, 3, 0 },
{ 0, 0, 0, 0 },
{ 4, 3, 2, 1 },
{ 0, 0, 0, 0 } };
auto rs = blaze::rows( mat, { 3UL, 1UL } );
rs %= blaze::rows( mat_, { 3UL, 1UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 4UL );
if( rs(0,0) != 0 || rs(0,1) != 12 || rs(0,2) != 10 || rs(0,3) != -6 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 12 10 -6 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 || mat(0,3) != 0 ||
mat(1,0) != 0 || mat(1,1) != 2 || mat(1,2) != 0 || mat(1,3) != 0 ||
mat(2,0) != 0 || mat(2,1) != 0 || mat(2,2) != 0 || mat(2,3) != 0 ||
mat(3,0) != 0 || mat(3,1) != 12 || mat(3,2) != 10 || mat(3,3) != -6 ||
mat(4,0) != 0 || mat(4,1) != 0 || mat(4,2) != 0 || mat(4,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 12 10 -6 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major Rows Schur product assignment (aliasing)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 4UL } );
rs %= blaze::rows( mat_, { 2UL, 3UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 7UL );
if( rs(0,0) != 0 || rs(0,1) != 0 || rs(0,2) != -15 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != -32 || rs(1,2) != 45 || rs(1,3) != -60 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 0 -15 0 )\n( 0 -32 45 -60 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 1 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != -15 || mat_(3,3) != 0 ||
mat_(4,0) != 0 || mat_(4,1) != -32 || mat_(4,2) != 45 || mat_(4,3) != -60 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 0 -15 0 )\n"
"( 0 -32 45 -60 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major dense matrix Schur product assignment
//=====================================================================================
{
test_ = "Row-major/row-major dense matrix Schur product assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,rowMajor> mat{ { 0, -1, 0, -2 },
{ 0, 2, 1, 0 } };
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 2 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != -4 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major dense matrix Schur product assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 32UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,1) = -1;
mat(0,3) = -2;
mat(1,1) = 2;
mat(1,2) = 1;
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 2 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != -4 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major dense matrix Schur product assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,1) = -1;
mat(0,3) = -2;
mat(1,1) = 2;
mat(1,2) = 1;
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 2 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != -4 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix Schur product assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,columnMajor> mat{ { 0, -1, 0, -2 },
{ 0, 2, 1, 0 } };
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 2 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != -4 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix Schur product assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,1) = -1;
mat(0,3) = -2;
mat(1,1) = 2;
mat(1,2) = 1;
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 2 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != -4 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix Schur product assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,1) = -1;
mat(0,3) = -2;
mat(1,1) = 2;
mat(1,2) = 1;
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 2 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != -4 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major sparse matrix Schur product assignment
//=====================================================================================
{
test_ = "Row-major/row-major sparse matrix Schur product assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,rowMajor> mat{ { 0, -1, 0, -2 },
{ 0, 2, 1, 0 } };
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 2 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != -4 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major sparse matrix Schur product assignment";
initialize();
auto rs = blaze::rows( mat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,columnMajor> mat{ { 0, -1, 0, -2 },
{ 0, 2, 1, 0 } };
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 2 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != -2 || mat_(2,1) != 0 || mat_(2,2) != -3 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != -4 || mat_(3,2) != 0 || mat_(3,3) != 12 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major Rows Schur product assignment
//=====================================================================================
{
test_ = "Column-major Rows Schur product assignment (no aliasing)";
initialize();
OMT mat{ { 0, 0, 0, 0 },
{ 1, 2, 3, 0 },
{ 0, 0, 0, 0 },
{ 4, 3, 2, 1 },
{ 0, 0, 0, 0 } };
auto rs = blaze::rows( mat, { 3UL, 1UL } );
rs %= blaze::rows( tmat_, { 3UL, 1UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 4UL );
if( rs(0,0) != 0 || rs(0,1) != 12 || rs(0,2) != 10 || rs(0,3) != -6 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 12 10 -6 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 || mat(0,3) != 0 ||
mat(1,0) != 0 || mat(1,1) != 2 || mat(1,2) != 0 || mat(1,3) != 0 ||
mat(2,0) != 0 || mat(2,1) != 0 || mat(2,2) != 0 || mat(2,3) != 0 ||
mat(3,0) != 0 || mat(3,1) != 12 || mat(3,2) != 10 || mat(3,3) != -6 ||
mat(4,0) != 0 || mat(4,1) != 0 || mat(4,2) != 0 || mat(4,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 12 10 -6 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major Rows Schur product assignment (aliasing)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 4UL } );
rs %= blaze::rows( tmat_, { 2UL, 3UL } );
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 4UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 7UL );
if( rs(0,0) != 0 || rs(0,1) != 0 || rs(0,2) != -15 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != -32 || rs(1,2) != 45 || rs(1,3) != -60 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 0 -15 0 )\n( 0 -32 45 -60 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 1 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != -15 || tmat_(3,3) != 0 ||
tmat_(4,0) != 0 || tmat_(4,1) != -32 || tmat_(4,2) != 45 || tmat_(4,3) != -60 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 0 -15 0 )\n"
"( 0 -32 45 -60 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major dense matrix Schur product assignment
//=====================================================================================
{
test_ = "Column-major/row-major dense matrix Schur product assignment (mixed type)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,rowMajor> mat{ { 0, -1, 0, -2 },
{ 0, 2, 1, 0 } };
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 2 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != -4 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major dense matrix Schur product assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 32UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,1) = -1;
mat(0,3) = -2;
mat(1,1) = 2;
mat(1,2) = 1;
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 2 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != -4 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major dense matrix Schur product assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,1) = -1;
mat(0,3) = -2;
mat(1,1) = 2;
mat(1,2) = 1;
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 2 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != -4 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix Schur product assignment (mixed type)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::DynamicMatrix<short,columnMajor> mat{ { 0, -1, 0, -2 },
{ 0, 2, 1, 0 } };
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 2 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != -4 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix Schur product assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 2UL, 4UL, 16UL );
mat = 0;
mat(0,1) = -1;
mat(0,3) = -2;
mat(1,1) = 2;
mat(1,2) = 1;
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 2 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != -4 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix Schur product assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>;
std::unique_ptr<int[]> memory( new int[9UL] );
UnalignedUnpadded mat( memory.get()+1UL, 2UL, 4UL );
mat = 0;
mat(0,1) = -1;
mat(0,3) = -2;
mat(1,1) = 2;
mat(1,2) = 1;
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 2 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != -4 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major sparse matrix Schur product assignment
//=====================================================================================
{
test_ = "Column-major/row-major sparse matrix Schur product assignment";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,rowMajor> mat{ { 0, -1, 0, -2 },
{ 0, 2, 1, 0 } };
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 2 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != -4 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major sparse matrix Schur product assignment";
initialize();
auto rs = blaze::rows( tmat_, { 3UL, 1UL } );
const blaze::CompressedMatrix<int,columnMajor> mat{ { 0, -1, 0, -2 },
{ 0, 2, 1, 0 } };
rs %= mat;
checkRows ( rs , 2UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 3UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 9UL );
if( rs(0,0) != 0 || rs(0,1) != -4 || rs(0,2) != 0 || rs(0,3) != 12 ||
rs(1,0) != 0 || rs(1,1) != 2 || rs(1,2) != 0 || rs(1,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 -4 0 12 )\n( 0 2 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 2 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != -2 || tmat_(2,1) != 0 || tmat_(2,2) != -3 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != -4 || tmat_(3,2) != 0 || tmat_(3,3) != 12 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Schur product assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 2 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 0 -4 0 12 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the Rows multiplication assignment operators.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the multiplication assignment operators of the Rows
// specialization. In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseGeneralTest::testMultAssign()
{
using blaze::aligned;
using blaze::unaligned;
using blaze::padded;
using blaze::unpadded;
using blaze::rowMajor;
using blaze::columnMajor;
//=====================================================================================
// Row-major Rows multiplication assignment
//=====================================================================================
{
test_ = "Row-major Rows multiplication assignment (no aliasing)";
initialize();
MT mat{ { 0, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ 0, 4, 5, -6 },
{ 7, -8, 9, 10 } };
auto rs = blaze::rows( mat, { 2UL, 0UL, 3UL, 1UL } );
rs *= blaze::rows( mat_, { 1UL, 2UL, 2UL, 1UL } );
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 || mat(0,3) != 0 ||
mat(1,0) != -2 || mat(1,1) != 0 || mat(1,2) != -3 || mat(1,3) != 0 ||
mat(2,0) != 6 || mat(2,1) != -2 || mat(2,2) != 9 || mat(2,3) != 0 ||
mat(3,0) != -18 || mat(3,1) != -6 || mat(3,2) != -27 || mat(3,3) != 0 ||
mat(4,0) != 7 || mat(4,1) != -8 || mat(4,2) != 9 || mat(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major Rows multiplication assignment (aliasing)";
initialize();
auto rs = blaze::rows( mat_, { 2UL, 0UL, 3UL, 1UL } );
rs *= blaze::rows( mat_, { 1UL, 2UL, 2UL, 1UL } );
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != -2 || mat_(1,1) != 0 || mat_(1,2) != -3 || mat_(1,3) != 0 ||
mat_(2,0) != 6 || mat_(2,1) != -2 || mat_(2,2) != 9 || mat_(2,3) != 0 ||
mat_(3,0) != -18 || mat_(3,1) != -6 || mat_(3,2) != -27 || mat_(3,3) != 0 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major dense matrix multiplication assignment
//=====================================================================================
{
test_ = "Row-major/row-major dense matrix multiplication assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 2UL, 0UL, 3UL, 1UL } );
const blaze::DynamicMatrix<short,rowMajor> mat{ { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != -2 || mat_(1,1) != 0 || mat_(1,2) != -3 || mat_(1,3) != 0 ||
mat_(2,0) != 6 || mat_(2,1) != -2 || mat_(2,2) != 9 || mat_(2,3) != 0 ||
mat_(3,0) != -18 || mat_(3,1) != -6 || mat_(3,2) != -27 || mat_(3,3) != 0 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major dense matrix multiplication assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 2UL, 0UL, 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 4UL, 4UL, 16UL );
mat = { { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != -2 || mat_(1,1) != 0 || mat_(1,2) != -3 || mat_(1,3) != 0 ||
mat_(2,0) != 6 || mat_(2,1) != -2 || mat_(2,2) != 9 || mat_(2,3) != 0 ||
mat_(3,0) != -18 || mat_(3,1) != -6 || mat_(3,2) != -27 || mat_(3,3) != 0 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/row-major dense matrix multiplication assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 2UL, 0UL, 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>;
std::unique_ptr<int[]> memory( new int[17UL] );
UnalignedUnpadded mat( memory.get()+1UL, 4UL, 4UL );
mat = { { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != -2 || mat_(1,1) != 0 || mat_(1,2) != -3 || mat_(1,3) != 0 ||
mat_(2,0) != 6 || mat_(2,1) != -2 || mat_(2,2) != 9 || mat_(2,3) != 0 ||
mat_(3,0) != -18 || mat_(3,1) != -6 || mat_(3,2) != -27 || mat_(3,3) != 0 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix multiplication assignment (mixed type)";
initialize();
auto rs = blaze::rows( mat_, { 2UL, 0UL, 3UL, 1UL } );
const blaze::DynamicMatrix<short,columnMajor> mat{ { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != -2 || mat_(1,1) != 0 || mat_(1,2) != -3 || mat_(1,3) != 0 ||
mat_(2,0) != 6 || mat_(2,1) != -2 || mat_(2,2) != 9 || mat_(2,3) != 0 ||
mat_(3,0) != -18 || mat_(3,1) != -6 || mat_(3,2) != -27 || mat_(3,3) != 0 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix multiplication assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( mat_, { 2UL, 0UL, 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 4UL, 4UL, 16UL );
mat = { { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != -2 || mat_(1,1) != 0 || mat_(1,2) != -3 || mat_(1,3) != 0 ||
mat_(2,0) != 6 || mat_(2,1) != -2 || mat_(2,2) != 9 || mat_(2,3) != 0 ||
mat_(3,0) != -18 || mat_(3,1) != -6 || mat_(3,2) != -27 || mat_(3,3) != 0 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major dense matrix multiplication assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( mat_, { 2UL, 0UL, 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>;
std::unique_ptr<int[]> memory( new int[17UL] );
UnalignedUnpadded mat( memory.get()+1UL, 4UL, 4UL );
mat = { { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != -2 || mat_(1,1) != 0 || mat_(1,2) != -3 || mat_(1,3) != 0 ||
mat_(2,0) != 6 || mat_(2,1) != -2 || mat_(2,2) != 9 || mat_(2,3) != 0 ||
mat_(3,0) != -18 || mat_(3,1) != -6 || mat_(3,2) != -27 || mat_(3,3) != 0 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major sparse matrix multiplication assignment
//=====================================================================================
{
test_ = "Row-major/row-major sparse matrix multiplication assignment";
initialize();
auto rs = blaze::rows( mat_, { 2UL, 0UL, 3UL, 1UL } );
const blaze::CompressedMatrix<int,rowMajor> mat{ { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != -2 || mat_(1,1) != 0 || mat_(1,2) != -3 || mat_(1,3) != 0 ||
mat_(2,0) != 6 || mat_(2,1) != -2 || mat_(2,2) != 9 || mat_(2,3) != 0 ||
mat_(3,0) != -18 || mat_(3,1) != -6 || mat_(3,2) != -27 || mat_(3,3) != 0 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major/column-major sparse matrix multiplication assignment";
initialize();
auto rs = blaze::rows( mat_, { 2UL, 0UL, 3UL, 1UL } );
const blaze::CompressedMatrix<int,columnMajor> mat{ { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat_, 5UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != -2 || mat_(1,1) != 0 || mat_(1,2) != -3 || mat_(1,3) != 0 ||
mat_(2,0) != 6 || mat_(2,1) != -2 || mat_(2,2) != 9 || mat_(2,3) != 0 ||
mat_(3,0) != -18 || mat_(3,1) != -6 || mat_(3,2) != -27 || mat_(3,3) != 0 ||
mat_(4,0) != 7 || mat_(4,1) != -8 || mat_(4,2) != 9 || mat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major Rows multiplication assignment
//=====================================================================================
{
test_ = "Column-major Rows multiplication assignment (no aliasing)";
initialize();
OMT mat{ { 0, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ 0, 4, 5, -6 },
{ 7, -8, 9, 10 } };
auto rs = blaze::rows( mat, { 2UL, 0UL, 3UL, 1UL } );
rs *= blaze::rows( tmat_, { 1UL, 2UL, 2UL, 1UL } );
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( mat, 5UL );
checkColumns ( mat, 4UL );
checkNonZeros( mat, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat(0,0) != 0 || mat(0,1) != 0 || mat(0,2) != 0 || mat(0,3) != 0 ||
mat(1,0) != -2 || mat(1,1) != 0 || mat(1,2) != -3 || mat(1,3) != 0 ||
mat(2,0) != 6 || mat(2,1) != -2 || mat(2,2) != 9 || mat(2,3) != 0 ||
mat(3,0) != -18 || mat(3,1) != -6 || mat(3,2) != -27 || mat(3,3) != 0 ||
mat(4,0) != 7 || mat(4,1) != -8 || mat(4,2) != 9 || mat(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major Rows multiplication assignment (aliasing)";
initialize();
auto rs = blaze::rows( tmat_, { 2UL, 0UL, 3UL, 1UL } );
rs *= blaze::rows( tmat_, { 1UL, 2UL, 2UL, 1UL } );
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != -2 || tmat_(1,1) != 0 || tmat_(1,2) != -3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 6 || tmat_(2,1) != -2 || tmat_(2,2) != 9 || tmat_(2,3) != 0 ||
tmat_(3,0) != -18 || tmat_(3,1) != -6 || tmat_(3,2) != -27 || tmat_(3,3) != 0 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major dense matrix multiplication assignment
//=====================================================================================
{
test_ = "Column-major/row-major dense matrix multiplication assignment (mixed type)";
initialize();
auto rs = blaze::rows( tmat_, { 2UL, 0UL, 3UL, 1UL } );
const blaze::DynamicMatrix<short,rowMajor> mat{ { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != -2 || tmat_(1,1) != 0 || tmat_(1,2) != -3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 6 || tmat_(2,1) != -2 || tmat_(2,2) != 9 || tmat_(2,3) != 0 ||
tmat_(3,0) != -18 || tmat_(3,1) != -6 || tmat_(3,2) != -27 || tmat_(3,3) != 0 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major dense matrix multiplication assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( tmat_, { 2UL, 0UL, 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,rowMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 4UL, 4UL, 16UL );
mat = { { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != -2 || tmat_(1,1) != 0 || tmat_(1,2) != -3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 6 || tmat_(2,1) != -2 || tmat_(2,2) != 9 || tmat_(2,3) != 0 ||
tmat_(3,0) != -18 || tmat_(3,1) != -6 || tmat_(3,2) != -27 || tmat_(3,3) != 0 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/row-major dense matrix multiplication assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( tmat_, { 2UL, 0UL, 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,rowMajor>;
std::unique_ptr<int[]> memory( new int[17UL] );
UnalignedUnpadded mat( memory.get()+1UL, 4UL, 4UL );
mat = { { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != -2 || tmat_(1,1) != 0 || tmat_(1,2) != -3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 6 || tmat_(2,1) != -2 || tmat_(2,2) != 9 || tmat_(2,3) != 0 ||
tmat_(3,0) != -18 || tmat_(3,1) != -6 || tmat_(3,2) != -27 || tmat_(3,3) != 0 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix multiplication assignment (mixed type)";
initialize();
auto rs = blaze::rows( tmat_, { 2UL, 0UL, 3UL, 1UL } );
const blaze::DynamicMatrix<short,columnMajor> mat{ { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != -2 || tmat_(1,1) != 0 || tmat_(1,2) != -3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 6 || tmat_(2,1) != -2 || tmat_(2,2) != 9 || tmat_(2,3) != 0 ||
tmat_(3,0) != -18 || tmat_(3,1) != -6 || tmat_(3,2) != -27 || tmat_(3,3) != 0 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix multiplication assignment (aligned/padded)";
initialize();
auto rs = blaze::rows( tmat_, { 2UL, 0UL, 3UL, 1UL } );
using AlignedPadded = blaze::CustomMatrix<int,aligned,padded,columnMajor>;
std::unique_ptr<int[],blaze::Deallocate> memory( blaze::allocate<int>( 64UL ) );
AlignedPadded mat( memory.get(), 4UL, 4UL, 16UL );
mat = { { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != -2 || tmat_(1,1) != 0 || tmat_(1,2) != -3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 6 || tmat_(2,1) != -2 || tmat_(2,2) != 9 || tmat_(2,3) != 0 ||
tmat_(3,0) != -18 || tmat_(3,1) != -6 || tmat_(3,2) != -27 || tmat_(3,3) != 0 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major dense matrix multiplication assignment (unaligned/unpadded)";
initialize();
auto rs = blaze::rows( tmat_, { 2UL, 0UL, 3UL, 1UL } );
using UnalignedUnpadded = blaze::CustomMatrix<int,unaligned,unpadded,columnMajor>;
std::unique_ptr<int[]> memory( new int[17UL] );
UnalignedUnpadded mat( memory.get()+1UL, 4UL, 4UL );
mat = { { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != -2 || tmat_(1,1) != 0 || tmat_(1,2) != -3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 6 || tmat_(2,1) != -2 || tmat_(2,2) != 9 || tmat_(2,3) != 0 ||
tmat_(3,0) != -18 || tmat_(3,1) != -6 || tmat_(3,2) != -27 || tmat_(3,3) != 0 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major sparse matrix multiplication assignment
//=====================================================================================
{
test_ = "Column-major/row-major sparse matrix multiplication assignment";
initialize();
auto rs = blaze::rows( tmat_, { 2UL, 0UL, 3UL, 1UL } );
const blaze::CompressedMatrix<int,rowMajor> mat{ { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != -2 || tmat_(1,1) != 0 || tmat_(1,2) != -3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 6 || tmat_(2,1) != -2 || tmat_(2,2) != 9 || tmat_(2,3) != 0 ||
tmat_(3,0) != -18 || tmat_(3,1) != -6 || tmat_(3,2) != -27 || tmat_(3,3) != 0 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Column-major/column-major sparse matrix multiplication assignment";
initialize();
auto rs = blaze::rows( tmat_, { 2UL, 0UL, 3UL, 1UL } );
const blaze::CompressedMatrix<int,columnMajor> mat{ { 0, 1, 0, 0 },
{ -2, 0, -3, 0 },
{ -2, 0, -3, 0 },
{ 0, 1, 0, 0 } };
rs *= mat;
checkRows ( rs , 4UL );
checkColumns ( rs , 4UL );
checkNonZeros( rs , 8UL );
checkRows ( tmat_, 5UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 12UL );
if( rs(0,0) != 6 || rs(0,1) != -2 || rs(0,2) != 9 || rs(0,3) != 0 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 || rs(1,3) != 0 ||
rs(2,0) != -18 || rs(2,1) != -6 || rs(2,2) != -27 || rs(2,3) != 0 ||
rs(3,0) != -2 || rs(3,1) != 0 || rs(3,2) != -3 || rs(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 6 -2 9 0 )\n"
"( 0 0 -3 0 )\n"
"( -18 -6 -27 0 )\n"
"( -2 0 -3 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != -2 || tmat_(1,1) != 0 || tmat_(1,2) != -3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 6 || tmat_(2,1) != -2 || tmat_(2,2) != 9 || tmat_(2,3) != 0 ||
tmat_(3,0) != -18 || tmat_(3,1) != -6 || tmat_(3,2) != -27 || tmat_(3,3) != 0 ||
tmat_(4,0) != 7 || tmat_(4,1) != -8 || tmat_(4,2) != 9 || tmat_(4,3) != 10 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Multiplication assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( -2 0 -3 0 )\n"
"( 6 -2 9 0 )\n"
"( -18 -6 -27 0 )\n"
"( 7 -8 9 10 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//=================================================================================================
//
// UTILITY FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Initialization of all member matrices.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function initializes all member matrices to specific predetermined values.
*/
void DenseGeneralTest::initialize()
{
// Initializing the row-major dynamic matrix
mat_.reset();
mat_(1,1) = 1;
mat_(2,0) = -2;
mat_(2,2) = -3;
mat_(3,1) = 4;
mat_(3,2) = 5;
mat_(3,3) = -6;
mat_(4,0) = 7;
mat_(4,1) = -8;
mat_(4,2) = 9;
mat_(4,3) = 10;
// Initializing the column-major dynamic matrix
tmat_.reset();
tmat_(1,1) = 1;
tmat_(2,0) = -2;
tmat_(2,2) = -3;
tmat_(3,1) = 4;
tmat_(3,2) = 5;
tmat_(3,3) = -6;
tmat_(4,0) = 7;
tmat_(4,1) = -8;
tmat_(4,2) = 9;
tmat_(4,3) = 10;
}
//*************************************************************************************************
} // namespace rows
} // namespace views
} // namespace mathtest
} // namespace blazetest
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running Rows dense general test (part 1)..." << std::endl;
try
{
RUN_ROWS_DENSEGENERAL_TEST;
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during Rows dense general test (part 1):\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| 41.591575 | 117 | 0.37364 | [
"vector"
] |
912e5513a9e7eb5f769787c2e307a375c64aefe6 | 736 | hpp | C++ | OpenTimer/ot/timer/scc.hpp | Ace-Ma/LSOracle | 6e940906303ef6c2c6b96352f44206567fdd50d3 | [
"MIT"
] | null | null | null | OpenTimer/ot/timer/scc.hpp | Ace-Ma/LSOracle | 6e940906303ef6c2c6b96352f44206567fdd50d3 | [
"MIT"
] | null | null | null | OpenTimer/ot/timer/scc.hpp | Ace-Ma/LSOracle | 6e940906303ef6c2c6b96352f44206567fdd50d3 | [
"MIT"
] | null | null | null | #ifndef OT_TIMER_SCC_HPP_
#define OT_TIMER_SCC_HPP_
#include <vector>
#include <optional>
namespace ot {
class Pin;
// ------------------------------------------------------------------------------------------------
// Class: SCC
// strongly connected component
class SCC {
friend class Timer;
public:
SCC(std::vector<Pin*>&&);
private:
std::optional<std::list<SCC>::iterator> _satellite;
std::vector<Pin*> _pins;
std::string _dump() const;
bool _is_entry(const Pin&) const;
bool _is_exit(const Pin&) const;
void _clear();
void _unloop(Pin&);
void _unloop();
};
}; // end of namespace ot. -----------------------------------------------------------------------
#endif
| 15.659574 | 99 | 0.490489 | [
"vector"
] |
91388c0486250f5b8065d4b69053877ef61d06e0 | 5,858 | cpp | C++ | src/test/pow_tests.cpp | BTCfork/hardfork_prototype_1_mvf | 7730366fd6aa853f0c40d7f91699c415b3c9987e | [
"MIT"
] | 2 | 2017-01-02T20:12:35.000Z | 2018-04-30T00:02:11.000Z | src/test/pow_tests.cpp | BTCfork/hardfork_prototype_1_mvf | 7730366fd6aa853f0c40d7f91699c415b3c9987e | [
"MIT"
] | 24 | 2016-10-15T09:03:30.000Z | 2017-11-19T02:13:26.000Z | src/test/pow_tests.cpp | BTCfork/hardfork_prototype_1_mvf | 7730366fd6aa853f0c40d7f91699c415b3c9987e | [
"MIT"
] | 4 | 2016-09-27T13:39:13.000Z | 2021-01-05T09:38:14.000Z | // Copyright (c) 2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "chainparams.h"
#include "pow.h"
#include "random.h"
#include "util.h"
#include "test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)
/* Test calculation of next difficulty target with no constraints applying */
BOOST_AUTO_TEST_CASE(get_next_work)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1261130161; // Block #30240
CBlockIndex pindexLast;
pindexLast.nHeight = 32255;
pindexLast.nTime = 1262152739; // Block #32255
pindexLast.nBits = 0x1d00ffff;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00d86a);
}
/* Test the constraint on the upper bound for next work */
BOOST_AUTO_TEST_CASE(get_next_work_pow_limit)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1231006505; // Block #0
CBlockIndex pindexLast;
pindexLast.nHeight = 2015;
pindexLast.nTime = 1233061996; // Block #2015
pindexLast.nBits = 0x1d00ffff;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00ffff);
}
/* Test the constraint on the lower bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1279008237; // Block #66528
CBlockIndex pindexLast;
pindexLast.nHeight = 68543;
pindexLast.nTime = 1279297671; // Block #68543
pindexLast.nBits = 0x1c05a3f4;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1c0168fd);
}
/* Test the constraint on the upper bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
int64_t nLastRetargetTime = 1263163443; // NOTE: Not an actual block time
CBlockIndex pindexLast;
pindexLast.nHeight = 46367;
pindexLast.nTime = 1269211443; // Block #46367
pindexLast.nBits = 0x1c387f6f;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00e1fd);
}
BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus();
std::vector<CBlockIndex> blocks(10000);
for (int i = 0; i < 10000; i++) {
blocks[i].pprev = i ? &blocks[i - 1] : NULL;
blocks[i].nHeight = i;
blocks[i].nTime = 1269211443 + i * params.nPowTargetSpacing;
blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */
blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0);
}
for (int j = 0; j < 1000; j++) {
CBlockIndex *p1 = &blocks[GetRand(10000)];
CBlockIndex *p2 = &blocks[GetRand(10000)];
CBlockIndex *p3 = &blocks[GetRand(10000)];
int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, params);
BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());
}
}
// MVF-BU begin
/* added unit test after we found that on regtest, difficulty calculation
can lead to overflow of 256-bit integer. Here an excessive retarget time
is set in order to trigger the overflow case, in which case the previous
difficulty is re-used. */
BOOST_AUTO_TEST_CASE(MVFCheckOverflowCalculation_test)
{
SelectParams(CBaseChainParams::REGTEST);
const Consensus::Params& params = Params().GetConsensus();
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); // MVF-BU moved here
// test scenario post fork
FinalActivateForkHeight = 2016;
int64_t nLastRetargetTime = 7; // Force an excessive retarget time to trigger overflow
CBlockIndex pindexLast;
pindexLast.nHeight = 2024;
pindexLast.nTime = 1279297671; // Block #68543
pindexLast.nBits = 0x207aaaaa; // Almost overflowing already
// an overflow causes the POW limit to be returned
// need to set -force-retarget, otherwise cannot test overflow
// because it would never reach the computation
SoftSetBoolArg("-force-retarget", true);
BOOST_CHECK_EQUAL(CalculateMVFNextWorkRequired(&pindexLast, nLastRetargetTime, params), bnPowLimit.GetCompact());
}
/* added unit test for fork reset. doesn't test easily in regtest
* because takes some retargets before raising bits off the limit */
BOOST_AUTO_TEST_CASE(MVFCheckCalculateMVFResetWorkRequired)
{
SelectParams(CBaseChainParams::REGTEST);
const Consensus::Params& params = Params().GetConsensus();
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); // MVF-BU moved here
// define last block
CBlockIndex pindexLast;
pindexLast.nHeight = 68543;
pindexLast.nTime = 1279297671; // Block #68543
pindexLast.nBits = 0x1c05a3f4;
// retarget time for test
int64_t nLastRetargetTime = pindexLast.nTime - (params.nPowTargetSpacing * params.DifficultyAdjustmentInterval());
// force retargeting in CalculateMVFNextWorkRequired
SoftSetBoolArg("-force-retarget", true);
// test for drop factor
FinalDifficultyDropFactor = HARDFORK_DROPFACTOR_REGTEST;
BOOST_CHECK_EQUAL(CalculateMVFResetWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1c168fcf);
}
// MVF-BU end
BOOST_AUTO_TEST_SUITE_END()
| 38.287582 | 118 | 0.73421 | [
"vector"
] |
913c0044f7f1f914a122ed74114555d967c94697 | 680 | cpp | C++ | 2015/day12/p1/main.cpp | jbaldwin/adventofcode2019 | bdc333330dd5e36458a49f0b7cd64d462c9988c7 | [
"MIT"
] | null | null | null | 2015/day12/p1/main.cpp | jbaldwin/adventofcode2019 | bdc333330dd5e36458a49f0b7cd64d462c9988c7 | [
"MIT"
] | null | null | null | 2015/day12/p1/main.cpp | jbaldwin/adventofcode2019 | bdc333330dd5e36458a49f0b7cd64d462c9988c7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <lib/file_util.hpp>
int main(int argc, char* argv[])
{
std::vector<std::string> args{argv, argv + argc};
if(args.size() != 2)
{
std::cout << args[0] << " <input_file>" << std::endl;
return 1;
}
auto json = file::read(args[1]);
int64_t total{0};
for(std::size_t i = 0; i < json.length(); ++i)
{
try
{
total += std::stol(json.substr(i));
while(json[i] == '-' || std::isdigit(json[i]))
{
++i;
}
}
catch(...) { }
}
std::cout << total << '\n';
return 0;
}
| 17.894737 | 61 | 0.445588 | [
"vector"
] |
913c02f26c6d5463f804bf0b8d96e8282e6a0c5e | 27,403 | cpp | C++ | src/test.cpp | deruncie/GridLMM | b0e5a9d60ef7ddabd2ad1df105bb452a00327f38 | [
"MIT"
] | 33 | 2018-07-24T14:58:40.000Z | 2021-11-25T09:51:48.000Z | src/test.cpp | deruncie/GridLMM | b0e5a9d60ef7ddabd2ad1df105bb452a00327f38 | [
"MIT"
] | 11 | 2019-02-12T17:37:35.000Z | 2021-09-17T01:17:39.000Z | src/test.cpp | deruncie/GridLMM | b0e5a9d60ef7ddabd2ad1df105bb452a00327f38 | [
"MIT"
] | 7 | 2019-05-31T02:00:46.000Z | 2021-06-04T23:26:00.000Z | #include <RcppEigen.h>
using Eigen::Map; // 'Eigen::Maps' rather than copies
using Eigen::MatrixXd; // variable size matrix, double precision
using Eigen::VectorXd; // variable size vector, double precision
using Eigen::ArrayXd; // variable size vector, double precision
typedef Eigen::SparseMatrix<double> SpMat;
typedef Eigen::Map<SpMat> MSpMat;
using namespace Rcpp;
using namespace Eigen;
// [[Rcpp::export()]]
MatrixXd chol_update2(MatrixXd L, MatrixXd X, int sign) {
int n = L.rows();
Map<MatrixXd> L_new(L.data(),n,n);
for(int i = 0; i < X.cols(); i++){
for(int k = 0; k < n; k++){
double L_kk = L_new.coeffRef(k,k);
double x_k = X.coeffRef(k,i);
double r = sqrt(L_kk*L_kk + sign * x_k*x_k);
double c = r / L_kk;
double s = x_k / L_kk;
L_new.coeffRef(k,k) = r;
if(k < (n-1)) {
L_new.block(k+1,k,n-k-1,1) = (L.block(k+1,k,n-k-1,1) + sign * s * X.block(k+1,i,n-k-1,1))/c;
X.block(k+1,i,n-k-1,1) = c*X.block(k+1,i,n-k-1,1) - s*L_new.block(k+1,k,n-k-1,1);
}
}
}
return(L_new);
}
// [[Rcpp::export()]]
MatrixXd chol_update2s(MatrixXd L, MatrixXd X, int sign) {
int n = L.rows();
Map<MatrixXd> L_new(L.data(),n,n);
for(int i = 0; i < X.cols(); i++){
int sum_nzero = 0;
// Rcout << X << std::endl << std::endl;
for(int k = 0; k < n; k++){
double x_k = X.coeffRef(k,i);
// if(x_k != 0.0) {
if(std::abs(x_k - 0.0) > 1e-10) {
// Rcout << i << " " << k << " " << x_k << std::endl;
sum_nzero++;
double L_kk = L_new.coeffRef(k,k);
double r = sqrt(L_kk*L_kk + sign * x_k*x_k);
double c = r / L_kk;
double s = x_k / L_kk;
L_new.coeffRef(k,k) = r;
if(k < (n-1)) {
L_new.block(k+1,k,n-k-1,1) = (L.block(k+1,k,n-k-1,1) + sign * s * X.block(k+1,i,n-k-1,1))/c;
X.block(k+1,i,n-k-1,1) = c*X.block(k+1,i,n-k-1,1) - s*L_new.block(k+1,k,n-k-1,1);
}
}
}
// Rcout << sum_nzero << std::endl;
}
return(L_new);
}
//
//
// MatrixXd block_cholesky2(MatrixXd L_A, // Cholesky L matrix for A matrix (lower-left block)
// MatrixXd B, MatrixXd D){
// // block cholesky decomposition of a symmetric square matrix: [A B;B^t D]
// // returns L st L*L^T = original matrix
// MatrixXd L_A_invB = L_A.triangularView<Lower>().solve(B);
// MatrixXd Q = D - L_A_invB.transpose() * L_A_invB;
// Eigen::LLT<MatrixXd> llt_of_Q(Q);
// MatrixXd QL = llt_of_Q.matrixL();
// MatrixXd L(L_A.rows() + D.rows(),L_A.rows() + D.rows());
// MatrixXd z = MatrixXd::Zero(L_A.rows(),D.cols());
// L << L_A,z,L_A_invB.transpose(),QL;
// return(L);
// }
//
// // [[Rcpp::export()]]
// VectorXd log_det_of_XtX2(
// Map<MatrixXd> X_cov,
// Rcpp::List X_tests,
// ArrayXi X_indices // 1-based index of the tests to actually calculate
// ){
//
// int b_x = X_tests.length();
// int n = X_cov.rows();
//
// MatrixXd A = X_cov.transpose() * X_cov;
// Eigen::LLT<MatrixXd> llt_of_A(A);
// MatrixXd L_A = llt_of_A.matrixL();
//
// std::vector<Map<MatrixXd> > Xs;
// for(int i = 0; i < b_x; i++){
// Xs.push_back(as<Map<MatrixXd> >(X_tests[i]));
// if(Xs[i].cols() != Xs[0].cols()) stop("Different numbers of columns in X_list matrices");
// }
// int p = X_indices.size();
//
// if(p == 0){
// VectorXd log_det(1);
// log_det(0) = 2*L_A.diagonal().array().log().sum();
// return(log_det);
// }
//
//
// VectorXd log_det(p);
// MatrixXd Xi(n,b_x);
// for(int i = 0; i < p; i++){
// for(int j = 0; j < b_x; j++){
// Xi.col(j) = Xs[j].col(X_indices[i]-1);
// }
//
// MatrixXd B = X_cov.transpose() * Xi;
// MatrixXd D = Xi.transpose() * Xi;
// MatrixXd L = block_cholesky2(L_A, B, D);
//
// log_det(i) = 2*L.diagonal().array().log().sum();
// }
//
// return(log_det);
// }
//
// void load_list(
// Rcpp::List X_list_,
// ArrayXi X_indices
// ) {
//
// int b_x = X_list_.size();
// // Process X_list
// std::vector<Map<MatrixXd> > X_list;
// for(int j = 0; j < b_x; j++) {
// X_list.push_back(as<Map<MatrixXd> >(X_list_[j]));
// if(X_list[j].cols() != X_list[0].cols()) stop("Different numbers of columns in X_list matrices");
// // if(X_list[j].rows() != n) stop("Wrong number of rows in X_list matrices");
// }
// int n = X_list[0].rows();
// int p = X_indices.size();
//
// MatrixXd X_std(n,p*b_x);
// for(int i = 0; i < p; i++) {
// // reform X_list into a wide matrix of n x b_x design matrices
// int index_i = X_indices[i]-1;
// for(int j = 0; j < b_x; j++) {
// X_std.col(i*b_x + j) = X_list[j].col(index_i);
// }
// }
//
// // Rcout << X_list[0].col(X_list[0].cols()-1) << std::endl;
// // Rcout << X_list[0].cols() << std::endl;
// }
//
// MatrixXd ginv_LDLt(Eigen::LDLT<MatrixXd,Lower> ldlt_K, MatrixXd Y) {
// if(Y.rows() != ldlt_K.rows()) stop("Wrong dimensions of Y");
// MatrixXd L = ldlt_K.matrixL();
// MatrixXd I = MatrixXd::Identity(ldlt_K.rows(), ldlt_K.rows());
// MatrixXd P = ldlt_K.transpositionsP() * I;
// VectorXd d = ldlt_K.vectorD();
// int p = d.size();
// VectorXd dinv = VectorXd::Zero(p);
// for(int i = 0; i < p; i++) {
// if(d[i] > 1e-9) dinv[i] = 1/d[i];
// }
// MatrixXd LinvP = L.triangularView<Lower>().solve(P);
// return(LinvP.transpose() * dinv.asDiagonal() * LinvP*Y);
// }
//
// // [[Rcpp::export()]]
// MatrixXd solve_LDLt(Map<MatrixXd> K, Map<MatrixXd> y){
// // MatrixXd K = X.transpose()*X;
// Eigen::LDLT<MatrixXd,Lower> ldlt_K(K);
// // MatrixXd Z = ldlt_K.solve(y);
// MatrixXd Z = ginv_LDLt(ldlt_K,y);
// return(Z);
// }
//
//
// // [[Rcpp::export()]]
// List LDLt_downdate(Map<MatrixXd> K, Map<MatrixXd> X) {
// Eigen::LDLT<MatrixXd,Lower> ldlt_K(K);
// int k = X.cols();
// int p = X.rows();
// // Rcout << ldlt_K.isPositive() << std::endl;
// for(int i = 0; i< k; i++) {
// // int sign = 1;
// // if(X.col(i).minCoeff() < 0) sign = -1;
// // ldlt_K.rankUpdate(X.col(i).cwiseAbs().cwiseSqrt(),sign);
// ldlt_K.rankUpdate(X.col(i));
// // Rcout << ldlt_K.isPositive() << std::endl;
// }
// // Rcout << ldlt_K.isPositive() << std::endl;
// ldlt_K.setZero();
// MatrixXd L = ldlt_K.matrixL();
// VectorXd d = ldlt_K.vectorD();
// MatrixXd I = MatrixXd::Identity(ldlt_K.rows(), ldlt_K.rows());
// MatrixXd P = ldlt_K.transpositionsP() * I;
// MatrixXd K2 = ldlt_K.reconstructedMatrix();
// return(Rcpp::List::create(Named("L") = L,
// Named("d") = d,
// Named("P") = P,
// Named("K2") = K2
// ));
// }
// //
// // // [[Rcpp::export()]]
// // VectorXd Calculate_qt(Map<MatrixXd> X, Map<MatrixXd> beta,Map<VectorXd> lambdas){
// // // This function calculates tr(X(t(X) %*% X + n*lambda*W^-)^- t(X)), which is the number of effective parameters, part of the calculation of GCV.
// // // It uses the fact that W^- is diagonal, with most elements zero, so several low-rank updates can be made to LDLt = t(X) %*% X
// // int n = X.rows();
// // int p = beta.rows();
// // if(X.cols() != p) stop("Wrong dimensions of beta or X");
// // int l = lambdas.size();
// // if(beta.cols() != l) stop("Wrong length of lambdas");
// // MatrixXd nlambda_beta_abs =(1.0/n)*(beta*(lambdas.cwiseInverse().asDiagonal())).cwiseAbs();
// // MatrixXd K = X.transpose() * X;
// // Eigen::LDLT<MatrixXd,Lower> ldlt_K_base(K);
// // VectorXd results = VectorXd::Zero(l);
// // for(int i = 0; i < l; i++) {
// // Eigen::LDLT<MatrixXd,Lower> ldlt_K = ldlt_K_base;
// // for(int j = 0; j < p; j++) {
// // if(nlambda_beta_abs.coeffRef(j,i) > 0) {
// // VectorXd w = VectorXd::Zero(p);
// // w[j] = 1.0/std::sqrt(nlambda_beta_abs.coeffRef(j,i));
// // ldlt_K.rankUpdate(w);
// // }
// // }
// // MatrixXd S = X * ldlt_K.solve(X.transpose());
// // results[i] = S.diagonal().sum();
// // }
// // return(results);
// // }
//
//
// // [[Rcpp::export()]]
// List LDLT_base(MatrixXd K) {
// LDLT<MatrixXd,Lower> ldlt(K);
// MatrixXd mLDLT = ldlt.matrixLDLT();
// // Rcout << m << std::endl;
// // MatrixXd L = ldlt.matrixL();
// // VectorXd d = ldlt.vectorD();
// VectorXi t = ldlt.transpositionsP().indices();
// return(Rcpp::List::create(Named("mLDLT") = mLDLT,
// // Named("L") = L,
// // Named("d") = d,
// Named("t") = t));
// }
//
// // [[Rcpp::export()]]
// List LDLT_u1(MatrixXd K,MatrixXd X) {
// LDLT<MatrixXd,Lower> ldlt(K);
// int k = X.cols();
// for(int i = 0; i < k; i++) {
// ldlt.rankUpdate(X.col(i));
// }
// MatrixXd mLDLT = ldlt.matrixLDLT();
// // Rcout << m << std::endl;
// // MatrixXd L = ldlt.matrixL();
// // VectorXd d = ldlt.vectorD();
// VectorXi t = ldlt.transpositionsP().indices();
// return(Rcpp::List::create(Named("mLDLT") = mLDLT,
// // Named("L") = L,
// // Named("d") = d,
// Named("t") = t));
// }
//
// // [[Rcpp::export()]]
// List LDLT_update(List LDLt_old, MatrixXd X) {
// int k = X.cols();
// int n = X.rows();
// // Rcout << n << std::endl;
// MatrixXd mLDLT = as<MatrixXd>(LDLt_old["mLDLT"]);
// MatrixXd L; //= as<MatrixXd>(LDLt_old["L"]);
// VectorXd d; //= as<VectorXd>(LDLt_old["d"]);
// VectorXi t = as<VectorXi>(LDLt_old["t"]);
// // Rcout << L << std::endl;
// // Rcout << d << std::endl;
// LDLT<MatrixXd,Lower> ldlt(n);
// ldlt.matrixLDLT().const_cast_derived() = mLDLT;
// ldlt.transpositionsP().indices().const_cast_derived() = t;
// // t = ldlt.transpositionsP().indices();
// // Rcout << t << std::endl;
// // d = ldlt.vectorD();
// // Rcout << d << std::endl;
// // ldlt.matrixL().nestedExpression().const_cast_derived() = L;
// // ldlt.vectorD().nestedExpression().const_cast_derived() = d.asDiagonal();
// // d = ldlt.vectorD();
// // Rcout << d << std::endl;
// // L = ldlt.matrixL();
// // Rcout << L << std::endl;
// // ldlt.vectorD().fill(d);
// // ldlt.vectorD().coeff(0) = d(0);
// // ldlt.vectorD().nestByValue().const_cast_derived() = d;
// // ldlt.vectorD().nestedExpression().const_cast_derived() = d.asDiagonal();
// // diagonal().const_cast_derived() = d;
// // const_cast_derived() = d;
// // nestedExpression().const_cast_derived() = d.asDiagonal();
// // ldlt.matrixL().nestedExpression().const_cast_derived() = L;
// // nestedExpression().const_cast_derived() = d;
// // L = ldlt.matrixL();
// // Rcout << L << std::endl;
// // d = ldlt.vectorD();
// // Rcout << d << std::endl;
// // t = ldlt.transpositionsP().indices();
// // Rcout << t << std::endl;
// // L = ldlt.matrixL();
// // Rcout << L << std::endl;
//
// // for(int i = 0; i < k; i++) {
// // ldlt.rankUpdate(X.col(i));
// // }
// L = ldlt.matrixL();
// d = ldlt.vectorD();
// t = ldlt.transpositionsP().indices();
// return(Rcpp::List::create(Named("L") = L,
// Named("d") = d,
// Named("t") = t));
// }
//
//
// // [[Rcpp::export()]]
// void asdf(VectorXi indices) {
// PermutationMatrix<Dynamic> P(indices);
// MatrixXd I = MatrixXd::Identity(indices.size(),indices.size());
// MatrixXd M = P*I;
// Rcout << M << std::endl;
// Rcout << P.indices() << std::endl;
// }
//
// // [[Rcpp::export()]]
// MatrixXd LDLt2(MatrixXd X) {
// LDLT<MatrixXd,Lower> ldlt(X);
// // ldlt.compute();
// MatrixXd I = MatrixXd::Identity(ldlt.rows(), ldlt.rows());
// MatrixXd P = ldlt.transpositionsP() * I;
// Rcout << P << std::endl;
// Rcout << ldlt.transpositionsP().coeff(0) << std::endl;
// Rcout << ldlt.transpositionsP().coeff(1) << std::endl;
// Rcout << ldlt.transpositionsP().coeff(2) << std::endl;
// Eigen::Transpositions<Dynamic> P2(3);
// VectorXi p(3);
// p << 2,1,2;
// P2.indices() = p;
// ldlt.transpositionsP().indices().const_cast_derived() = p;
// Rcout << ldlt.transpositionsP().coeff(0) << std::endl;
// Rcout << ldlt.transpositionsP().coeff(1) << std::endl;
// Rcout << ldlt.transpositionsP().coeff(2) << std::endl;
// // const_cast_derived() = P2;
// P = ldlt.transpositionsP() * I;
// Rcout << P << std::endl;
// // ldlt.transpositionsP().nestedExpression().
// // ldlt.transpositionsP().coeff(1) = 1;
// // ldlt.transpositionsP().coeff(2) = 1;
// // ldlt.matrixU().nestedExpression().const_cast_derived()
// MatrixXd L = ldlt.matrixL();
// VectorXd d = ldlt.vectorD();
// // VectorXd p = ldlt.transpositionsP().indices().cast(double);
// // Rcout << p << std::endl;
// // Rcout << ldlt.vectorD() << std::endl;
// // Rcout << ldlt.transpositionsP() << std::endl;
// return(ldlt.matrixL());
// }
//
// // // [[Rcpp::export()]]
// // List LKLt_update(List LDLt_old,MatrixXd X) {
// // MatrixXd L = as<MatrixXd>(LDLt_old["L"]);
// // MSpMat P = as<MSpMat>(LDLt_old["P"]);
// // VectorXd d = as<VectorXd>(LDLt_old["d"]);
// // int n = X.rows();
// // LDLT<MatrixXd,Lower> ldlt(n);
// // ldlt.matrixL().nestedExpression().const_cast_derived() = L;
// // ldlt.vectorD().nestedExpression().const_cast_derived() = d;
// // // ldlt.transpositionsP().indices().const_cast_derived()
// // }
//
// // [[Rcpp::export()]]
// MatrixXd my_cholUpdate(Map<MatrixXd> R, MatrixXd X) {
// int n = X.rows();
// LLT<MatrixXd,Lower> llt(n);
// // llt.matrixL().nestedExpression().const_cast_derived() = VectorXd::Ones(n).asDiagonal();
// llt.matrixL().nestedExpression().const_cast_derived() = R.transpose();
// for(int i = 0; i < X.cols(); i++) {
// llt.rankUpdate(X.col(i));
// }
// MatrixXd L = llt.matrixL();
// return(L);
// }
//
// // // [[Rcpp::export()]]
// // MatrixXd usemyChol1(Map<MatrixXd> R) {
// // int n = R.rows();
// // LLT<Ref<MatrixXd>,Lower> llt(n);
// // llt.matrixL().nestedExpression().const_cast_derived() = R.transpose();
// // MatrixXd L = llt.matrixL();
// // return(L);
// // }
// // // [[Rcpp::export()]]
// // MatrixXd usemyChol2(Map<MatrixXd> R) {
// // // int n = R.rows();
// // LLT<MatrixXd,Lower> llt(R);
// // llt.matrixL().nestedExpression().const_cast_derived() = R.transpose();
// // MatrixXd L = llt.matrixL();
// // return(L);
// // }
// // // [[Rcpp::export()]]
// // void usemyChol3(MatrixXd R) {
// // // int n = R.rows();
// // // LLT<MatrixXd,Lower> llt(n);
// // // llt.matrixL().nestedExpression().const_cast_derived() = R.transpose();
// // // MatrixXd L = llt.matrixL();
// // // MatrixXd L = R;
// // // return(L);
// // }
// // // [[Rcpp::export()]]
// // void usemyChol4(Map<MatrixXd> R) {
// // // R.triangularView<Lower>().nestedExpression().
// // // int n = R.rows();
// // // LLT<MatrixXd,Lower> llt(n);
// // // llt.matrixL().nestedExpression().const_cast_derived() = R.transpose();
// // // MatrixXd L = llt.matrixL();
// // // Map<MatrixXd> L = R;
// // // return(R);
// // }
//
//
// // void sdi(Rcpp::List A, IntegerVector b){
// // IntegerVector a(0);
// // for(int i = 0; i < A.size(); i++) {
// // Rcout << Rf_isInteger(A[i]) << std::endl;
// // if(Rf_isInteger(A[i])) {
// // a = as<IntegerVector>(A[i]);
// // }
// // }
// // Rcout << a << std::endl;
// // // Rcout << Rf_isInteger(a_) << std::endl;
// // // if(Rf_isInteger(a_)){
// // // IntegerVector a = as<IntegerVector>(a_);
// // // return(setdiff(a,b));
// // // }
// // // return(b);
// // }
//
//
// // void chol_update_R_inplace2(MatrixXd &R, MatrixXd X, VectorXd weights) {
// // int n = R.rows();
// // if(X.rows() != n) stop("Wrong dimension of X for downdating R");
// // if(weights.size() != X.cols()) stop("wrong length of weights for downdating R");
// // for(int i = 0; i < X.cols(); i++){
// // VectorXd Xi = X.col(i);
// // double weights_i = weights[i];
// // for(int k = 0; k < n; k++){
// // double R_kk = R.coeffRef(k,k);
// // double x_k = Xi.coeffRef(k);
// // double r = sqrt(R_kk*R_kk + weights_i * x_k*x_k);
// // double c = r / R_kk;
// // double s = x_k / R_kk;
// // R.coeffRef(k,k) = r;
// // if(k < (n-1)) {
// // for(int j=k+1; j<n; j++) {
// // double R_kj = R.coeffRef(k,j);
// // double X_ij = Xi.coeff(j);
// // R_kj += weights_i * s * X_ij;
// // R_kj /= c;
// // X_ij *= c;
// // X_ij -= s*R_kj;
// // R.coeffRef(k,j) = R_kj;
// // Xi.coeffRef(j) = X_ij;
// // }
// // // R.block(k,k+1,1,n-k-1) = (R.block(k,k+1,1,n-k-1) + weights_i * s * Xi.tail(n-k-1).transpose())/c;
// // // Xi.tail(n-k-1) = c*Xi.tail(n-k-1) - s*R.block(k,k+1,1,n-k-1).transpose();
// // // R.block(k,k+1,1,n-k-1) += weights_i * s * Xi.tail(n-k-1).transpose();
// // // R.block(k,k+1,1,n-k-1) /= c;
// // // Xi.tail(n-k-1) *= c;
// // // Xi.tail(n-k-1) -= s*R.block(k,k+1,1,n-k-1).transpose();
// // }
// // }
// // }
// // }
// //
// //
// // // [[Rcpp::export()]]
// // MatrixXd chol_update_L2(MatrixXd L, MatrixXd X, VectorXd weights) {
// // MatrixXd R = L.transpose();
// // chol_update_R_inplace2(R,X,weights);
// // return(R.transpose());
// // }
// //
// // // [[Rcpp::export()]]
// // MatrixXd chol_update_R2(MatrixXd R, MatrixXd X, VectorXd weights) {
// // chol_update_R_inplace2(R,X,weights);
// // return(R);
// // }
// //
// // void chol_update_L_inplace2(MatrixXd &L, MatrixXd X, VectorXd weights) {
// // int n = L.rows();
// // if(X.rows() != n) stop("Wrong dimension of X for downdating L");
// // if(weights.size() != X.cols()) stop("wrong length of weights for downdating L");
// // for(int i = 0; i < X.cols(); i++){
// // VectorXd Xi = X.col(i);
// // double weights_i = weights[i];
// // for(int k = 0; k < n; k++){
// // double L_kk = L.coeffRef(k,k);
// // double x_k = Xi.coeffRef(k);
// // double r = sqrt(L_kk*L_kk + weights_i * x_k*x_k);
// // double c = r / L_kk;
// // double s = x_k / L_kk;
// // L.coeffRef(k,k) = r;
// // if(k < (n-1)) {
// // for(int j=k+1; j<n; j++) {
// // double L_jk = L.coeffRef(j,k);
// // double X_ij = Xi.coeff(j);
// // L_jk += weights_i * s * X_ij;
// // L_jk /= c;
// // X_ij *= c;
// // X_ij -= s*L_jk;
// // L.coeffRef(j,k) = L_jk;
// // Xi.coeffRef(j) = X_ij;
// // }
// // // L.block(k+1,k,n-k-1,1) = (L.block(k+1,k,n-k-1,1) + weights_i * s * Xi.tail(n-k-1))/c;
// // // Xi.tail(n-k-1) = c*Xi.tail(n-k-1) - s*L.block(k+1,k,n-k-1,1);
// // // R.block(k,k+1,1,n-k-1) += weights_i * s * Xi.tail(n-k-1).transpose();
// // // R.block(k,k+1,1,n-k-1) /= c;
// // // Xi.tail(n-k-1) *= c;
// // // Xi.tail(n-k-1) -= s*R.block(k,k+1,1,n-k-1).transpose();
// // }
// // }
// // }
// // }
// //
// // // [[Rcpp::export()]]
// // MatrixXd chol_update_L3(MatrixXd L, MatrixXd X, VectorXd weights) {
// // chol_update_L_inplace2(L,X,weights);
// // return(L);
// // }
// //
// // // [[Rcpp::export()]]
// // MatrixXd chol_solve1(Map<MatrixXd> chol_R, Map<MatrixXd> Y){
// // return(chol_R.transpose().triangularView<Lower>().solve(Y));
// // }
// // // [[Rcpp::export()]]
// // MatrixXd chol_solve2(Map<MatrixXd> chol_L, Map<MatrixXd> Y){
// // return(chol_L.triangularView<Lower>().solve(Y));
// // }
// //
// // // [[Rcpp::export()]]
// // MatrixXd chol_u1(Map<MatrixXd> A, VectorXd X, int times){
// // LLT<MatrixXd> lA(A);
// // MatrixXd L = lA.matrixL();
// // // VectorXd weights = VectorXd::Constant(1,1.0);
// // // for(int i = 0; i < times; i++){
// // // chol_update_L_inplace2(L, X, weights);
// // // }
// // MatrixXd XX = X.replicate(1,times);
// // VectorXd weights = VectorXd::Constant(times,1.0);
// // chol_update_L_inplace2(L,XX,weights);
// // return(L);
// // }
// //
// // // [[Rcpp::export()]]
// // MatrixXd chol_u2(Map<MatrixXd> A, VectorXd X, int times){
// // LLT<MatrixXd> lA(A);
// // VectorXd weights = VectorXd::Constant(1,1.0);
// // for(int i = 0; i < times; i++){
// // lA.rankUpdate(X,1.0);
// // }
// // MatrixXd L = lA.matrixL();
// // return(L);
// // }
// //
// // Rcpp::List chol_cT(Map<MatrixXd> A){
// // LLT<MatrixXd> lA(A);
// // return(Rcpp::List::create(lA));
// // }
// // // [[Rcpp::export()]]
// // MatrixXd chol_cL(Rcpp::List L){
// // LLT<MatrixXd> lA = as<LLT<MatrixXd>>(L[0]);
// // return(lA.matrixL());
// // }
//
//
// // void a1(MatrixXd &X){
// // X.coeffRef(0,0) += 1;
// // Rcout << X.coeff(0,0) << std::endl;
// // }
// //
// // // [[Rcpp::export()]]
// // void a0(MatrixXd X){
// // Rcout << X.coeff(0,0) << std::endl;
// // a1(X);
// // Rcout << X.coeff(0,0) << std::endl;
// // MatrixXd Y(X);
// // a1(Y);
// // Rcout << X.coeff(0,0) << std::endl;
// // }
// //
// // struct x{
// // double A=0;
// // };
// //
// // x a3a(double A){
// // x X;
// // X.A = A;
// // return(X);
// // }
// // void a3(x &X){
// // // X.A = 3;
// // X = a3a(5);
// // }
// //
// // // [[Rcpp::export()]]
// // void a4(){
// // x X;
// // Rcout << X.A << std::endl;
// // a3(X);
// // Rcout << X.A << std::endl;
// // }
//
// // // [[Rcpp::export()]]
// // Rcpp::List svd_c(Map<MatrixXd> X) {
// // Eigen::BDCSVD<MatrixXd> bcdsolve(X, Eigen::ComputeFullU | Eigen::ComputeFullV);
// // // bcdsolve.computeU();
// // // MatrixXd U = bcdsolve.matrixU();
// // return(Rcpp::List::create(Named("u") = bcdsolve.matrixU(),
// // Named("d") = bcdsolve.singularValues()));
// // }
// //
// //
// // // [[Rcpp::export()]]
// // Rcpp::List svd_c3(SEXP X) {
// // if(Rf_isMatrix(X)) {
// // Eigen::BDCSVD<MatrixXd> bcdsolve(X, Eigen::ComputeFullU | Eigen::ComputeFullV);
// // // bcdsolve.computeU();
// // // MatrixXd U = bcdsolve.matrixU();
// // return(Rcpp::List::create(Named("u") = bcdsolve.matrixU(),
// // Named("d") = bcdsolve.singularValues()));
// // } else{
// // Eigen::BDCSVD<MSpMat> bcdsolve(X, Eigen::ComputeFullU | Eigen::ComputeFullV);
// // // bcdsolve.computeU();
// // // MatrixXd U = bcdsolve.matrixU();
// // return(Rcpp::List::create(Named("u") = bcdsolve.matrixU(),
// // Named("d") = bcdsolve.singularValues()));
// // }
// // }
// //
// // // [[Rcpp::export()]]
// // Rcpp::List svd_c2(MatrixXd X) {
// // Eigen::BDCSVD<MatrixXd> bcdsolve(X, Eigen::ComputeFullU | Eigen::ComputeFullV);
// // // bcdsolve.computeU();
// // // MatrixXd U = bcdsolve.matrixU();
// // return(Rcpp::List::create(Named("u") = bcdsolve.matrixU(),
// // Named("d") = bcdsolve.singularValues()));
// // }
// //
// //
// // // [[Rcpp::export()]]
// // void m1(Map<MatrixXd> X){
// // X *= 3;
// // }
// //
// // // [[Rcpp::export()]]
// // void m1b(Map<MatrixXd> X){
// // MatrixXd X2(X);
// // X2 *= 3;
// // }
// //
// //
// // // [[Rcpp::export()]]
// // void test_list(Rcpp::List X_){
// // std::vector<Map<MatrixXd> > X;
// // for(int i = 0; i < X_.length(); i++){
// // X.push_back(as<Map<MatrixXd> >(X_[i]));
// // }
// // X[0] *= 3;
// // }
// // // [[Rcpp::export()]]
// // void test_list2(Rcpp::List X_){
// // std::vector<MatrixXd> X;
// // for(int i = 0; i < X_.length(); i++){
// // X.push_back(MatrixXd());
// // MatrixXd Xi = as<MatrixXd>(X_[i]);
// // X.back().swap(as<Map<MatrixXd> >(X_[i]));
// // }
// // X[0] *= 3;
// // }
// //
// // // [[Rcpp::export()]]
// // void m3(Map<MatrixXd> X){
// // X *= 3;
// // }
// // // [[Rcpp::export()]]
// // void m3b(Map<MatrixXd> X_){
// // MatrixXd X = X_;
// // Map<MatrixXd> X2(X.data(),X.rows(),X.cols());
// // m3(X2);
// // }
// //
// // // [[Rcpp::export()]]
// // void m4(MatrixXd &X){
// // X *= 3;
// // Rcout << X.coeff(0,0);
// // }
// //
// // // [[Rcpp::export()]]
// // void m4b(Map<MatrixXd> X_){
// // MatrixXd X(X_);
// // m4(X);
// // Rcout << X.coeff(0,0);
// // }
// //
// // // [[Rcpp::export()]]
// // void t(MatrixXd X, VectorXd y){
// // if(y.size() != X.cols()) stop("asdf");
// // }
//
// // // [[Rcpp::export()]]
// // MatrixXd t1(Map<MatrixXd> R,Map<MatrixXd> Y){
// // return(R.triangularView<Upper>().solve(Y));
// // }
// //
// // // [[Rcpp::export()]]
// // MatrixXd invt(Map<MatrixXd> Rinv,Map<MatrixXd> Y){
// // return(Rinv.triangularView<Upper>() * Y);
// // }
// //
// //
// // // [[Rcpp::export()]]
// // void temp(SEXP Rinv_,Map<MatrixXd> Y, bool sparseR = false){
// // if(Rf_isMatrix(Rinv_) ){
// // Rcout << "yes";
// // } else{
// // Rcout << "no";
// // }
// // }
// //
// // // [[Rcpp::export()]]
// // MatrixXd invt2(SEXP Rinv_,Map<MatrixXd> Y, bool sparseR = false){
// // MatrixXd result;
// // if(sparseR) {
// // MSpMat Rinv = as<MSpMat>(Rinv_);
// // result = Rinv.triangularView<Upper>() * Y;
// // } else{
// // Map<MatrixXd> Rinv = as<Map<MatrixXd> >(Rinv_);
// // result = Rinv.triangularView<Upper>() * Y;
// // }
// // return(result);
// // }
// //
// //
// // // [[Rcpp::export()]]
// // MatrixXd m1(Map<MatrixXd> X, Map<MatrixXd> Y) {
// // MatrixXd result(X.rows(),Y.cols());
// // result = X*Y;
// // return(result);
// // }
// // // [[Rcpp::export()]]
// // MatrixXd m1b(Map<MatrixXd> X, Map<MatrixXd> Y) {
// // MatrixXd result(X.rows(),Y.cols());
// // for(int i = 0; i < Y.cols(); i++){
// // MatrixXd Yi(X.rows(),1);
// // // Yi = Y.col(i);
// // // result.col(i) = X*Y.block(0,i,Y.rows(),1);
// // result.block(0,i,Y.rows(),1) = X*Y.col(i);
// // }
// // return(result);
// // }
// // // [[Rcpp::export()]]
// // MatrixXd m1c(Map<MatrixXd> Xt, Map<MatrixXd> Y) {
// // MatrixXd result(Xt.cols(),Y.cols());
// // for(int i = 0; i < Y.cols(); i++){
// // result.col(i) = Xt.transpose()*Y.col(i);
// // }
// // return(result);
// // }
// //
// // // [[Rcpp::export()]]
// // MatrixXd m2(Map<MatrixXd> X, Map<MatrixXd> Y) {
// // int n = X.cols();
// // int b = Y.rows()/n;
// // int p = Y.cols();
// // MatrixXd result(Y.rows(),Y.cols());
// // for(int i = 0; i < b; i++) {
// // result.block(n*i,0,n,p) = X * Y.block(n*i,0,n,p);
// // }
// // return(result);
// // }
// //
// // // [[Rcpp::export()]]
// // MatrixXd m3(Map<MatrixXd> X, Map<MatrixXd> Y) {
// // int n = X.cols();
// // int b = Y.rows()/n;
// // int p = Y.cols();
// // MatrixXd result(Y.rows(),Y.cols());
// // for(int i = 0; i < p; i++) {
// // MatrixXd Yi = Map<MatrixXd>(Y.col(i).data(),n,b);
// // MatrixXd r = X * Yi;
// // // result.col(i) = Map<VectorXd>(r.data(),n*b);
// // }
// // return(result);
// // }
// //
// // // [[Rcpp::export()]]
// // MatrixXd m4(MatrixXd &X, MatrixXd &Y) {
// // return(X*Y);
// // }
// // // [[Rcpp::export()]]
// // MatrixXd m4b(MatrixXd X, MatrixXd Y) {
// // return(X*Y);
// // }
| 33.789149 | 153 | 0.498632 | [
"vector"
] |
913cbe374e68899f5aeda9c11de8b1540edc77f9 | 2,354 | cpp | C++ | cpp/godot-cpp/src/gen/World.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | 1 | 2021-03-16T09:51:00.000Z | 2021-03-16T09:51:00.000Z | cpp/godot-cpp/src/gen/World.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | cpp/godot-cpp/src/gen/World.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | #include "World.hpp"
#include <core/GodotGlobal.hpp>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include <core/Godot.hpp>
#include "__icalls.hpp"
#include "PhysicsDirectSpaceState.hpp"
#include "Environment.hpp"
namespace godot {
World::___method_bindings World::___mb = {};
void World::___init_method_bindings() {
___mb.mb_get_direct_space_state = godot::api->godot_method_bind_get_method("World", "get_direct_space_state");
___mb.mb_get_environment = godot::api->godot_method_bind_get_method("World", "get_environment");
___mb.mb_get_fallback_environment = godot::api->godot_method_bind_get_method("World", "get_fallback_environment");
___mb.mb_get_scenario = godot::api->godot_method_bind_get_method("World", "get_scenario");
___mb.mb_get_space = godot::api->godot_method_bind_get_method("World", "get_space");
___mb.mb_set_environment = godot::api->godot_method_bind_get_method("World", "set_environment");
___mb.mb_set_fallback_environment = godot::api->godot_method_bind_get_method("World", "set_fallback_environment");
}
World *World::_new()
{
return (World *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"World")());
}
PhysicsDirectSpaceState *World::get_direct_space_state() {
return (PhysicsDirectSpaceState *) ___godot_icall_Object(___mb.mb_get_direct_space_state, (const Object *) this);
}
Ref<Environment> World::get_environment() const {
return Ref<Environment>::__internal_constructor(___godot_icall_Object(___mb.mb_get_environment, (const Object *) this));
}
Ref<Environment> World::get_fallback_environment() const {
return Ref<Environment>::__internal_constructor(___godot_icall_Object(___mb.mb_get_fallback_environment, (const Object *) this));
}
RID World::get_scenario() const {
return ___godot_icall_RID(___mb.mb_get_scenario, (const Object *) this);
}
RID World::get_space() const {
return ___godot_icall_RID(___mb.mb_get_space, (const Object *) this);
}
void World::set_environment(const Ref<Environment> env) {
___godot_icall_void_Object(___mb.mb_set_environment, (const Object *) this, env.ptr());
}
void World::set_fallback_environment(const Ref<Environment> env) {
___godot_icall_void_Object(___mb.mb_set_fallback_environment, (const Object *) this, env.ptr());
}
} | 37.365079 | 191 | 0.790569 | [
"object"
] |
91428cca85b8e45b4cf51b10a9e8df5e1f096b11 | 11,997 | cpp | C++ | linux/policy/src/NMPolicyHistoryBased.cpp | RedCarrottt/selective-connection | 6103a21ffc5deea45ae3f913cd2d732c5364cf5d | [
"Apache-2.0"
] | 11 | 2019-09-04T06:27:04.000Z | 2020-08-25T08:36:11.000Z | linux/policy/src/NMPolicyHistoryBased.cpp | RedCarrottt/Virtual-Connection | 6103a21ffc5deea45ae3f913cd2d732c5364cf5d | [
"Apache-2.0"
] | 15 | 2019-09-04T10:29:28.000Z | 2019-12-24T13:05:46.000Z | linux/policy/src/NMPolicyHistoryBased.cpp | RedCarrottt/Virtual-Connection | 6103a21ffc5deea45ae3f913cd2d732c5364cf5d | [
"Apache-2.0"
] | 6 | 2021-07-26T01:40:37.000Z | 2021-10-12T06:33:28.000Z | /* Copyright 2017-2018 All Rights Reserved.
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* [Contact]
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* 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 "../inc/NMPolicyHistoryBased.h"
#include "../inc/EnergyPredictor.h"
#include "../inc/ConfigHistoryBasedPolicy.h"
#include "../../common/inc/DebugLog.h"
#include <assert.h>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <sstream>
#define PRINT_EVERY_ENERGY_COMPARISON 0
using namespace sc;
std::string NMPolicyHistoryBased::get_stats_string(void) {
char recent_adapter_name[50];
if (mIsRecentWfdOn) {
snprintf(recent_adapter_name, 50, "WFD");
} else {
snprintf(recent_adapter_name, 50, "BT");
}
char stats_cstr[256];
snprintf(stats_cstr, 256, "\"%s(%d)/%s(%d)\": %d vs. %d - (%d/%d) - %s",
this->mPresentBGAppName.c_str(), this->mPresentBGEventType,
this->mPresentFGAppName.c_str(), this->mPresentFGEventType,
(int)this->mEnergyRetain, (int)this->mEnergySwitch,
this->mRequestSpeedIncCount, this->mRequestSpeedDecCount,
recent_adapter_name);
std::string stats_string(stats_cstr);
return stats_string;
}
void NMPolicyHistoryBased::on_custom_event(std::string &event_description) {
// change current app name (event_description = "app_name event_type")
std::istringstream sstream(event_description);
std::string token;
int i = 0;
bool is_background_app = false;
while (std::getline(sstream, token, ' ')) {
if (i == 0) {
if (token.find("BG") != std::string::npos) {
is_background_app = true;
}
if (is_background_app) {
if (this->mPresentBGAppName.compare(token) != 0) {
gettimeofday(&this->mPresentBGAppStartTS, NULL);
}
this->mPresentBGAppName.assign(token);
} else {
if (this->mPresentFGAppName.compare(token) != 0) {
gettimeofday(&this->mPresentFGAppStartTS, NULL);
}
this->mPresentFGAppName.assign(token);
}
} else if (i == 1) {
if (is_background_app) {
this->mPresentBGEventType = std::stoi(token);
} else {
this->mPresentFGEventType = std::stoi(token);
}
}
i++;
}
// reset recent switch timestamp: start to decide switch
this->reset_recent_switch_ts();
return;
}
#define SERIAL_INC_COUNT_THRESHOLD 3
#define SERIAL_DEC_COUNT_THRESHOLD 3
SwitchBehavior NMPolicyHistoryBased::decide(const Stats &stats,
bool is_increasable,
bool is_decreasable) {
// No decision after switch for prediction window
if (this->mRecentSwitchTS.tv_sec != 0 && this->mRecentSwitchTS.tv_usec != 0) {
struct timeval present_tv;
gettimeofday(&present_tv, NULL);
long long from_switch_elapsed_time_us =
((long long)present_tv.tv_sec * (1000 * 1000) +
(long long)present_tv.tv_usec) -
((long long)this->mRecentSwitchTS.tv_sec * (1000 * 1000) +
(long long)this->mRecentSwitchTS.tv_usec);
if (from_switch_elapsed_time_us < PREDICTION_WINDOW_SEC * 1000 * 1000 / 2) {
return kNoBehavior;
}
}
// Filtering intermittent decision
SwitchBehavior behavior =
this->decide_internal(stats, is_increasable, is_decreasable);
if (behavior == SwitchBehavior::kIncreaseAdapter) {
if (this->mSerialIncCount < SERIAL_INC_COUNT_THRESHOLD) {
behavior = kNoBehavior;
} else {
this->mIsRecentWfdOn = true;
}
this->mSerialIncCount++;
this->mSerialDecCount = 0;
} else if (behavior == SwitchBehavior::kDecreaseAdapter) {
if (this->mSerialDecCount < SERIAL_DEC_COUNT_THRESHOLD) {
behavior = kNoBehavior;
} else {
this->mIsRecentWfdOn = false;
}
this->mSerialDecCount++;
this->mSerialIncCount = 0;
} else {
this->mSerialIncCount = 0;
this->mSerialDecCount = 0;
}
if (behavior == SwitchBehavior::kIncreaseAdapter ||
behavior == SwitchBehavior::kDecreaseAdapter) {
this->update_recent_switch_ts();
}
return behavior;
}
void NMPolicyHistoryBased::update_recent_switch_ts(void) {
gettimeofday(&this->mRecentSwitchTS, NULL);
}
void NMPolicyHistoryBased::reset_recent_switch_ts(void) {
this->mRecentSwitchTS.tv_sec = 0;
this->mRecentSwitchTS.tv_usec = 0;
}
SwitchBehavior NMPolicyHistoryBased::decide_internal(const Stats &stats,
bool is_increasable,
bool is_decreasable) {
float present_media_bandwidth =
stats.ema_queue_arrival_speed + (float)stats.now_queue_data_size; // B/s
// Step 1. Filtering
// Step 1-a. Filtering increase when idle / decrease when busy
// if (present_media_bandwidth > IDLE_THRESHOLD && is_decreasable) {
// // Filtering decrease when busy
// return kNoBehavior;
// } else if (present_media_bandwidth < IDLE_THRESHOLD && is_increasable) {
// // Filtering increase when idle
// return kNoBehavior;
// }
// Step 1-b. detect increasing/decreasing traffic in series
if (present_media_bandwidth > HIGH_THRESHOLD) {
this->mRequestSpeedIncCount++;
this->mRequestSpeedDecCount = 0;
} else if (present_media_bandwidth < LOW_THRESHOLD) {
this->mRequestSpeedDecCount++;
this->mRequestSpeedIncCount = 0;
} else if (present_media_bandwidth > this->mLastMediaBandwidth) {
this->mRequestSpeedIncCount++;
this->mRequestSpeedDecCount = 0;
} else if (present_media_bandwidth < this->mLastMediaBandwidth) {
this->mRequestSpeedDecCount++;
this->mRequestSpeedIncCount = 0;
}
this->mLastMediaBandwidth = present_media_bandwidth;
if (this->mRequestSpeedIncCount < INC_COUNT_THRESHOLD &&
this->mRequestSpeedDecCount < DEC_COUNT_THRESHOLD) {
return kNoBehavior;
}
if ((is_increasable && (this->mRequestSpeedDecCount > DEC_COUNT_THRESHOLD)) ||
(is_decreasable && (this->mRequestSpeedIncCount > INC_COUNT_THRESHOLD))) {
return kNoBehavior;
}
// Step 2. get traffic prediction entry for the FG/BG apps
AppEntry *fgAppEntry = NULL;
if (!this->mPresentFGAppName.empty()) {
fgAppEntry = this->mTrafficPredictionTable.getItem(this->mPresentFGAppName);
if (fgAppEntry == NULL) {
LOG_WARN("Cannot find traffic prediction: %s",
this->mPresentFGAppName.c_str());
return kNoBehavior;
}
}
AppEntry *bgAppEntry = this->mBGAppEntry;
if (fgAppEntry == NULL && bgAppEntry == NULL) {
LOG_WARN("No apps: no traffic prediction");
return kNoBehavior;
}
// Step 3-a. predict traffic history for the foreground app
int predicted_traffic_length = 0;
TrafficEntry *fg_traffic = NULL;
if (fgAppEntry != NULL) {
fg_traffic = this->get_predicted_traffic(fgAppEntry, false);
if (fg_traffic == NULL) {
LOG_WARN("No predicted traffic for FG app");
return kNoBehavior;
}
predicted_traffic_length = fg_traffic->getTrafficSequence().size();
}
// Step 3-b. predict traffic history for the background app
TrafficEntry *bg_traffic = NULL;
if (bgAppEntry != NULL) {
bg_traffic = this->get_predicted_traffic(bgAppEntry, true);
if (bg_traffic == NULL) {
LOG_WARN("No predicted traffic for BG app");
return kNoBehavior;
}
predicted_traffic_length = bg_traffic->getTrafficSequence().size();
}
// Step 3-C. merge traffic histories
std::vector<int> traffic_seq;
for (int i = 0; i < predicted_traffic_length; i++) {
int traffic = 0;
traffic += (fg_traffic) ? fg_traffic->getTrafficSequence()[i] : 0;
traffic += (bg_traffic) ? bg_traffic->getTrafficSequence()[i] : 0;
traffic_seq.push_back(traffic);
}
// Step 4. predict energy and final decision
int seg_q_length = stats.now_queue_data_size; // Bytes
if (is_increasable) {
float energy_bt = EnergyPredictor::predictEnergy(seg_q_length, traffic_seq,
SCENARIO_BT); // mJ
float energy_bt_to_wfd = EnergyPredictor::predictEnergy(
seg_q_length, traffic_seq, SCENARIO_BT_TO_WFD); // mJ
this->mEnergyRetain = energy_bt;
this->mEnergySwitch = energy_bt_to_wfd;
#if PRINT_EVERY_ENERGY_COMPARISON == 1
LOG_IMP(" => (%f > %f) ? BT : to-WFD", this->mEnergyRetain,
this->mEnergySwitch);
#endif
if (energy_bt < 0.0f || energy_bt_to_wfd < 0.0f) {
return kNoBehavior;
} else if (energy_bt > energy_bt_to_wfd ||
energy_bt == std::numeric_limits<float>::max()) {
return kIncreaseAdapter;
} else {
return kNoBehavior;
}
} else if (is_decreasable) {
float energy_wfd = EnergyPredictor::predictEnergy(seg_q_length, traffic_seq,
SCENARIO_WFD); // mJ
float energy_wfd_to_bt = EnergyPredictor::predictEnergy(
seg_q_length, traffic_seq, SCENARIO_WFD_TO_BT); // mJ
this->mEnergyRetain = energy_wfd;
this->mEnergySwitch = energy_wfd_to_bt;
#if PRINT_EVERY_ENERGY_COMPARISON == 1
LOG_IMP(" => (%f > %f) ? WFD : to-BT", this->mEnergyRetain,
this->mEnergySwitch);
#endif
if (energy_wfd < 0.0f || energy_wfd_to_bt < 0.0f) {
return kNoBehavior;
} else if (energy_wfd > energy_wfd_to_bt) {
return kDecreaseAdapter;
} else {
return kNoBehavior;
}
} else {
// If there is only one network adapter
return kNoBehavior;
}
}
TrafficEntry *
NMPolicyHistoryBased::get_predicted_traffic(AppEntry *appEntry,
bool isBackgroundApp) {
struct timeval present_time;
struct timeval present_app_start_time;
int event_type;
if (isBackgroundApp) {
present_app_start_time = this->mPresentBGAppStartTS;
event_type = this->mPresentBGEventType;
} else {
present_app_start_time = this->mPresentFGAppStartTS;
event_type = this->mPresentFGEventType;
}
gettimeofday(&present_time, NULL);
long long presentTimeUS =
(long long)present_time.tv_sec * 1000 * 1000 + present_time.tv_usec;
long long appStartTimeUs =
(long long)present_app_start_time.tv_sec * 1000 * 1000 +
present_app_start_time.tv_usec;
// Get event type entry
EventTypeEntry *eventTypeEntry = appEntry->getItem(event_type);
if (eventTypeEntry == NULL) {
LOG_WARN("Cannot find event_type_entry: %d", event_type);
return NULL;
}
// Get timestamp relative to app start event
float present_time_sec = (float)(presentTimeUS - appStartTimeUs) / 1000000.0f;
TrafficEntry *trafficEntry = eventTypeEntry->findItem(present_time_sec);
// LOG_ERR("Predicted traffic at : %4.1f (%d)", trafficEntry->getTimeSec(),
// isBackgroundApp);
// std::vector<int>& traffic = trafficEntry->getTrafficSequence();
// for(int i=0; i<traffic.size(); i++) {
// printf("%d ", traffic[i]);
// }
// printf("\n");
return trafficEntry;
}
void NMPolicyHistoryBased::check_background_app_entry(void) {
std::map<std::string, AppEntry> &appEntries =
this->mTrafficPredictionTable.getMap();
for (std::map<std::string, AppEntry>::iterator it = appEntries.begin();
it != appEntries.end(); it++) {
std::string appName = it->first;
AppEntry *appEntry = &(it->second);
if (appName.find("BG") != std::string::npos) {
// Prevent more than one background apps
assert(this->mBGAppEntry == NULL);
this->mBGAppEntry = appEntry;
}
}
} | 34.474138 | 80 | 0.668917 | [
"vector"
] |
914c2d10ff1e2f1f0a9f5b16d14e32d3aa190184 | 13,128 | cpp | C++ | RNAstructure_Source/PARTS/src/parts/ppf_w.cpp | mayc2/PseudoKnot_research | 33e94b84435d87aff3d89dbad970c438ac173331 | [
"MIT"
] | null | null | null | RNAstructure_Source/PARTS/src/parts/ppf_w.cpp | mayc2/PseudoKnot_research | 33e94b84435d87aff3d89dbad970c438ac173331 | [
"MIT"
] | null | null | null | RNAstructure_Source/PARTS/src/parts/ppf_w.cpp | mayc2/PseudoKnot_research | 33e94b84435d87aff3d89dbad970c438ac173331 | [
"MIT"
] | null | null | null | #include <string.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include "parts_compilation_directives.h"
#include "ppf_w.h"
#include "ppf_w_l.h"
#include "ppf_v_mhe.h"
#include "process_sequences.h"
#include "ppf_math.h"
#include <iostream>
#include "alignment_priors.h"
#include "phmm_parameters.h"
#include "single_pf_array.h"
#include "template_pf_array.h"
#include "ppf_loops.h"
//#include "../../../src/phmm/nnm_energy/xlog_math.h"
#include "ppf_tb_stack.h"
#include "map_structures.h"
#include "map_alignment.h"
#include "stoch_tb/stoch_sampling_math.h"
#include "ppf_cli.h"
#include "../../../src/phmm/structure/folding_constraints.h"
using namespace std;
extern bool problem;
extern bool map_problem;
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
bool _DUMP_PPF_W_MESSAGES_ = false;
t_ppf_W::t_ppf_W(t_ppf_loops* _ppf_loops)
{
if(_DUMP_PPF_W_MESSAGES_)
printf(" W ");
this->ppf_loops = _ppf_loops;
// Copy sequence lengths.
this->N1 = this->ppf_loops->seq_man->get_l_seq1();
this->N2 = this->ppf_loops->seq_man->get_l_seq2();
this->seq1_spf = this->ppf_loops->seq1_spf;
this->seq2_spf = this->ppf_loops->seq2_spf;
this->aln_priors = this->ppf_loops->aln_priors;
this->pf_array = new t_template_pf_array(this->ppf_loops->seq_man,
seq1_spf->folding_constraints->coinc_pointer_relocation_map,
seq2_spf->folding_constraints->coinc_pointer_relocation_map,
true);
this->ext_pf_array = new t_template_pf_array(this->ppf_loops->seq_man,
seq1_spf->folding_constraints->coinc_pointer_relocation_map,
seq2_spf->folding_constraints->coinc_pointer_relocation_map,
true);
}
t_ppf_W::~t_ppf_W()
{
if(_DUMP_PPF_W_MESSAGES_)
printf("Destruct'ing a t_ppf_W object.\n");
delete(this->pf_array);
delete(this->ext_pf_array);
}
bool t_ppf_W::check_boundary(int i1, int i2)
{
return(this->pf_array->check_boundary(i1, i2));
}
// Access to partition function array by reference.
double& t_ppf_W::x_setter(int i, int j, int k, int l)
{
if(this->pf_array->check_4D_ll(i,j,k,l))
{
return(this->pf_array->x(i, j, k, l));
}
else
{
printf("%s(%d)\n", __FILE__, __LINE__);
exit(0);
}
}
double t_ppf_W::x(int i, int j, int k, int l)
{
if(this->pf_array->check_4D_ll(i,j,k,l))
{
return(this->pf_array->x(i, j, k, l));
}
else
{
return(ZERO);
}
}
double& t_ppf_W::x_ext(int i, int j, int k, int l)
{
if(this->pf_array->check_4D_ll(i,j,k,l))
{
return(this->ext_pf_array->x(i, j, k, l));
}
else
{
printf("%s(%d)\n", __FILE__, __LINE__);
int* p = NULL;
*p = 0;
exit(0);
}
}
void t_ppf_W::calculate_W(int i, int j, int k, int l, bool bt) // Arrays to use.
{
// Have to fork for j > N, do bound checking...
if( !this->pf_array->check_4D_ll(i,j,k,l) )
{
//printf("Returning from W calculation @ %s(%d) before calculating W(%d, %d, %d, %d)\n", __FILE__, __LINE__, i,j,k,l);
return;
}
if(_DUMP_PPF_W_MESSAGES_)
printf("\nW(%d, %d, %d, %d):\n", i,j,k,l);
// Following are needed to check if i and k unpaired nucleotide additions are inside
// alignment constraints.
bool i_dec_k_dec = this->check_boundary(i - 1, k - 1);
bool i_dec_k = this->check_boundary(i - 1, k);
bool i_k_dec = this->check_boundary(i, k - 1);
// Following are needed for extending W to 5' side, that is,
// when calculating W from WR.
bool i_inc_k_inc = this->check_boundary(i + 1, k + 1);
bool i_inc_k = this->check_boundary(i + 1, k);
bool i_k_inc = this->check_boundary(i, k + 1);
// Following are needed for extending W to 3' side, that is,
// when calculating W from WL.
bool j_dec_l_dec = this->check_boundary(j - 1 , l - 1);
bool j_l_dec = this->check_boundary(j, l - 1);
bool j_dec_l = this->check_boundary(j - 1 , l);
// Calculate W from WL.
// Init W(i,j,k,l) as WL(i,j,k,l).
// And extend it through 3' side.
double j_l_ALN_unpair_score = MUL(seq1_spf->ux_3p(i,j), seq2_spf->ux_3p(k,l));
double j_INS_unpair_score = seq1_spf->ux_3p(i,j);
double l_INS_unpair_score = seq2_spf->ux_3p(k,l);
// Set up backtracking if requested backtracking.
double random_cumulative = ZERO;
double current_cumulative = ZERO;
bool pushed = false;
if(bt)
{
if(this->ppf_loops->ppf_cli->mode == PARTS_RUN_MODE_STOCH_SAMPLE)
{
random_cumulative = MUL(this->ppf_loops->stoch_sampler->random_double_1_0(), this->x(i,j,k,l));
}
else if(this->ppf_loops->ppf_cli->mode == PARTS_RUN_MODE_MAP)
{
random_cumulative = this->x(i,j,k,l);
}
else
{
printf("Cannot run backtracking with mode %d\n", this->ppf_loops->ppf_cli->mode);
exit(0);
}
}
// Initialize with WL.
current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, this->ppf_loops->WL->x(i,j,k,l));
if(bt && !pushed && this->ppf_loops->BT_OP(current_cumulative, random_cumulative))
{
this->ppf_loops->tb_stack->push_str(i, j, k, l, TRACE_WL);
pushed = true;
}
if(_DUMP_PPF_W_MESSAGES_)
printf("W_WL(%d, %d, %d, %d): inited: %f\n", i,j,k,l,(current_cumulative));
// Note that the same can be done by initing W as WR and extending to 5' side, this is in fact a very good test case for verifying partition function.
// align ij
double j_l_ALN_prior = aln_priors->x(j, l, STATE_ALN);
current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->x(i, j - 1, k, l - 1), MUL(j_l_ALN_prior, j_l_ALN_unpair_score)) );
if(bt && !pushed && this->ppf_loops->BT_OP(current_cumulative, random_cumulative))
{
this->ppf_loops->tb_stack->push_str(i, j-1, k, l-1, TRACE_W);
this->ppf_loops->set_aln(j,l);
pushed = true;
}
current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->ppf_loops->V_mhe->x(i, j - 1, k, l - 1), MUL(j_l_ALN_prior, j_l_ALN_unpair_score)) );
if(bt && !pushed && this->ppf_loops->BT_OP(current_cumulative, random_cumulative))
{
this->ppf_loops->tb_stack->push_str(i, j-1, k, l-1, TRACE_V_mhe);
this->ppf_loops->set_aln(j,l);
pushed = true;
}
if(_DUMP_PPF_W_MESSAGES_)
printf("W_WL(%d, %d, %d, %d) = %f, recursed on ALNed insertion with score W(%d, %d, %d, %d) = %f\n", i,j,k,l, (current_cumulative), i, j - 1, k, l - 1, (this->x(i, j - 1, k, l - 1)));
// insert l
double l_INS2_prior = aln_priors->x(j, l, STATE_INS2);
current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->x(i, j, k, l - 1), MUL(l_INS2_prior, l_INS_unpair_score)) );
if(bt && !pushed && this->ppf_loops->BT_OP(current_cumulative, random_cumulative))
{
this->ppf_loops->tb_stack->push_str(i, j, k, l-1, TRACE_W);
this->ppf_loops->set_seq2_ins(j,l);
pushed = true;
}
current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->ppf_loops->V_mhe->x(i, j, k, l - 1), MUL(l_INS2_prior, l_INS_unpair_score)) );
if(bt && !pushed && this->ppf_loops->BT_OP(current_cumulative, random_cumulative))
{
this->ppf_loops->tb_stack->push_str(i, j, k, l-1, TRACE_V_mhe);
this->ppf_loops->set_seq2_ins(j,l);
pushed = true;
}
if(_DUMP_PPF_W_MESSAGES_)
printf("W_WL(%d, %d, %d, %d) = %f, recursed on l insertion with score W(%d, %d, %d, %d) = %f\n", i,j,k,l, (current_cumulative), i, j, k, l - 1, (this->x(i, j, k, l - 1)));
// insert j
double j_INS1_prior = aln_priors->x(j, l, STATE_INS1);
current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->x(i, j - 1, k, l), MUL(j_INS1_prior, j_INS_unpair_score)) );
if(bt && !pushed && this->ppf_loops->BT_OP(current_cumulative, random_cumulative))
{
this->ppf_loops->tb_stack->push_str(i, j-1, k, l, TRACE_W);
this->ppf_loops->set_seq1_ins(j,l);
pushed = true;
}
current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->ppf_loops->V_mhe->x(i, j - 1, k, l), MUL(j_INS1_prior, j_INS_unpair_score)) );
if(bt && !pushed && this->ppf_loops->BT_OP(current_cumulative, random_cumulative))
{
this->ppf_loops->tb_stack->push_str(i, j-1, k, l, TRACE_V_mhe);
this->ppf_loops->set_seq1_ins(j,l);
pushed = true;
}
if(_DUMP_PPF_W_MESSAGES_)
printf("W_WL(%d, %d, %d, %d) = %f, recursed on j insertion with score W(%d, %d, %d, %d) = %f\n", i, j, k, l, (current_cumulative), i, j - 1, k, l, (this->x(i, j - 1, k, l)));
if(current_cumulative < ZERO)
{
printf("W_WL(%d, %d, %d, %d) = %f\n", i,j,k,l,current_cumulative );
getc(stdin);
}
// Assign or compare.
if(bt)
{
if(!COMPARE(this->x(i,j,k,l), current_cumulative))
{
printf("Traceback error @ %s(%d)\n", __FILE__, __LINE__);
exit(0);
}
}
else
{
this->x_setter(i,j,k,l) = current_cumulative;
}
if(_DUMP_PPF_W_MESSAGES_)
printf("W(%d, %d, %d, %d) = %f\n", i, j, k, l, (this->x(i,j,k,l)));
}
void t_ppf_W::calculate_ext_dependencies(int i, int j, int k, int l) // Arrays to use.
{
// Have to fork for j > N, do bound checking...
if( !this->pf_array->check_4D_ll(i,j,k,l) )
{
//printf("Returning from W calculation @ %s(%d) before calculating W(%d, %d, %d, %d)\n", __FILE__, __LINE__, i,j,k,l);
return;
}
if(_DUMP_PPF_W_MESSAGES_)
printf("\nW(%d, %d, %d, %d):\n", i,j,k,l);
// Following are needed to check if i and k unpaired nucleotide additions are inside
// alignment constraints.
bool i_dec_k_dec = this->check_boundary(i - 1, k - 1);
bool i_dec_k = this->check_boundary(i - 1, k);
bool i_k_dec = this->check_boundary(i, k - 1);
// Following are needed for extending W to 5' side, that is,
// when calculating W from WR.
bool i_inc_k_inc = this->check_boundary(i + 1, k + 1);
bool i_inc_k = this->check_boundary(i + 1, k);
bool i_k_inc = this->check_boundary(i, k + 1);
// Following are needed for extending W to 3' side, that is,
// when calculating W from WL.
bool j_dec_l_dec = this->check_boundary(j - 1 , l - 1);
bool j_l_dec = this->check_boundary(j, l - 1);
bool j_dec_l = this->check_boundary(j - 1 , l);
// Calculate W from WL.
// Init W(i,j,k,l) as WL(i,j,k,l).
// And extend it through 3' side.
double W_WL = this->ppf_loops->WL->x(i,j,k,l);
double j_l_ALN_unpair_score = MUL(seq1_spf->ux_3p(i,j), seq2_spf->ux_3p(k,l));
double j_INS_unpair_score = seq1_spf->ux_3p(i,j);
double l_INS_unpair_score = seq2_spf->ux_3p(k,l);
if(_DUMP_PPF_W_MESSAGES_)
printf("W_WL(%d, %d, %d, %d): inited: %f\n", i,j,k,l,(W_WL));
// Initialize with W_WL.
if(this->ppf_loops->WL->pf_array->check_4D_ll(i,j,k,l))
{
//current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, this->ppf_loops->WL->x(i,j,k,l));
this->ppf_loops->WL->x_ext(i,j,k,l) = this->ppf_loops->MAX_SUM(this->ppf_loops->WL->x_ext(i,j,k,l), this->x_ext(i,j,k,l));
}
// Note that the same can be done by initing W as WR and extending to 5' side, this is in fact a very good test case for verifying partition function.
// align ij
double j_l_ALN_prior = aln_priors->x(j, l, STATE_ALN);
if(this->pf_array->check_4D_ll(i, j-1, k, l-1))
{
//current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->x(i, j - 1, k, l - 1), MUL(j_l_ALN_prior, j_l_ALN_unpair_score)) );
this->x_ext(i,j-1,k,l-1) = this->ppf_loops->MAX_SUM(this->x_ext(i,j-1,k,l-1),
MUL3(this->x_ext(i,j,k,l), j_l_ALN_prior, j_l_ALN_unpair_score));
}
if(this->ppf_loops->V_mhe->pf_array->check_4D_ll(i, j-1, k, l-1))
{
//current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->ppf_loops->V_mhe->x(i, j - 1, k, l - 1), MUL(j_l_ALN_prior, j_l_ALN_unpair_score)) );
this->ppf_loops->V_mhe->x_ext(i,j-1,k,l-1) = this->ppf_loops->MAX_SUM(this->ppf_loops->V_mhe->x_ext(i,j-1,k,l-1),
MUL3(this->x_ext(i,j,k,l), j_l_ALN_prior, j_l_ALN_unpair_score));
}
// insert l
double l_INS2_prior = aln_priors->x(j, l, STATE_INS2);
if(this->pf_array->check_4D_ll(i, j, k, l-1))
{
//current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->x(i, j, k, l - 1), MUL(l_INS2_prior, l_INS_unpair_score)) );
this->x_ext(i,j,k,l-1) = this->ppf_loops->MAX_SUM(this->x_ext(i,j,k,l-1),
MUL3(this->x_ext(i,j,k,l), l_INS2_prior, l_INS_unpair_score));
}
if(this->ppf_loops->V_mhe->pf_array->check_4D_ll(i, j, k, l-1))
{
//current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->ppf_loops->V_mhe->x(i, j, k, l - 1), MUL(l_INS2_prior, l_INS_unpair_score)) );
this->ppf_loops->V_mhe->x_ext(i,j,k,l-1) = this->ppf_loops->MAX_SUM(this->ppf_loops->V_mhe->x_ext(i,j,k,l-1),
MUL3(this->x_ext(i,j,k,l), l_INS2_prior, l_INS_unpair_score));
}
// insert j
double j_INS1_prior = aln_priors->x(j, l, STATE_INS1);
if(this->pf_array->check_4D_ll(i, j-1, k, l))
{
//current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->x(i, j - 1, k, l), MUL(j_INS1_prior, j_INS_unpair_score)) );
this->x_ext(i,j-1,k,l) = this->ppf_loops->MAX_SUM(this->x_ext(i,j-1,k,l),
MUL3(this->x_ext(i,j,k,l), j_INS1_prior, j_INS_unpair_score));
}
if(this->ppf_loops->V_mhe->pf_array->check_4D_ll(i, j-1, k, l))
{
//current_cumulative = this->ppf_loops->MAX_SUM(current_cumulative, MUL(this->ppf_loops->V_mhe->x(i, j - 1, k, l), MUL(j_INS1_prior, j_INS_unpair_score)) );
this->ppf_loops->V_mhe->x_ext(i,j-1,k,l) = this->ppf_loops->MAX_SUM(this->ppf_loops->V_mhe->x_ext(i,j-1,k,l),
MUL3(this->x_ext(i,j,k,l), j_INS1_prior, j_INS_unpair_score));
}
}
| 34.638522 | 184 | 0.673979 | [
"object"
] |
914fd357b03de3f965c226ff99d9f8c2d263548b | 34,283 | cpp | C++ | qnn/src/network/sw/main.cpp | Elli1993/QNN-MO-PYNQ | 9a37c116f7d2984547af513dd1c423dd3cc1494d | [
"BSD-3-Clause"
] | 8 | 2019-04-02T15:09:22.000Z | 2021-06-12T17:57:56.000Z | qnn/src/network/sw/main.cpp | awai54st/QNN-MO-PYNQ | d43a9e0cab11ddbe06aab1252ea0db2f735090b7 | [
"BSD-3-Clause"
] | null | null | null | qnn/src/network/sw/main.cpp | awai54st/QNN-MO-PYNQ | d43a9e0cab11ddbe06aab1252ea0db2f735090b7 | [
"BSD-3-Clause"
] | 2 | 2019-04-19T03:32:06.000Z | 2019-09-24T13:01:34.000Z | /*
Copyright (c) 2018, Xilinx, 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:
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 copyright holder 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 HOLDER 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 <iostream>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <string>
#include <unistd.h>
#include <sstream>
#include <list>
#include <atomic>
#include <signal.h>
#include <iomanip>
#include <memory>
#include <vector>
#include <map>
#ifndef NOZIP
#include <zip.h>
#endif
#include "general-utils.h"
#include "offload-utils.h"
#include "offload-adapter.h"
#include "jobber.h"
#include "network.h"
#include "layers.h"
#include "platform.h"
#include "logger.h"
void dump_to_file(std::string filename, char * buffer, size_t const size) {
std::ofstream ofile(filename, std::ios::out | std::ios::trunc);
ofile.write(buffer, size);
ofile.close();
}
extern "C" {
void initParameters(unsigned int const batch, unsigned int const threads);
void initAccelerator(char const *networkJson, char const *layerJson);
#ifndef NOZIP
void initAcceleratorZip(char const *zipPath);
#endif
void singleInference(char *in, size_t const inSize, char *out, size_t const outSize);
void deinitAccelerator();
}
namespace {
std::atomic<unsigned long long> duration(0);
std::atomic<unsigned long long> splitTime(0);
std::atomic<unsigned long long> splitBufferTime(0);
std::atomic<unsigned long long> mergeTime(0);
std::atomic<unsigned long long> weightsTime(0);
std::atomic<unsigned long long> prepareTime(0);
std::atomic<unsigned long long> offloadTime(0);
std::atomic<unsigned long long> concatTime(0);
std::atomic<unsigned long long> swpcpyTime(0);
std::atomic<unsigned long long> swapTime(0);
std::atomic<unsigned long long> resultTime(0);
std::atomic<unsigned long long> inputTime(0);
unsigned int batchSize = 1;
unsigned int imageCount = 1;
unsigned int threadCount = 0;
bool verbose = false;
bool threading = false;
bool inputTiming = false;
std::unique_ptr<Network> network;
std::unique_ptr<Layers> layers;
std::unique_ptr<OffloadAdapter> adapter;
std::unique_ptr<Jobber> jobber;
std::vector<OffloadAdapter::ExtMemBuffer *> resultBuffers;
std::vector<OffloadAdapter::ExtMemBuffer *> concatBuffers;
std::vector<OffloadAdapter::ExtMemBuffer *> mergeBuffers;
std::vector<OffloadAdapter::ExtMemBuffer *> testBuffers;
std::vector<std::vector<OffloadAdapter::ExtMemBuffer *>> splitBuffers;
Logger stdOut(std::cout, verbose);
Logger stdErr(std::cerr, verbose);
Logger::Verbosity verboseIgnore(true);
Logger::Verbosity verboseNone(false);
bool initialized = false;
}
void initParameters(unsigned int const batch, unsigned int const threads) {
if (initialized)
return;
batchSize = (batch > 0) ? batch : 1;
threadCount = threads;
}
void _init() {
threading = (threadCount == 0) ? false : true;
adapter.reset(new OffloadAdapter(layers->getNetwork(), network->getMemChannels(), layers->getMaxBufferSize()));
jobber.reset(new Jobber(threadCount));
if (layers->useBinparams()) {
adapter->loadWeights(*network, *layers);
};
unsigned int const maxIterations = layers->getMaxIterations();
unsigned int const maxSplits = layers->getMaxSplit();
// batchSize of hardware buffers for the inputs, 2 for output buffers
// even a single threaded call tries to do work parallel to hardware
// that needs at least one more output buffer to not block the applciation
unsigned int const minHardwareBuffers = batchSize + 2;
unsigned int hardwareBufferCount = 0;
stdOut << "Initializing a minimum of " << minHardwareBuffers << " hardware buffers of size " << adapter->getBufferSize() << " bytes..." << std::endl;
// Threading is drastically improved through free hardware buffers
// In case we are in hardware aquire as many buffers as possible
// In case of software aquire the minimum amount, because sw is
// already slow and not threaded at the moment
hardwareBufferCount += adapter->reserveBuffers(minHardwareBuffers, EXTMEMBUFFER_HARDWARE);
if (hardwareBufferCount < minHardwareBuffers) {
throw std::runtime_error("Could not initizialize " + std::to_string(minHardwareBuffers) + " required hardware buffers!");
}
stdOut << "Initialized minimum of " << hardwareBufferCount << " hardware buffers!" << std::endl;
unsigned int const minLocalBuffers = ((maxIterations > 1) ? batchSize : 0)
+ ((maxSplits > 1) ? batchSize + (batchSize * maxSplits) : 0)
+ batchSize;
unsigned int localBufferCount = 0;
stdOut << "Initializing a minimum of " << minLocalBuffers << " local buffers of size " << adapter->getBufferSize() << " bytes..." << std::endl;
localBufferCount += adapter->reserveBuffers(minLocalBuffers, EXTMEMBUFFER_LOCAL);;
if (localBufferCount < minLocalBuffers) {
throw std::runtime_error("Could not initizialize " + std::to_string(minLocalBuffers) + " required local buffers!");
}
stdOut << "Initialized " << localBufferCount << " local buffers!" << std::endl;
//Concat buffers are only used for multi iterations
concatBuffers.resize((maxIterations > 1) ? batchSize : 0);
for (auto &buf : concatBuffers) {
buf = &adapter->getBuffer(EXTMEMBUFFER_LOCAL);
}
mergeBuffers.resize((maxSplits > 1) ? batchSize : 0);
for (auto &buf : mergeBuffers) {
buf = &adapter->getBuffer(EXTMEMBUFFER_LOCAL);
}
resultBuffers.resize(batchSize);
for (auto &buf : resultBuffers) {
buf = &adapter->getBuffer(EXTMEMBUFFER_LOCAL);
}
splitBuffers.resize(batchSize);
for (auto &buffers : splitBuffers) {
buffers.resize(maxSplits);
for (auto &buf: buffers) {
buf = &adapter->getBuffer(EXTMEMBUFFER_LOCAL);
}
}
testBuffers.resize(batchSize);
for (auto &buf : testBuffers) {
buf = &adapter->getBuffer(EXTMEMBUFFER_HARDWARE);
}
if (threading) {
stdOut << "Initializing " << batchSize << " hardware buffers to increase thread performance..." << std::endl;
hardwareBufferCount += adapter->reserveBuffers(batchSize, EXTMEMBUFFER_HARDWARE);
stdOut << "Initialized a total of " << hardwareBufferCount << " hardware buffers!" << std::endl;
}
initialized = true;
}
#ifndef NOZIP
void initAcceleratorZip(char const *zipPath) {
if (initialized)
return;
static const std::pair<char const *, std::function<void(std::vector<char> &)>> extractFiles[] = {
{ "bitstream" , [](std::vector<char> &buffer){
stdOut << "Loading Bitstream from zip..." << std::endl;
GeneralUtils::configureFabric(buffer);
}},
{ "network.json" , [](std::vector<char> &buffer){
stdOut << "Loading network json from zip..." << std::endl;
network.reset(new Network(buffer));
}},
{ "layers.json" , [zipPath](std::vector<char> &buffer){
stdOut << "Loading layers json from zip..." << std::endl;
layers.reset(new Layers(*network, std::string(zipPath), buffer));
}}
};
zip *zipFile = zip_open(zipPath, 0, NULL);
if (zipFile == NULL) {
throw std::runtime_error("Could not open zip file " + std::string(zipPath));
}
for (auto & extractFile : extractFiles) {
std::vector<char> buffer;
struct zip_stat stats;
zip_stat_init(&stats);
if (zip_stat(zipFile, extractFile.first, 0, &stats) < 0) {
throw std::runtime_error("Could not find " + std::string(extractFile.first) + " in zip file!");
}
buffer.resize(stats.size);
zip_file *f = zip_fopen(zipFile, extractFile.first, 0);
zip_fread(f, buffer.data(), buffer.size());
zip_fclose(f);
extractFile.second(buffer);
}
zip_close(zipFile);
_init();
}
#endif
void initAccelerator(char const *networkJson, char const *layerJson) {
if (initialized)
return;
std::string networkJsonPath(networkJson);
std::string layersJsonPath(layerJson);
network.reset(new Network(networkJsonPath));
layers.reset(new Layers(*network, layersJsonPath));
_init();
}
void deinitAccelerator() {
if (!initialized)
return;
jobber.reset();
adapter.reset();
layers.reset();
network.reset();
splitBuffers.clear();
testBuffers.clear();
resultBuffers.clear();
concatBuffers.clear();
initialized = false;
}
void inference(unsigned int const batch = 1) {
unsigned int layerIndex = 0;
bool splitMode = false;
unsigned int splitIndex = 0;
unsigned int splitWeightOffset = 0;
GeneralUtils::chrono_t timer = GeneralUtils::getTimer();
std::vector<Layers::Layer>::const_iterator layerIter = layers->begin();
std::vector<Layers::Layer>::const_iterator layerSplitIter = layers->end();
while (layerIter != layers->end()) {
Layers::Layer const &layer = (*layerIter);
Layers::Layer const &nextLayer = ((layerIter + 1) == layers->end()) ? layers->getNoneLayer() : (*(layerIter + 1));
if (layer.layer & Layers::split) {
stdOut << "\t" << layer.function << "[" << layerIndex << "]" << std::endl;
for (unsigned int k = 0; k < batch; k++) {
stdOut << "\t> Prepare new buffers for batch image " << k << " and split run " << splitIndex << "..." << std::endl;
testBuffers[k]->waitPending();
testBuffers[k]->setTarget(1);
jobber->add([splitMode, k, splitIndex, &layer](){
if (!splitMode) {
GeneralUtils::chrono_t timer = GeneralUtils::getTimer();
for (unsigned int s = 0; s < layer.split; s++) {
OffloadUtils::split(*splitBuffers[k][s], *testBuffers[k], layer, s);
}
splitTime += GeneralUtils::getTime(timer);
}
GeneralUtils::chrono_t timer = GeneralUtils::getTimer();
OffloadUtils::memcpy(*testBuffers[k], *splitBuffers[k][splitIndex], layer.outSize);
OffloadUtils::down(*testBuffers[k]);
splitBufferTime += GeneralUtils::getTime(timer);
}, threading);
}
if (!splitMode) {
layerSplitIter = layerIter;
splitMode = true;
splitIndex = 0;
splitWeightOffset = 0;
}
} else if (layer.layer & Layers::merge) {
stdOut << "\t" << layer.function << "[" << layerIndex << "]" << std::endl;
if ( splitIndex < layer.merge - 1) {
stdOut << "\t> Return to split layer..." << std::endl;
splitIndex++;
splitWeightOffset += layer.weightIndex;
layerIter = layerSplitIter;
continue;
}
splitMode = false;
splitIndex = 0;
splitWeightOffset = 0;
} else if (layer.layer & Layers::conv) {
stdOut << "\t" << layer.function << "[" << layerIndex << "]" << std::endl;
stdOut << "\t> Iterations: " << layer.iterations << std::endl;
for (unsigned int j = 0; j < layer.iterations; j++) {
if (layers->useBinparams()) {
stdOut << "\t> [" << j << "] Loading weights: " << layer.weightIndex + j + splitWeightOffset << std::endl;
GeneralUtils::chrono_t weightsTimer = GeneralUtils::getTimer();
adapter->offloadWeights(layer, j + splitWeightOffset);
adapter->exec();
weightsTime += GeneralUtils::getTime(weightsTimer);
}
stdOut << "\t> [" << j << "] Offloading..." << std::endl;
for (unsigned int k = 0; k < batch; k++) {
GeneralUtils::chrono_t offloadTimer = GeneralUtils::getTimer();
OffloadAdapter::ExtMemBuffer &inputBuffer = *(testBuffers[k]);
OffloadAdapter::ExtMemBuffer &outputBuffer = adapter->getBuffer(EXTMEMBUFFER_HARDWARE);
if (j == 0) {
inputBuffer.waitPending();
inputBuffer.setTarget(1);
}
prepareTime += GeneralUtils::getTime(offloadTimer);
stdOut << "\t> [" << j << "] Process image " << k << "... ";
offloadTimer = GeneralUtils::getTimer();
adapter->offload(inputBuffer, outputBuffer, layer);
adapter->execAsync();
do {
if (!jobber->work()) {
adapter->wait();
} else {
}
} while (adapter->running());
adapter->sync();
offloadTime += GeneralUtils::getTime(offloadTimer);
stdOut << " done" << std::endl;
if (layer.iterations > 1) {
OffloadAdapter::ExtMemBuffer &concatBuffer = *(concatBuffers[k]);
if (j == 0) {
concatBuffer.setTarget(layer.iterations);
}
jobber->add([&inputBuffer, &outputBuffer, &concatBuffer, &layer, j](){
GeneralUtils::chrono_t timer = GeneralUtils::getTimer();
OffloadUtils::concat(concatBuffer, outputBuffer, layer, j);
outputBuffer.release();
concatTime += GeneralUtils::getTime(timer);
if(OffloadUtils::down(concatBuffer)) {
timer = GeneralUtils::getTimer();
OffloadUtils::swpcpy(inputBuffer, concatBuffer, layer.inSize);
OffloadUtils::down(inputBuffer);
swpcpyTime += GeneralUtils::getTime(timer);
}
}, threading || (j+1 < layer.iterations));
} else {
if (nextLayer.layer & Layers::merge) {
OffloadAdapter::ExtMemBuffer &mergeBuffer = *(mergeBuffers[k]);
if (splitIndex == 0) {
mergeBuffer.waitPending();
mergeBuffer.setTarget(nextLayer.merge);
}
stdOut << "\t> Merging split " << splitIndex << " of batch image " << k << "..." << std::endl;
jobber->add([k, splitIndex, &mergeBuffer, &outputBuffer, &layer, &nextLayer](){
GeneralUtils::chrono_t timer = GeneralUtils::getTimer();
OffloadUtils::mergeBuffer(mergeBuffer.buffer, outputBuffer.buffer, nextLayer, splitIndex);
outputBuffer.release();
OffloadUtils::down(mergeBuffer);
mergeTime += GeneralUtils::getTime(timer);
}, threading || splitIndex < (nextLayer.merge - 1));
if (splitIndex + 1 == nextLayer.merge) {
stdOut << "\t> Copy merged layer back to batch image " << k << "..." << std::endl;
jobber->add([k, &inputBuffer, &mergeBuffer, &nextLayer](){
mergeBuffer.waitPending();
GeneralUtils::chrono_t timer = GeneralUtils::getTimer();
OffloadUtils::memcpy(inputBuffer, mergeBuffer, nextLayer.outSize);
OffloadUtils::down(inputBuffer);
mergeTime += GeneralUtils::getTime(timer);
}, threading);
} else {
// the input buffer can be reused by the split layer
OffloadUtils::down(inputBuffer);
}
} else {
jobber->add([&inputBuffer, &outputBuffer](){
GeneralUtils::chrono_t timer = GeneralUtils::getTimer();
OffloadUtils::swap(inputBuffer, outputBuffer);
OffloadUtils::down(inputBuffer);
outputBuffer.release();
swapTime += GeneralUtils::getTime(timer);
}, threading);
}
}
}
} // for layer.iterations
layerIndex++;
stdOut << std::endl;
} //end if conv_layer
std::advance(layerIter, 1);
} // for layers
duration += GeneralUtils::getTime(timer);
stdOut << std::endl;
}
void singleInference(char *in, size_t const inSize, char *out, size_t const outSize) {
if (!initialized)
return;
stdOut << "Got input with " << inSize << " bytes..." << std::endl;
if (inSize != layers->getInMem()) {
stdOut << "Padding downto/to " << layers->getInMem() << " bytes..." << std::endl;
OffloadUtils::padTo((char *) testBuffers[0]->buffer, layers->getInMem(), in, inSize, layers->getInDim() * layers->getInDim());
} else {
stdOut << "Memcpy to input buffer... " << std::endl;
OffloadUtils::memcpy((char *) testBuffers[0]->buffer, in, inSize);
}
inference(1);
testBuffers[0]->wait();
testBuffers[0]->waitPending();
stdOut << "Got output with " << outSize << " bytes..." << std::endl;
if (outSize != layers->getOutMem()) {
stdOut << "Padding downto/to " << layers->getOutMem() << " bytes..." << std::endl;
OffloadUtils::padTo(out, outSize, (char *) testBuffers[0]->buffer, layers->getOutMem(), layers->getOutDim() * layers->getOutDim());
} else {
stdOut << "Memcpy to output buffer... " << std::endl;
OffloadUtils::memcpy(out, (char *) testBuffers[0]->buffer, outSize);
}
}
bool toUnsignedInt(char *from, unsigned int &to) {
std::istringstream ss(from);
unsigned int test;
if (ss >> test) {
to = test;
return true;
}
return false;
}
void printHelp(char opt = 0, char *optarg = NULL) {
if (opt != 0) {
stdErr << "Invalid parameter -" << char(opt);
if (optarg) {
stdErr << " " << optarg;
}
stdErr << std::endl;
}
srand (time(NULL));
stdErr << "QNN Testbench" << std::endl;
stdErr << "\t -i <imageCount> Number of images to process" << std::endl;
stdErr << "\t -b <batchSize>\t Batch size" << std::endl;
stdErr << "\t -t <threads> \t Number of worker threads" << std::endl;
stdErr << "\t -n <path> \t Network description json file" << std::endl;
stdErr << "\t -l <path> \t Layers description json file" << std::endl;
stdErr << "\t -z <path> \t Zip package (disables -l and -n)" << std::endl;
stdErr << "\t -v \t\t increase verbosity" << std::endl;
if (rand() % 100 < 20) {
stdErr << "\t -a \t\t baaad timings" << std::endl;
}
stdErr << "\t -h \t\t show this help" << std::endl;
}
void sigHandler(int) {
deinitAccelerator();
}
int main(int argc, char **argv) {
// cleanup hardware on STRG+C
signal(SIGINT, sigHandler);
stdOut.on();
stdErr.on();
GeneralUtils::chrono_t timer;
std::string networkJsonPath;
std::string layersJsonPath;
std::string zipPath;
unsigned int result = 0;
unsigned int correctImages = 0;
threadCount = std::thread::hardware_concurrency();
threading = true;
char *env = getenv("QNN_NETWORK_JSON");
if (env) {
networkJsonPath = env;
}
env = getenv("QNN_LAYERS_JSON");
if (env) {
layersJsonPath = env;
}
int opt;
while ((opt = getopt(argc, argv, "ahvn:l:i:t:b:z:")) != -1) {
switch (opt) {
case 'n':
networkJsonPath = optarg;
break;
case 'l':
layersJsonPath = optarg;
break;
case 'z':
zipPath = optarg;
break;
case 'v':
verbose = true;
break;
case 'a':
inputTiming = true;
break;
case 'i':
if (!toUnsignedInt(optarg, imageCount)) {
printHelp(opt, optarg);
return 1;
}
break;
case 't':
if (!toUnsignedInt(optarg, threadCount)) {
printHelp(opt, optarg);
return 1;
}
if (threadCount == 0) {
threading = false;
}
break;
case 'b':
if (!toUnsignedInt(optarg, batchSize)) {
printHelp(opt, optarg);
return 1;
}
batchSize = (batchSize == 0) ? 1 : batchSize;
break;
case '?':
case 'h':
printHelp();
return 0;
default:
printHelp(opt);
return 1;
break;
}
}
if (zipPath.size() == 0) {
if (networkJsonPath.size() == 0) {
stdErr << "Please specifiy network json file through n parameter or QNN_NETWORK_JSON enviroment variable!" << std::endl;
printHelp();
return 1;
}
if (layersJsonPath.size() == 0) {
stdErr << "Please specifiy layers json file through l parameter or QNN_LAYERS_JSON enviroment variable!" << std::endl;
printHelp();
return 1;
}
}
unsigned const int batchIterations = std::ceil((float) imageCount/ (float) batchSize);
try {
Logger::Verbosity verboseLevel(verbose);
stdOut <<verboseIgnore;
stdOut << "QNN Testbench" << std::endl;
stdOut << "Images to test: " << imageCount << std::endl;
stdOut << "Batch size: " << batchSize << std::endl;
stdOut << "Batch iterations: " << batchIterations << std::endl;
stdOut << "Threading: " << threading << std::endl;
if (threading) {
stdOut << "Worker threads: " << threadCount << std::endl;
} else {
threadCount = 0;
}
stdOut << std::endl;
stdOut << verboseLevel;
stdErr << verboseLevel;
if (zipPath.size() == 0) {
initAccelerator(networkJsonPath.c_str(), layersJsonPath.c_str());
} else {
#ifndef NOZIP
initAcceleratorZip(zipPath.c_str());
#else
throw std::runtime_error("zip capability was not compiled in");
#endif
}
stdOut << "Network is " << layers->getNetwork() << std::endl;
if (layers->size() == 0) {
throw std::runtime_error("There are no layers specified, maybe layer_skip is to high!");
}
// Load the verification images
std::vector<char> resultImage;
std::string resultFilename = layers->getVerificationImagePath();
stdOut << "Loading result images from " << resultFilename << "..." << std::endl;
GeneralUtils::readBinaryFile(resultImage, resultFilename);
stdOut << "read " << resultImage.size() << " bytes!" << std::endl;
// load test images from binary files
std::vector<char> inputImage;
std::string imageFilename = layers->getInputImagePath();
stdOut << "Loading test images from " << imageFilename << "..." << std::endl;
GeneralUtils::readBinaryFile(inputImage, imageFilename);
stdOut << "read " << inputImage.size() << " bytes!" << std::endl;
OffloadAdapter::ExtMemBuffer &inputImagePadded = adapter->getBuffer(EXTMEMBUFFER_LOCAL);
if (inputImage.size() < layers->getInMem()) {
stdOut << "Input image only contains " << inputImage.size() << " bytes, need a padding to " << layers->getInMem() << " bytes..." << std::endl;
OffloadUtils::padTo((char *) inputImagePadded.buffer, layers->getInMem(), (char *) inputImage.data(), inputImage.size() , layers->getInDim() * layers->getInDim());
} else {
std::memcpy(inputImagePadded.buffer, inputImage.data(), layers->getInMem());
stdOut << "Copied " << layers->getInMem() << " bytes from input image" << std::endl;
}
stdOut << std::endl << std::endl;
for (unsigned int i = 0; i < batchIterations; i++) {
unsigned int const currentBatchSize = ((i * batchSize) + batchSize > imageCount) ? imageCount - (i * batchSize) : batchSize;
stdOut << verboseIgnore << "Batch run " << i << " processing " << currentBatchSize << " images" << std::endl << verboseLevel;
for (unsigned int k = 0; k < currentBatchSize; k++) {
testBuffers[k]->setTarget(1);
jobber->add([k, &inputImagePadded](){
GeneralUtils::chrono_t timer = GeneralUtils::getTimer();
OffloadUtils::memcpy(*testBuffers[k], inputImagePadded, inputImagePadded.size());
OffloadUtils::down(*testBuffers[k]);
inputTime += GeneralUtils::getTime(timer);
}, threading && inputTiming);
}
inference(currentBatchSize);
for (unsigned int k = 0; k < currentBatchSize; k++) {
stdOut << "\t> Get result of image " << k << std::endl;
GeneralUtils::chrono_t timer = GeneralUtils::getTimer();
testBuffers[k]->waitPending();
OffloadUtils::memcpy(*resultBuffers[k], *testBuffers[k], layers->getOutMem());
resultTime += GeneralUtils::getTime(timer);
stdOut << "\t> Copied " << layers->getOutMem() << " bytes from the result" << std::endl;
}
for (int k = 0; k < currentBatchSize; k++) {
// dump_to_file("/tmp/accel_out_" + std::to_string(k) + ".bin",(char *) resultBuffers[k]->buffer, layers->getOutMem());
unsigned int const currentImage = (i * batchSize) + k;
if (OffloadUtils::verifyBuffers((ExtMemWord *) resultImage.data(), resultBuffers[k]->buffer, *network, layers->getOutCh(), layers->getOutDim(), stdErr)) {
stdOut << "Verification of image " << currentImage << " succeeded!" << std::endl;
correctImages++;
} else {
const unsigned long long outPixels = layers->getOutDim() * layers->getOutDim();
unsigned long long const correctPixels = outPixels - OffloadUtils::tellPixels();
stdErr << verboseIgnore << "Verification of image " << currentImage << " failed!" << std::endl;
stdErr << correctPixels << "/" << outPixels << " pixels are correct, accuracy " << std::fixed << std::setprecision(2) << (float) 100 * ((float) correctPixels / (float) outPixels) << "%" << std::endl;
stdErr << verboseLevel;
result = 1;
}
}
stdOut << std::endl;
} // for batchIterations
duration += resultTime;
if (inputTiming) {
duration += inputTime;
}
size_t maxLen = std::to_string(duration).length();
stdOut << verboseIgnore << std::endl;
stdOut << correctImages << "/" << imageCount << " images correct, accuracy " << (100.0 * (float) correctImages / imageCount) << "%" << std::endl;
stdOut << "━┳━Overall " << std::setw(maxLen) << duration << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) duration / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) duration / 1000000) << "s, 100.00%" << std::endl;
if (inputTiming) {
stdOut << " ┣━Inputs " << std::setw(maxLen) << inputTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) inputTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) inputTime / 1000000) << "s, " << std::setw(6) << ((float) inputTime * 100 / duration) << "%" << std::endl;
}
stdOut << " ┣┳━Splitting " << std::setw(maxLen) << splitTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) splitTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) splitTime / 1000000) << "s, " << std::setw(6) << ((float) splitTime * 100 / duration) << "%" << std::endl;
stdOut << " ┃┣━Prepare " << std::setw(maxLen) << splitBufferTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) splitBufferTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) splitBufferTime / 1000000) << "s, " << std::setw(6) << ((float) splitBufferTime * 100 / duration) << "%" << std::endl;
stdOut << " ┣┻━Merging " << std::setw(maxLen) << mergeTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) mergeTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) mergeTime / 1000000) << "s, " << std::setw(6) << ((float) mergeTime * 100 / duration) << "%" << std::endl;
stdOut << " ┣━Weights " << std::setw(maxLen) << weightsTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) weightsTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) weightsTime / 1000000) << "s, " << std::setw(6) << ((float) weightsTime * 100 / duration) << "%" << std::endl;
stdOut << " ┣┳━Prepare " << std::setw(maxLen) << prepareTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) prepareTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) prepareTime / 1000000) << "s, " << std::setw(6) << ((float) prepareTime * 100 / duration) << "%" << std::endl;
stdOut << " ┃┣━Offload " << std::setw(maxLen) << offloadTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) offloadTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) offloadTime / 1000000) << "s, " << std::setw(6) << ((float) offloadTime * 100 / duration) << "%" << std::endl;
stdOut << " ┃┣┳━Concat " << std::setw(maxLen) << concatTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) concatTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) concatTime / 1000000) << "s, " << std::setw(6) << ((float) concatTime * 100 / duration) << "%" << std::endl;
stdOut << " ┃┃┗━SwapCpy " << std::setw(maxLen) << swpcpyTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) swpcpyTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) swpcpyTime / 1000000) << "s, " << std::setw(6) << ((float) swpcpyTime * 100 / duration) << "%" << std::endl;
stdOut << " ┃┗━Swap " << std::setw(maxLen) << swapTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) swapTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) swapTime / 1000000) << "s, " << std::setw(6) << ((float) swapTime * 100 / duration) << "%" << std::endl;
stdOut << " ┗━Results " << std::setw(maxLen) << resultTime << " us, " << std::fixed << std::setprecision(2) << std::setw(maxLen) << ((float) resultTime / 1000) << " ms, " << std::setw(maxLen - 3) << ((float) resultTime / 1000000) << "s, " << std::setw(6) << ((float) resultTime * 100 / duration) << "%" << std::endl;
stdOut << "> " << std::fixed << std::setprecision(4) << (float) (1000000 * imageCount) / duration << " fps" << std::endl;
deinitAccelerator();
} catch(...) {
deinitAccelerator();
throw;
}
return result;
}
| 47.156809 | 347 | 0.54441 | [
"vector"
] |
9153cbe822b22c0ffc1bc022546bf8b4a6a5929b | 1,815 | cpp | C++ | 1v1 Brawlers/Final Project/player.cpp | shravanhariharan2/1v1-brawlers | 0ac3b3d7410b0c7bb7566409ec5b3e6ae08675c8 | [
"MIT"
] | null | null | null | 1v1 Brawlers/Final Project/player.cpp | shravanhariharan2/1v1-brawlers | 0ac3b3d7410b0c7bb7566409ec5b3e6ae08675c8 | [
"MIT"
] | null | null | null | 1v1 Brawlers/Final Project/player.cpp | shravanhariharan2/1v1-brawlers | 0ac3b3d7410b0c7bb7566409ec5b3e6ae08675c8 | [
"MIT"
] | null | null | null | #include "player.h"
#include "moves.h"
#include <SFML/Graphics.hpp>
#include<vector>
player::player() {
name = ""; health = 20; atk = 0; def = 0; accuracy = 0; crit = 0;
}
player::player(string nameIn, int healthIn, int atkIn, int defIn, int accIn, int critIn, int speedIn, vector<moves> movesIn) {
name = nameIn;
health = healthIn;
atk = atkIn;
def = defIn;
accuracy = accIn;
crit = critIn;
speed = speedIn;
playerMoves = movesIn;
}
string player::getName() {
return name;
}
int player::getHealth() {
return health;
}
int player::getAtk() {
return atk;
}
int player::getDef() {
return def;
}
int player::getAcc() {
return accuracy;
}
int player::getCrit() {
return crit;
}
int player::getSpeed() {
return speed;
}
void player::setName(string nameIn) {
name = nameIn;
}
void player::setHealth(int healthIn) {
health = healthIn;
}
void player::setAtk(int atkIn) {
atk = atkIn;
}
void player::setDef(int defIn) {
def = defIn;
}
void player::setAcc(int accIn) {
accuracy = accIn;
}
void player::setCrit(int critIn) {
crit = critIn;
}
void player::setSpeed(int speedIn) {
speed = speedIn;
}
void player::learnMove(moves moveIn) {
playerMoves.push_back(moveIn);
}
string player::displayMoves() {
string dispMoves = "Moves: ";
for (int i = 0; i < playerMoves.size(); i++) {
dispMoves += "\n" + to_string(i+1) + ". " + playerMoves[i].getName();
}
return dispMoves;
}
string player::dispStats() {
string stats = "\nHealth: " + to_string(health);
stats += "\nAttack: " + to_string(atk);
stats += "\nDefense: " + to_string(def);
stats += "\nAccuracy: " + to_string(accuracy);
stats += "\nCritical Strike Chance: " + to_string(crit);
stats += "\nSpeed: " + to_string(speed);
return stats;
}
| 20.625 | 127 | 0.625895 | [
"vector"
] |
91549051e2e133ff37bf9abd72496e66de6f792a | 766 | cpp | C++ | kattis_done/treasurehunt.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | 5 | 2019-03-17T01:33:19.000Z | 2021-06-25T09:50:45.000Z | kattis_done/treasurehunt.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | null | null | null | kattis_done/treasurehunt.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
bool isOut(int x, int y, int w, int l) {
return x < 0 || x >= w || y < 0 || y >= l;
}
int main() {
int r, c;
cin >> r >> c;
vector<string> m(r, "");
for (int i = 0; i < r ; i++) {
cin >> m[i];
}
vector<vector<bool> > e(r, vector<bool> (c, false));
int pr = 0, pc = 0;
int cnt = 0;
bool found = true;
while (!isOut(pc, pr, c, r) && m[pr][pc] != 'T') {
// cout << cnt << endl;
cnt++;
if (e[pr][pc]) {
found = false;
break;
}
e[pr][pc] = true;
if (m[pr][pc] == 'N') pr--;
else if (m[pr][pc] == 'E') pc++;
else if (m[pr][pc] == 'W') pc--;
else pr++;
}
if (!found) cout << "Lost" << endl;
else if (isOut(pr, pc, r, c)) cout << "Out" << endl;
else cout << cnt << endl;
return 0;
} | 21.277778 | 53 | 0.472585 | [
"vector"
] |
91609dac0e3c3d03171d4b79732dab79ae1f915e | 56,407 | cc | C++ | src/kudu/fs/log_block_manager.cc | fxlambda-twickly5/kudu | 63fdc0c9f49e55ac043c9ba25e9b755b696d405d | [
"Apache-2.0"
] | 1 | 2019-12-02T11:52:01.000Z | 2019-12-02T11:52:01.000Z | src/kudu/fs/log_block_manager.cc | fxlambda-twickly5/kudu | 63fdc0c9f49e55ac043c9ba25e9b755b696d405d | [
"Apache-2.0"
] | null | null | null | src/kudu/fs/log_block_manager.cc | fxlambda-twickly5/kudu | 63fdc0c9f49e55ac043c9ba25e9b755b696d405d | [
"Apache-2.0"
] | 1 | 2019-12-02T11:52:08.000Z | 2019-12-02T11:52:08.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "kudu/fs/log_block_manager.h"
#include <algorithm>
#include <mutex>
#include "kudu/fs/block_manager_metrics.h"
#include "kudu/fs/block_manager_util.h"
#include "kudu/fs/data_dirs.h"
#include "kudu/fs/fs.pb.h"
#include "kudu/gutil/callback.h"
#include "kudu/gutil/integral_types.h"
#include "kudu/gutil/map-util.h"
#include "kudu/gutil/strings/strcat.h"
#include "kudu/gutil/strings/strip.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/gutil/walltime.h"
#include "kudu/util/alignment.h"
#include "kudu/util/atomic.h"
#include "kudu/util/env.h"
#include "kudu/util/env_util.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/locks.h"
#include "kudu/util/malloc.h"
#include "kudu/util/metrics.h"
#include "kudu/util/mutex.h"
#include "kudu/util/path_util.h"
#include "kudu/util/pb_util.h"
#include "kudu/util/random_util.h"
#include "kudu/util/scoped_cleanup.h"
#include "kudu/util/stopwatch.h"
#include "kudu/util/test_util_prod.h"
#include "kudu/util/threadpool.h"
#include "kudu/util/trace.h"
DECLARE_bool(enable_data_block_fsync);
DECLARE_bool(block_manager_lock_dirs);
// TODO(unknown): How should this be configured? Should provide some guidance.
DEFINE_uint64(log_container_max_size, 10LU * 1024 * 1024 * 1024,
"Maximum size (soft) of a log container");
TAG_FLAG(log_container_max_size, advanced);
DEFINE_uint64(log_container_preallocate_bytes, 32LU * 1024 * 1024,
"Number of bytes to preallocate in a log container when "
"creating new blocks. Set to 0 to disable preallocation");
TAG_FLAG(log_container_preallocate_bytes, advanced);
DEFINE_bool(log_block_manager_test_hole_punching, true,
"Ensure hole punching is supported by the underlying filesystem");
TAG_FLAG(log_block_manager_test_hole_punching, advanced);
TAG_FLAG(log_block_manager_test_hole_punching, unsafe);
METRIC_DEFINE_gauge_uint64(server, log_block_manager_bytes_under_management,
"Bytes Under Management",
kudu::MetricUnit::kBytes,
"Number of bytes of data blocks currently under management");
METRIC_DEFINE_gauge_uint64(server, log_block_manager_blocks_under_management,
"Blocks Under Management",
kudu::MetricUnit::kBlocks,
"Number of data blocks currently under management");
METRIC_DEFINE_counter(server, log_block_manager_containers,
"Number of Block Containers",
kudu::MetricUnit::kLogBlockContainers,
"Number of log block containers");
METRIC_DEFINE_counter(server, log_block_manager_full_containers,
"Number of Full Block Counters",
kudu::MetricUnit::kLogBlockContainers,
"Number of full log block containers");
METRIC_DEFINE_counter(server, log_block_manager_unavailable_containers,
"Number of Unavailable Log Block Containers",
kudu::MetricUnit::kLogBlockContainers,
"Number of non-full log block containers that are under root paths "
"whose disks are full");
namespace kudu {
namespace fs {
using internal::LogBlock;
using internal::LogBlockContainer;
using pb_util::ReadablePBContainerFile;
using pb_util::WritablePBContainerFile;
using std::unordered_set;
using strings::Substitute;
namespace internal {
////////////////////////////////////////////////////////////
// LogBlockManagerMetrics
////////////////////////////////////////////////////////////
// Metrics container associated with the log block manager.
//
// Includes implementation-agnostic metrics as well as some that are
// specific to the log block manager.
struct LogBlockManagerMetrics {
explicit LogBlockManagerMetrics(const scoped_refptr<MetricEntity>& metric_entity);
// Implementation-agnostic metrics.
BlockManagerMetrics generic_metrics;
scoped_refptr<AtomicGauge<uint64_t> > bytes_under_management;
scoped_refptr<AtomicGauge<uint64_t> > blocks_under_management;
scoped_refptr<Counter> containers;
scoped_refptr<Counter> full_containers;
};
#define MINIT(x) x(METRIC_log_block_manager_##x.Instantiate(metric_entity))
#define GINIT(x) x(METRIC_log_block_manager_##x.Instantiate(metric_entity, 0))
LogBlockManagerMetrics::LogBlockManagerMetrics(const scoped_refptr<MetricEntity>& metric_entity)
: generic_metrics(metric_entity),
GINIT(bytes_under_management),
GINIT(blocks_under_management),
MINIT(containers),
MINIT(full_containers) {
}
#undef GINIT
#undef MINIT
////////////////////////////////////////////////////////////
// LogBlockContainer
////////////////////////////////////////////////////////////
// A single block container belonging to the log-backed block manager.
//
// A container may only be used to write one WritableBlock at a given time.
// However, existing blocks may be deleted concurrently. As such, almost
// all container functions must be reentrant, even if the container itself
// is logically thread unsafe (i.e. multiple clients calling WriteData()
// concurrently will produce nonsensical container data). Thread unsafe
// functions are marked explicitly.
class LogBlockContainer {
public:
static const char* kMagic;
// Creates a new block container in 'dir'.
static Status Create(LogBlockManager* block_manager,
DataDir* dir,
gscoped_ptr<LogBlockContainer>* container);
// Opens an existing block container in 'dir'.
//
// Every container is comprised of two files: "<dir>/<id>.data" and
// "<dir>/<id>.metadata". Together, 'dir' and 'id' fully describe both
// files.
//
// Returns Status::Aborted() in the case that the metadata and data files
// both appear to have no data (e.g. due to a crash just after creating
// one of them but before writing any records).
static Status Open(LogBlockManager* block_manager,
DataDir* dir,
const std::string& id,
gscoped_ptr<LogBlockContainer>* container);
// Indicates that the writing of 'block' is finished. If successful,
// adds the block to the block manager's in-memory maps.
//
// Returns a status that is either the same as 's' (if !s.ok()) or
// potentially different (if s.ok() and FinishBlock() failed).
//
// After returning, this container has been released to the block manager
// and may no longer be used in the context of writing 'block'.
Status FinishBlock(const Status& s, WritableBlock* block);
// Frees the space associated with a block at 'offset' and 'length'. This
// is a physical operation, not a logical one; a separate AppendMetadata()
// is required to record the deletion in container metadata.
//
// The on-disk effects of this call are made durable only after SyncData().
Status DeleteBlock(int64_t offset, int64_t length);
// Appends 'data' to this container's data file.
//
// The on-disk effects of this call are made durable only after SyncData().
Status AppendData(const Slice& data);
// See RWFile::Read().
Status ReadData(int64_t offset, size_t length,
Slice* result, uint8_t* scratch) const;
// Appends 'pb' to this container's metadata file.
//
// The on-disk effects of this call are made durable only after SyncMetadata().
Status AppendMetadata(const BlockRecordPB& pb);
// Asynchronously flush this container's data file from 'offset' through
// to 'length'.
//
// Does not guarantee data durability; use SyncData() for that.
Status FlushData(int64_t offset, int64_t length);
// Asynchronously flush this container's metadata file (all dirty bits).
//
// Does not guarantee metadata durability; use SyncMetadata() for that.
//
// TODO(unknown): Add support to just flush a range.
Status FlushMetadata();
// Synchronize this container's data file with the disk. On success,
// guarantees that the data is made durable.
//
// TODO(unknown): Add support to synchronize just a range.
Status SyncData();
// Synchronize this container's metadata file with the disk. On success,
// guarantees that the metadata is made durable.
//
// TODO(unknown): Add support to synchronize just a range.
Status SyncMetadata();
// Reads the container's metadata from disk, sanity checking and
// returning the records.
Status ReadContainerRecords(deque<BlockRecordPB>* records) const;
// Updates 'total_bytes_written_', marking this container as full if
// needed. Should only be called when a block is fully written, as it
// will round up the container data file's position.
//
// This function is thread unsafe.
void UpdateBytesWritten(int64_t more_bytes);
// Run a task on this container's data directory thread pool.
//
// Normally the task is performed asynchronously. However, if submission to
// the pool fails, it runs synchronously on the current thread.
void ExecClosure(const Closure& task);
// Produces a debug-friendly string representation of this container.
string ToString() const;
// Simple accessors.
LogBlockManager* block_manager() const { return block_manager_; }
int64_t total_bytes_written() const { return total_bytes_written_; }
bool full() const {
return total_bytes_written_ >= FLAGS_log_container_max_size;
}
const LogBlockManagerMetrics* metrics() const { return metrics_; }
const DataDir* data_dir() const { return data_dir_; }
DataDir* mutable_data_dir() const { return data_dir_; }
const PathInstanceMetadataPB* instance() const { return data_dir_->instance()->metadata(); }
private:
LogBlockContainer(LogBlockManager* block_manager, DataDir* data_dir,
gscoped_ptr<WritablePBContainerFile> metadata_file,
gscoped_ptr<RWFile> data_file);
// Performs sanity checks on a block record.
void CheckBlockRecord(const BlockRecordPB& record,
uint64_t data_file_size) const;
// Preallocate enough space to ensure that an append of 'next_append_bytes'
// can be satisfied by this container.
//
// Does nothing if preallocation is disabled.
Status EnsurePreallocated(size_t next_append_bytes);
// The owning block manager. Must outlive the container itself.
LogBlockManager* const block_manager_;
// The data directory where the container lives.
DataDir* data_dir_;
// Offset up to which we have preallocated bytes.
int64_t preallocated_offset_ = 0;
// Opened file handles to the container's files.
//
// RWFile is not thread safe so access to each writer must be
// serialized through a (sleeping) mutex. We use different mutexes to
// avoid contention in cases where only one writer is needed.
gscoped_ptr<WritablePBContainerFile> metadata_file_;
Mutex metadata_file_lock_;
gscoped_ptr<RWFile> data_file_;
Mutex data_file_lock_;
// The amount of data written thus far in the container.
int64_t total_bytes_written_ = 0;
// The metrics. Not owned by the log container; it has the same lifespan
// as the block manager.
const LogBlockManagerMetrics* metrics_;
DISALLOW_COPY_AND_ASSIGN(LogBlockContainer);
};
LogBlockContainer::LogBlockContainer(
LogBlockManager* block_manager,
DataDir* data_dir,
gscoped_ptr<WritablePBContainerFile> metadata_file,
gscoped_ptr<RWFile> data_file)
: block_manager_(block_manager),
data_dir_(data_dir),
metadata_file_(std::move(metadata_file)),
data_file_(std::move(data_file)),
metrics_(block_manager->metrics()) {
}
Status LogBlockContainer::Create(LogBlockManager* block_manager,
DataDir* dir,
gscoped_ptr<LogBlockContainer>* container) {
string common_path;
string metadata_path;
string data_path;
Status metadata_status;
Status data_status;
gscoped_ptr<RWFile> metadata_writer;
gscoped_ptr<RWFile> data_file;
RWFileOptions wr_opts;
wr_opts.mode = Env::CREATE_NON_EXISTING;
// Repeat in the event of a container id collision (unlikely).
//
// When looping, we delete any created-and-orphaned files.
do {
if (metadata_writer) {
block_manager->env()->DeleteFile(metadata_path);
}
common_path = JoinPathSegments(dir->dir(),
block_manager->oid_generator()->Next());
metadata_path = StrCat(common_path, LogBlockManager::kContainerMetadataFileSuffix);
metadata_status = block_manager->env()->NewRWFile(wr_opts,
metadata_path,
&metadata_writer);
if (data_file) {
block_manager->env()->DeleteFile(data_path);
}
data_path = StrCat(common_path, LogBlockManager::kContainerDataFileSuffix);
RWFileOptions rw_opts;
rw_opts.mode = Env::CREATE_NON_EXISTING;
data_status = block_manager->env()->NewRWFile(rw_opts,
data_path,
&data_file);
} while (PREDICT_FALSE(metadata_status.IsAlreadyPresent() ||
data_status.IsAlreadyPresent()));
if (metadata_status.ok() && data_status.ok()) {
gscoped_ptr<WritablePBContainerFile> metadata_file(
new WritablePBContainerFile(std::move(metadata_writer)));
RETURN_NOT_OK(metadata_file->Init(BlockRecordPB()));
container->reset(new LogBlockContainer(block_manager,
dir,
std::move(metadata_file),
std::move(data_file)));
VLOG(1) << "Created log block container " << (*container)->ToString();
}
// Prefer metadata status (arbitrarily).
return !metadata_status.ok() ? metadata_status : data_status;
}
Status LogBlockContainer::Open(LogBlockManager* block_manager,
DataDir* dir,
const string& id,
gscoped_ptr<LogBlockContainer>* container) {
Env* env = block_manager->env();
string common_path = JoinPathSegments(dir->dir(), id);
string metadata_path = StrCat(common_path, LogBlockManager::kContainerMetadataFileSuffix);
string data_path = StrCat(common_path, LogBlockManager::kContainerDataFileSuffix);
// Check that both the metadata and data files exist and have valid lengths.
// This covers a commonly seen case at startup, where the previous incarnation
// of the server crashed due to "too many open files" just as it was trying
// to create a data file. This orphans an empty metadata file, which we can
// safely delete.
{
uint64_t metadata_size = 0;
uint64_t data_size = 0;
Status s = env->GetFileSize(metadata_path, &metadata_size);
if (s.IsNotFound()) {
LOG(WARNING) << "Missing metadata path at " << metadata_path;
} else {
RETURN_NOT_OK_PREPEND(s, "unable to determine metadata file size");
}
s = env->GetFileSize(data_path, &data_size);
if (s.IsNotFound()) {
LOG(WARNING) << "Missing data path at " << data_path;
} else {
RETURN_NOT_OK_PREPEND(s, "unable to determine data file size");
}
if (metadata_size < pb_util::kPBContainerMinimumValidLength && data_size == 0) {
LOG(WARNING) << "Data and metadata files for container " << common_path
<< " are both missing or empty. Deleting container.";
IgnoreResult(env->DeleteFile(metadata_path));
IgnoreResult(env->DeleteFile(data_path));
return Status::Aborted("orphaned empty metadata and data files removed");
}
}
// Open the existing metadata and data files for writing.
gscoped_ptr<RWFile> metadata_writer;
RWFileOptions wr_opts;
wr_opts.mode = Env::OPEN_EXISTING;
RETURN_NOT_OK(env->NewRWFile(wr_opts,
metadata_path,
&metadata_writer));
gscoped_ptr<WritablePBContainerFile> metadata_pb_writer(
new WritablePBContainerFile(std::move(metadata_writer)));
RETURN_NOT_OK(metadata_pb_writer->Reopen());
gscoped_ptr<RWFile> data_file;
RWFileOptions rw_opts;
rw_opts.mode = Env::OPEN_EXISTING;
RETURN_NOT_OK(env->NewRWFile(rw_opts,
data_path,
&data_file));
uint64_t data_file_size;
RETURN_NOT_OK(data_file->Size(&data_file_size));
// Create the in-memory container and populate it.
gscoped_ptr<LogBlockContainer> open_container(new LogBlockContainer(block_manager,
dir,
std::move(metadata_pb_writer),
std::move(data_file)));
open_container->preallocated_offset_ = data_file_size;
VLOG(1) << "Opened log block container " << open_container->ToString();
container->swap(open_container);
return Status::OK();
}
Status LogBlockContainer::ReadContainerRecords(deque<BlockRecordPB>* records) const {
string metadata_path = metadata_file_->filename();
gscoped_ptr<RandomAccessFile> metadata_reader;
RETURN_NOT_OK(block_manager()->env()->NewRandomAccessFile(metadata_path, &metadata_reader));
ReadablePBContainerFile pb_reader(std::move(metadata_reader));
RETURN_NOT_OK(pb_reader.Open());
uint64_t data_file_size;
RETURN_NOT_OK(data_file_->Size(&data_file_size));
deque<BlockRecordPB> local_records;
Status read_status;
while (true) {
local_records.resize(local_records.size() + 1);
read_status = pb_reader.ReadNextPB(&local_records.back());
if (!read_status.ok()) {
// Drop the last element; we didn't use it.
local_records.pop_back();
break;
}
const auto& record = local_records.back();
if (PREDICT_FALSE(data_file_size < record.offset() + record.length())) {
// KUDU-1657: When opening a container in read-only mode which is actively
// being written to by another lbm, we must reinspect the data file's size
// frequently in order to account for the latest appends. Inspecting the
// file size is expensive, so we only do it when the metadata indicates
// that additional data has been written to the file.
RETURN_NOT_OK(data_file_->Size(&data_file_size));
}
CheckBlockRecord(record, data_file_size);
}
// NOTE: 'read_status' will never be OK here.
if (PREDICT_TRUE(read_status.IsEndOfFile())) {
// We've reached the end of the file without any problems.
records->swap(local_records);
return Status::OK();
}
if (read_status.IsIncomplete()) {
// We found a partial trailing record in a version of the pb container file
// format that can reliably detect this. Consider this a failed partial
// write and truncate the metadata file to remove this partial record.
uint64_t truncate_offset = pb_reader.offset();
LOG(WARNING) << "Log block manager: Found partial trailing metadata record in container "
<< ToString() << ": "
<< "Truncating metadata file to last valid offset: " << truncate_offset;
gscoped_ptr<RWFile> file;
RWFileOptions opts;
opts.mode = Env::OPEN_EXISTING;
RETURN_NOT_OK(block_manager_->env()->NewRWFile(opts, metadata_path, &file));
RETURN_NOT_OK(file->Truncate(truncate_offset));
RETURN_NOT_OK(file->Close());
// Reopen the PB writer so that it will refresh its metadata about the
// underlying file and resume appending to the new end of the file.
RETURN_NOT_OK(metadata_file_->Reopen());
records->swap(local_records);
return Status::OK();
}
// If we've made it here, we've found (and are returning) an unrecoverable error.
return read_status;
}
void LogBlockContainer::CheckBlockRecord(const BlockRecordPB& record,
uint64_t data_file_size) const {
if (record.op_type() == CREATE &&
(!record.has_offset() ||
!record.has_length() ||
record.offset() < 0 ||
record.length() < 0 ||
record.offset() + record.length() > data_file_size)) {
LOG(FATAL) << "Found malformed block record in data file: " << data_file_->filename()
<< "\nRecord: " << record.DebugString()
<< "\nData file size: " << data_file_size;
}
}
Status LogBlockContainer::FinishBlock(const Status& s, WritableBlock* block) {
auto cleanup = MakeScopedCleanup([&]() {
block_manager_->MakeContainerAvailable(this);
});
if (!s.ok()) {
// Early return; 'cleanup' makes the container available again.
return s;
}
// A failure when syncing the container means the container (and its new
// blocks) may be missing the next time the on-disk state is reloaded.
//
// As such, it's not correct to add the block to in-memory state unless
// synchronization succeeds. In the worst case, this means the data file
// will have written some garbage that can be expunged during a GC.
RETURN_NOT_OK(block_manager()->SyncContainer(*this));
// Each call to AppendData() updated 'total_bytes_written_' to reflect the
// new block. Nevertheless, we must call UpdateBytesWritten() whenever a
// block is finished in order to prepare for the next block.
CHECK(block_manager()->AddLogBlock(this, block->id(),
total_bytes_written_ - block->BytesAppended(),
block->BytesAppended()));
UpdateBytesWritten(0);
if (full() && block_manager()->metrics()) {
block_manager()->metrics()->full_containers->Increment();
}
return Status::OK();
}
Status LogBlockContainer::DeleteBlock(int64_t offset, int64_t length) {
DCHECK_GE(offset, 0);
DCHECK_GE(length, 0);
// Guaranteed by UpdateBytesWritten().
DCHECK_EQ(0, offset % instance()->filesystem_block_size_bytes());
// It is invalid to punch a zero-size hole.
if (length) {
std::lock_guard<Mutex> l(data_file_lock_);
// Round up to the nearest filesystem block so that the kernel will
// actually reclaim disk space.
//
// It's OK if we exceed the file's total size; the kernel will truncate
// our request.
return data_file_->PunchHole(offset, KUDU_ALIGN_UP(
length, instance()->filesystem_block_size_bytes()));
}
return Status::OK();
}
Status LogBlockContainer::AppendData(const Slice& data) {
RETURN_NOT_OK(EnsurePreallocated(data.size()));
{
std::lock_guard<Mutex> l(data_file_lock_);
RETURN_NOT_OK(data_file_->Write(total_bytes_written_, data));
}
total_bytes_written_ += data.size();
// This append may have changed the container size if:
// 1. It was large enough that it blew out the preallocated space.
// 2. Preallocation was disabled.
if (total_bytes_written_ > preallocated_offset_) {
RETURN_NOT_OK(data_dir_->RefreshIsFull(DataDir::RefreshMode::ALWAYS));
}
return Status::OK();
}
Status LogBlockContainer::ReadData(int64_t offset, size_t length,
Slice* result, uint8_t* scratch) const {
DCHECK_GE(offset, 0);
return data_file_->Read(offset, length, result, scratch);
}
Status LogBlockContainer::AppendMetadata(const BlockRecordPB& pb) {
// Note: We don't check for sufficient disk space for metadata writes in
// order to allow for block deletion on full disks.
std::lock_guard<Mutex> l(metadata_file_lock_);
return metadata_file_->Append(pb);
}
Status LogBlockContainer::FlushData(int64_t offset, int64_t length) {
DCHECK_GE(offset, 0);
DCHECK_GE(length, 0);
std::lock_guard<Mutex> l(data_file_lock_);
return data_file_->Flush(RWFile::FLUSH_ASYNC, offset, length);
}
Status LogBlockContainer::FlushMetadata() {
std::lock_guard<Mutex> l(metadata_file_lock_);
return metadata_file_->Flush();
}
Status LogBlockContainer::SyncData() {
if (FLAGS_enable_data_block_fsync) {
std::lock_guard<Mutex> l(data_file_lock_);
return data_file_->Sync();
}
return Status::OK();
}
Status LogBlockContainer::SyncMetadata() {
if (FLAGS_enable_data_block_fsync) {
std::lock_guard<Mutex> l(metadata_file_lock_);
return metadata_file_->Sync();
}
return Status::OK();
}
Status LogBlockContainer::EnsurePreallocated(size_t next_append_bytes) {
if (!FLAGS_log_container_preallocate_bytes) {
return Status::OK();
}
// If the last write blew out the preallocation window, or if the next write
// exceeds it, we need to preallocate another chunk.
if (total_bytes_written_ > preallocated_offset_ ||
next_append_bytes > preallocated_offset_ - total_bytes_written_) {
int64_t off = std::max(preallocated_offset_, total_bytes_written_);
int64_t len = FLAGS_log_container_preallocate_bytes;
{
std::lock_guard<Mutex> l(data_file_lock_);
RETURN_NOT_OK(data_file_->PreAllocate(off, len));
}
RETURN_NOT_OK(data_dir_->RefreshIsFull(DataDir::RefreshMode::ALWAYS));
VLOG(2) << Substitute("Preallocated $0 bytes at offset $1 in container $2",
len, off, ToString());
preallocated_offset_ = off + len;
}
return Status::OK();
}
void LogBlockContainer::UpdateBytesWritten(int64_t more_bytes) {
DCHECK_GE(more_bytes, 0);
total_bytes_written_ += more_bytes;
// The number of bytes is rounded up to the nearest filesystem block so
// that each Kudu block is guaranteed to be on a filesystem block
// boundary. This guarantees that the disk space can be reclaimed when
// the block is deleted.
total_bytes_written_ = KUDU_ALIGN_UP(total_bytes_written_,
instance()->filesystem_block_size_bytes());
if (full()) {
VLOG(1) << Substitute(
"Container $0 with size $1 is now full, max size is $2",
ToString(), total_bytes_written_, FLAGS_log_container_max_size);
}
}
void LogBlockContainer::ExecClosure(const Closure& task) {
data_dir_->ExecClosure(task);
}
string LogBlockContainer::ToString() const {
string s;
CHECK(TryStripSuffixString(data_file_->filename(),
LogBlockManager::kContainerDataFileSuffix, &s));
return s;
}
////////////////////////////////////////////////////////////
// LogBlock
////////////////////////////////////////////////////////////
// The persistent metadata that describes a logical block.
//
// A block grows a LogBlock when its data has been synchronized with
// the disk. That's when it's fully immutable (i.e. none of its metadata
// can change), and when it becomes readable and persistent.
//
// LogBlocks are reference counted to simplify support for deletion with
// outstanding readers. All refcount increments are performed with the
// block manager lock held, as are deletion-based decrements. However,
// no lock is held when ~LogReadableBlock decrements the refcount, thus it
// must be made thread safe (by extending RefCountedThreadSafe instead of
// the simpler RefCounted).
class LogBlock : public RefCountedThreadSafe<LogBlock> {
public:
LogBlock(LogBlockContainer* container, BlockId block_id, int64_t offset,
int64_t length);
~LogBlock();
const BlockId& block_id() const { return block_id_; }
LogBlockContainer* container() const { return container_; }
int64_t offset() const { return offset_; }
int64_t length() const { return length_; }
// Delete the block. Actual deletion takes place when the
// block is destructed.
void Delete();
private:
// The owning container. Must outlive the LogBlock.
LogBlockContainer* container_;
// The block identifier.
const BlockId block_id_;
// The block's offset in the container.
const int64_t offset_;
// The block's length.
const int64_t length_;
// Whether the block has been marked for deletion.
bool deleted_;
DISALLOW_COPY_AND_ASSIGN(LogBlock);
};
LogBlock::LogBlock(LogBlockContainer* container, BlockId block_id,
int64_t offset, int64_t length)
: container_(container),
block_id_(block_id),
offset_(offset),
length_(length),
deleted_(false) {
DCHECK_GE(offset, 0);
DCHECK_GE(length, 0);
}
static void DeleteBlockAsync(LogBlockContainer* container,
BlockId block_id,
int64_t offset,
int64_t length) {
// We don't call SyncData() to synchronize the deletion because it's
// expensive, and in the worst case, we'll just leave orphaned data
// behind to be cleaned up in the next GC.
VLOG(3) << "Freeing space belonging to block " << block_id;
WARN_NOT_OK(container->DeleteBlock(offset, length),
Substitute("Could not delete block $0", block_id.ToString()));
}
LogBlock::~LogBlock() {
if (deleted_) {
container_->ExecClosure(Bind(&DeleteBlockAsync, container_, block_id_,
offset_, length_));
}
}
void LogBlock::Delete() {
DCHECK(!deleted_);
deleted_ = true;
}
////////////////////////////////////////////////////////////
// LogWritableBlock
////////////////////////////////////////////////////////////
// A log-backed block that has been opened for writing.
//
// There's no reference to a LogBlock as this block has yet to be
// persisted.
class LogWritableBlock : public WritableBlock {
public:
enum SyncMode {
SYNC,
NO_SYNC
};
LogWritableBlock(LogBlockContainer* container, BlockId block_id,
int64_t block_offset);
virtual ~LogWritableBlock();
virtual Status Close() OVERRIDE;
virtual Status Abort() OVERRIDE;
virtual const BlockId& id() const OVERRIDE;
virtual BlockManager* block_manager() const OVERRIDE;
virtual Status Append(const Slice& data) OVERRIDE;
virtual Status FlushDataAsync() OVERRIDE;
virtual size_t BytesAppended() const OVERRIDE;
virtual State state() const OVERRIDE;
// Actually close the block, possibly synchronizing its dirty data and
// metadata to disk.
Status DoClose(SyncMode mode);
// Write this block's metadata to disk.
//
// Does not synchronize the written data; that takes place in Close().
Status AppendMetadata();
private:
// The owning container. Must outlive the block.
LogBlockContainer* container_;
// The block's identifier.
const BlockId block_id_;
// The block's offset within the container. Known from the moment the
// block is created.
const int64_t block_offset_;
// The block's length. Changes with each Append().
int64_t block_length_;
// The state of the block describing where it is in the write lifecycle,
// for example, has it been synchronized to disk?
WritableBlock::State state_;
DISALLOW_COPY_AND_ASSIGN(LogWritableBlock);
};
LogWritableBlock::LogWritableBlock(LogBlockContainer* container,
BlockId block_id, int64_t block_offset)
: container_(container),
block_id_(block_id),
block_offset_(block_offset),
block_length_(0),
state_(CLEAN) {
DCHECK_GE(block_offset, 0);
DCHECK_EQ(0, block_offset % container->instance()->filesystem_block_size_bytes());
if (container->metrics()) {
container->metrics()->generic_metrics.blocks_open_writing->Increment();
container->metrics()->generic_metrics.total_writable_blocks->Increment();
}
}
LogWritableBlock::~LogWritableBlock() {
if (state_ != CLOSED) {
WARN_NOT_OK(Abort(), Substitute("Failed to abort block $0",
id().ToString()));
}
}
Status LogWritableBlock::Close() {
return DoClose(SYNC);
}
Status LogWritableBlock::Abort() {
RETURN_NOT_OK(DoClose(NO_SYNC));
// DoClose() has unlocked the container; it may be locked by someone else.
// But block_manager_ is immutable, so this is safe.
return container_->block_manager()->DeleteBlock(id());
}
const BlockId& LogWritableBlock::id() const {
return block_id_;
}
BlockManager* LogWritableBlock::block_manager() const {
return container_->block_manager();
}
Status LogWritableBlock::Append(const Slice& data) {
DCHECK(state_ == CLEAN || state_ == DIRTY)
<< "Invalid state: " << state_;
// The metadata change is deferred to Close() or FlushDataAsync(),
// whichever comes first. We can't do it now because the block's
// length is still in flux.
MicrosecondsInt64 start_time = GetMonoTimeMicros();
RETURN_NOT_OK(container_->AppendData(data));
MicrosecondsInt64 end_time = GetMonoTimeMicros();
int64_t dur = end_time - start_time;
TRACE_COUNTER_INCREMENT("lbm_write_time_us", dur);
const char* counter = BUCKETED_COUNTER_NAME("lbm_writes", dur);
TRACE_COUNTER_INCREMENT(counter, 1);
block_length_ += data.size();
state_ = DIRTY;
return Status::OK();
}
Status LogWritableBlock::FlushDataAsync() {
DCHECK(state_ == CLEAN || state_ == DIRTY || state_ == FLUSHING)
<< "Invalid state: " << state_;
if (state_ == DIRTY) {
VLOG(3) << "Flushing block " << id();
RETURN_NOT_OK(container_->FlushData(block_offset_, block_length_));
RETURN_NOT_OK_PREPEND(AppendMetadata(), "Unable to append block metadata");
// TODO(unknown): Flush just the range we care about.
RETURN_NOT_OK(container_->FlushMetadata());
}
state_ = FLUSHING;
return Status::OK();
}
size_t LogWritableBlock::BytesAppended() const {
return block_length_;
}
WritableBlock::State LogWritableBlock::state() const {
return state_;
}
Status LogWritableBlock::DoClose(SyncMode mode) {
if (state_ == CLOSED) {
return Status::OK();
}
// Tracks the first failure (if any).
//
// It's important that any subsequent failures mutate 's' before
// returning. Otherwise 'cleanup' won't properly provide the first
// failure to LogBlockContainer::FinishBlock().
//
// Note also that when 'cleanup' goes out of scope it may mutate 's'.
Status s;
{
auto cleanup = MakeScopedCleanup([&]() {
if (container_->metrics()) {
container_->metrics()->generic_metrics.blocks_open_writing->Decrement();
container_->metrics()->generic_metrics.total_bytes_written->IncrementBy(
BytesAppended());
}
state_ = CLOSED;
s = container_->FinishBlock(s, this);
});
// FlushDataAsync() was not called; append the metadata now.
if (state_ == CLEAN || state_ == DIRTY) {
s = AppendMetadata();
RETURN_NOT_OK_PREPEND(s, "Unable to flush block during close");
}
if (mode == SYNC &&
(state_ == CLEAN || state_ == DIRTY || state_ == FLUSHING)) {
VLOG(3) << "Syncing block " << id();
// TODO(unknown): Sync just this block's dirty data.
s = container_->SyncData();
RETURN_NOT_OK(s);
// TODO(unknown): Sync just this block's dirty metadata.
s = container_->SyncMetadata();
RETURN_NOT_OK(s);
}
}
return s;
}
Status LogWritableBlock::AppendMetadata() {
BlockRecordPB record;
id().CopyToPB(record.mutable_block_id());
record.set_op_type(CREATE);
record.set_timestamp_us(GetCurrentTimeMicros());
record.set_offset(block_offset_);
record.set_length(block_length_);
return container_->AppendMetadata(record);
}
////////////////////////////////////////////////////////////
// LogReadableBlock
////////////////////////////////////////////////////////////
// A log-backed block that has been opened for reading.
//
// Refers to a LogBlock representing the block's persisted metadata.
class LogReadableBlock : public ReadableBlock {
public:
LogReadableBlock(LogBlockContainer* container,
const scoped_refptr<LogBlock>& log_block);
virtual ~LogReadableBlock();
virtual Status Close() OVERRIDE;
virtual const BlockId& id() const OVERRIDE;
virtual Status Size(uint64_t* sz) const OVERRIDE;
virtual Status Read(uint64_t offset, size_t length,
Slice* result, uint8_t* scratch) const OVERRIDE;
virtual size_t memory_footprint() const OVERRIDE;
private:
// The owning container. Must outlive this block.
LogBlockContainer* container_;
// A reference to this block's metadata.
scoped_refptr<internal::LogBlock> log_block_;
// Whether or not this block has been closed. Close() is thread-safe, so
// this must be an atomic primitive.
AtomicBool closed_;
DISALLOW_COPY_AND_ASSIGN(LogReadableBlock);
};
LogReadableBlock::LogReadableBlock(LogBlockContainer* container,
const scoped_refptr<LogBlock>& log_block)
: container_(container),
log_block_(log_block),
closed_(false) {
if (container_->metrics()) {
container_->metrics()->generic_metrics.blocks_open_reading->Increment();
container_->metrics()->generic_metrics.total_readable_blocks->Increment();
}
}
LogReadableBlock::~LogReadableBlock() {
WARN_NOT_OK(Close(), Substitute("Failed to close block $0",
id().ToString()));
}
Status LogReadableBlock::Close() {
if (closed_.CompareAndSet(false, true)) {
log_block_.reset();
if (container_->metrics()) {
container_->metrics()->generic_metrics.blocks_open_reading->Decrement();
}
}
return Status::OK();
}
const BlockId& LogReadableBlock::id() const {
return log_block_->block_id();
}
Status LogReadableBlock::Size(uint64_t* sz) const {
DCHECK(!closed_.Load());
*sz = log_block_->length();
return Status::OK();
}
Status LogReadableBlock::Read(uint64_t offset, size_t length,
Slice* result, uint8_t* scratch) const {
DCHECK(!closed_.Load());
uint64_t read_offset = log_block_->offset() + offset;
if (log_block_->length() < offset + length) {
return Status::IOError("Out-of-bounds read",
Substitute("read of [$0-$1) in block [$2-$3)",
read_offset,
read_offset + length,
log_block_->offset(),
log_block_->offset() + log_block_->length()));
}
MicrosecondsInt64 start_time = GetMonoTimeMicros();
RETURN_NOT_OK(container_->ReadData(read_offset, length, result, scratch));
MicrosecondsInt64 end_time = GetMonoTimeMicros();
int64_t dur = end_time - start_time;
TRACE_COUNTER_INCREMENT("lbm_read_time_us", dur);
const char* counter = BUCKETED_COUNTER_NAME("lbm_reads", dur);
TRACE_COUNTER_INCREMENT(counter, 1);
if (container_->metrics()) {
container_->metrics()->generic_metrics.total_bytes_read->IncrementBy(length);
}
return Status::OK();
}
size_t LogReadableBlock::memory_footprint() const {
return kudu_malloc_usable_size(this);
}
} // namespace internal
////////////////////////////////////////////////////////////
// LogBlockManager
////////////////////////////////////////////////////////////
const char* LogBlockManager::kContainerMetadataFileSuffix = ".metadata";
const char* LogBlockManager::kContainerDataFileSuffix = ".data";
static const char* kBlockManagerType = "log";
LogBlockManager::LogBlockManager(Env* env, const BlockManagerOptions& opts)
: mem_tracker_(MemTracker::CreateTracker(-1,
"log_block_manager",
opts.parent_mem_tracker)),
dd_manager_(env, opts.metric_entity, kBlockManagerType, opts.root_paths),
blocks_by_block_id_(10,
BlockMap::hasher(),
BlockMap::key_equal(),
BlockAllocator(mem_tracker_)),
env_(DCHECK_NOTNULL(env)),
read_only_(opts.read_only),
next_block_id_(1) {
// HACK: when running in a test environment, we often instantiate many
// LogBlockManagers in the same process, eg corresponding to different
// tablet servers in a minicluster, or due to running many separate test
// cases of some CFile-related code. In that case, we need to make it more
// likely that the block IDs are not reused. So, instead of starting with
// block ID 1, we'll start with a random block ID. A collision is still
// possible, but exceedingly unlikely.
if (IsGTest()) {
Random r(GetRandomSeed32());
next_block_id_.Store(r.Next64());
}
if (opts.metric_entity) {
metrics_.reset(new internal::LogBlockManagerMetrics(opts.metric_entity));
}
}
LogBlockManager::~LogBlockManager() {
// Release all of the memory accounted by the blocks.
int64_t mem = 0;
for (const auto& entry : blocks_by_block_id_) {
mem += kudu_malloc_usable_size(entry.second.get());
}
mem_tracker_->Release(mem);
// A LogBlock's destructor depends on its container, so all LogBlocks must be
// destroyed before their containers.
blocks_by_block_id_.clear();
// Containers may have outstanding tasks running on data directories; shut
// them down before destroying the containers.
dd_manager_.Shutdown();
STLDeleteElements(&all_containers_);
}
Status LogBlockManager::Create() {
CHECK(!read_only_);
return dd_manager_.Create(FLAGS_enable_data_block_fsync ?
DataDirManager::FLAG_CREATE_TEST_HOLE_PUNCH | DataDirManager::FLAG_CREATE_FSYNC :
DataDirManager::FLAG_CREATE_TEST_HOLE_PUNCH);
}
Status LogBlockManager::Open() {
DataDirManager::LockMode mode;
if (!FLAGS_block_manager_lock_dirs) {
mode = DataDirManager::LockMode::NONE;
} else if (read_only_) {
mode = DataDirManager::LockMode::OPTIONAL;
} else {
mode = DataDirManager::LockMode::MANDATORY;
}
RETURN_NOT_OK(dd_manager_.Open(kuint32max, mode));
vector<Status> statuses(dd_manager_.data_dirs().size());
int i = 0;
for (const auto& dd : dd_manager_.data_dirs()) {
// Open the data dir asynchronously.
dd->ExecClosure(
Bind(&LogBlockManager::OpenDataDir,
Unretained(this),
dd.get(),
&statuses[i]));
i++;
}
// Wait for the opens to complete.
for (const auto& dd : dd_manager_.data_dirs()) {
dd->WaitOnClosures();
}
// Ensure that no open failed.
for (const auto& s : statuses) {
if (!s.ok()) {
return s;
}
}
return Status::OK();
}
Status LogBlockManager::CreateBlock(const CreateBlockOptions& opts,
gscoped_ptr<WritableBlock>* block) {
CHECK(!read_only_);
// Find a free container. If one cannot be found, create a new one.
//
// TODO(unknown): should we cap the number of outstanding containers and
// force callers to block if we've reached it?
LogBlockContainer* container;
RETURN_NOT_OK(GetOrCreateContainer(&container));
// Generate a free block ID.
// We have to loop here because earlier versions used non-sequential block IDs,
// and thus we may have to "skip over" some block IDs that are claimed.
BlockId new_block_id;
do {
new_block_id.SetId(next_block_id_.Increment());
} while (!TryUseBlockId(new_block_id));
block->reset(new internal::LogWritableBlock(container,
new_block_id,
container->total_bytes_written()));
VLOG(3) << "Created block " << (*block)->id() << " in container "
<< container->ToString();
return Status::OK();
}
Status LogBlockManager::CreateBlock(gscoped_ptr<WritableBlock>* block) {
return CreateBlock(CreateBlockOptions(), block);
}
Status LogBlockManager::OpenBlock(const BlockId& block_id,
gscoped_ptr<ReadableBlock>* block) {
scoped_refptr<LogBlock> lb;
{
std::lock_guard<simple_spinlock> l(lock_);
lb = FindPtrOrNull(blocks_by_block_id_, block_id);
}
if (!lb) {
return Status::NotFound("Can't find block", block_id.ToString());
}
block->reset(new internal::LogReadableBlock(lb->container(),
lb.get()));
VLOG(3) << "Opened block " << (*block)->id()
<< " from container " << lb->container()->ToString();
return Status::OK();
}
Status LogBlockManager::DeleteBlock(const BlockId& block_id) {
CHECK(!read_only_);
scoped_refptr<LogBlock> lb(RemoveLogBlock(block_id));
if (!lb) {
return Status::NotFound("Can't find block", block_id.ToString());
}
VLOG(3) << "Deleting block " << block_id;
lb->Delete();
// Record the on-disk deletion.
//
// TODO(unknown): what if this fails? Should we restore the in-memory block?
BlockRecordPB record;
block_id.CopyToPB(record.mutable_block_id());
record.set_op_type(DELETE);
record.set_timestamp_us(GetCurrentTimeMicros());
RETURN_NOT_OK_PREPEND(lb->container()->AppendMetadata(record),
"Unable to append deletion record to block metadata");
// We don't bother fsyncing the metadata append for deletes in order to avoid
// the disk overhead. Even if we did fsync it, we'd still need to account for
// garbage at startup time (in the event that we crashed just before the
// fsync).
//
// TODO(KUDU-829): Implement GC of orphaned blocks.
return Status::OK();
}
Status LogBlockManager::CloseBlocks(const std::vector<WritableBlock*>& blocks) {
VLOG(3) << "Closing " << blocks.size() << " blocks";
if (FLAGS_block_coalesce_close) {
// Ask the kernel to begin writing out each block's dirty data. This is
// done up-front to give the kernel opportunities to coalesce contiguous
// dirty pages.
for (WritableBlock* block : blocks) {
RETURN_NOT_OK(block->FlushDataAsync());
}
}
// Now close each block, waiting for each to become durable.
for (WritableBlock* block : blocks) {
RETURN_NOT_OK(block->Close());
}
return Status::OK();
}
int64_t LogBlockManager::CountBlocksForTests() const {
std::lock_guard<simple_spinlock> l(lock_);
return blocks_by_block_id_.size();
}
void LogBlockManager::AddNewContainerUnlocked(LogBlockContainer* container) {
DCHECK(lock_.is_locked());
all_containers_.push_back(container);
if (metrics()) {
metrics()->containers->Increment();
if (container->full()) {
metrics()->full_containers->Increment();
}
}
}
Status LogBlockManager::GetOrCreateContainer(LogBlockContainer** container) {
DataDir* dir;
RETURN_NOT_OK(dd_manager_.GetNextDataDir(&dir));
{
std::lock_guard<simple_spinlock> l(lock_);
auto& d = available_containers_by_data_dir_[DCHECK_NOTNULL(dir)];
if (!d.empty()) {
*container = d.front();
d.pop_front();
return Status::OK();
}
}
// All containers are in use; create a new one.
gscoped_ptr<LogBlockContainer> new_container;
RETURN_NOT_OK_PREPEND(LogBlockContainer::Create(this,
dir,
&new_container),
"Could not create new log block container at " + dir->dir());
{
std::lock_guard<simple_spinlock> l(lock_);
dirty_dirs_.insert(dir->dir());
AddNewContainerUnlocked(new_container.get());
}
*container = new_container.release();
return Status::OK();
}
void LogBlockManager::MakeContainerAvailable(LogBlockContainer* container) {
std::lock_guard<simple_spinlock> l(lock_);
MakeContainerAvailableUnlocked(container);
}
void LogBlockManager::MakeContainerAvailableUnlocked(LogBlockContainer* container) {
DCHECK(lock_.is_locked());
if (container->full()) {
return;
}
available_containers_by_data_dir_[container->data_dir()].push_back(container);
}
Status LogBlockManager::SyncContainer(const LogBlockContainer& container) {
Status s;
bool to_sync = false;
{
std::lock_guard<simple_spinlock> l(lock_);
to_sync = dirty_dirs_.erase(container.data_dir()->dir());
}
if (to_sync && FLAGS_enable_data_block_fsync) {
s = env_->SyncDir(container.data_dir()->dir());
// If SyncDir fails, the container directory must be restored to
// dirty_dirs_. Otherwise a future successful LogWritableBlock::Close()
// on this container won't call SyncDir again, and the container might
// be lost on crash.
//
// In the worst case (another block synced this container as we did),
// we'll sync it again needlessly.
if (!s.ok()) {
std::lock_guard<simple_spinlock> l(lock_);
dirty_dirs_.insert(container.data_dir()->dir());
}
}
return s;
}
bool LogBlockManager::TryUseBlockId(const BlockId& block_id) {
if (block_id.IsNull()) {
return false;
}
std::lock_guard<simple_spinlock> l(lock_);
if (ContainsKey(blocks_by_block_id_, block_id)) {
return false;
}
return InsertIfNotPresent(&open_block_ids_, block_id);
}
bool LogBlockManager::AddLogBlock(LogBlockContainer* container,
const BlockId& block_id,
int64_t offset,
int64_t length) {
std::lock_guard<simple_spinlock> l(lock_);
scoped_refptr<LogBlock> lb(new LogBlock(container, block_id, offset, length));
mem_tracker_->Consume(kudu_malloc_usable_size(lb.get()));
return AddLogBlockUnlocked(lb);
}
bool LogBlockManager::AddLogBlockUnlocked(const scoped_refptr<LogBlock>& lb) {
DCHECK(lock_.is_locked());
if (!InsertIfNotPresent(&blocks_by_block_id_, lb->block_id(), lb)) {
return false;
}
VLOG(2) << Substitute("Added block: offset $0, length $1",
lb->offset(), lb->length());
// There may already be an entry in open_block_ids_ (e.g. we just finished
// writing out a block).
open_block_ids_.erase(lb->block_id());
if (metrics()) {
metrics()->blocks_under_management->Increment();
metrics()->bytes_under_management->IncrementBy(lb->length());
}
return true;
}
scoped_refptr<LogBlock> LogBlockManager::RemoveLogBlock(const BlockId& block_id) {
std::lock_guard<simple_spinlock> l(lock_);
scoped_refptr<LogBlock> result =
EraseKeyReturnValuePtr(&blocks_by_block_id_, block_id);
if (result) {
VLOG(2) << Substitute("Removed block: offset $0, length $1",
result->offset(), result->length());
mem_tracker_->Release(kudu_malloc_usable_size(result.get()));
if (metrics()) {
metrics()->blocks_under_management->Decrement();
metrics()->bytes_under_management->DecrementBy(result->length());
}
}
return result;
}
void LogBlockManager::OpenDataDir(DataDir* dir,
Status* result_status) {
// Find all containers and open them.
vector<string> children;
Status s = env_->GetChildren(dir->dir(), &children);
if (!s.ok()) {
*result_status = s.CloneAndPrepend(Substitute(
"Could not list children of $0", dir->dir()));
return;
}
for (const string& child : children) {
string id;
if (!TryStripSuffixString(child, LogBlockManager::kContainerMetadataFileSuffix, &id)) {
continue;
}
gscoped_ptr<LogBlockContainer> container;
s = LogBlockContainer::Open(this, dir, id, &container);
if (s.IsAborted()) {
// Skip the container. Open() already handled logging for us.
continue;
}
if (!s.ok()) {
*result_status = s.CloneAndPrepend(Substitute(
"Could not open container $0", id));
return;
}
// Populate the in-memory block maps using each container's records.
deque<BlockRecordPB> records;
s = container->ReadContainerRecords(&records);
if (!s.ok()) {
*result_status = s.CloneAndPrepend(Substitute(
"Could not read records from container $0", container->ToString()));
return;
}
// Process the records, building a container-local map.
//
// It's important that we don't try to add these blocks to the global map
// incrementally as we see each record, since it's possible that one container
// has a "CREATE <b>" while another has a "CREATE <b> ; DELETE <b>" pair.
// If we processed those two containers in this order, then upon processing
// the second container, we'd think there was a duplicate block. Building
// the container-local map first ensures that we discount deleted blocks
// before checking for duplicate IDs.
//
// NOTE: Since KUDU-1538, we allocate sequential block IDs, which makes reuse
// exceedingly unlikely. However, we might have old data which still exhibits
// the above issue.
UntrackedBlockMap blocks_in_container;
uint64_t max_block_id = 0;
for (const BlockRecordPB& r : records) {
ProcessBlockRecord(r, container.get(), &blocks_in_container);
max_block_id = std::max(max_block_id, r.block_id().id());
}
next_block_id_.StoreMax(max_block_id + 1);
// Under the lock, merge this map into the main block map and add
// the container.
{
std::lock_guard<simple_spinlock> l(lock_);
// To avoid cacheline contention during startup, we aggregate all of the
// memory in a local and add it to the mem-tracker in a single increment
// at the end of this loop.
int64_t mem_usage = 0;
for (const UntrackedBlockMap::value_type& e : blocks_in_container) {
if (!AddLogBlockUnlocked(e.second)) {
LOG(FATAL) << "Found duplicate CREATE record for block " << e.first
<< " which already is alive from another container when "
<< " processing container " << container->ToString();
}
mem_usage += kudu_malloc_usable_size(e.second.get());
}
mem_tracker_->Consume(mem_usage);
AddNewContainerUnlocked(container.get());
MakeContainerAvailableUnlocked(container.release());
}
}
*result_status = Status::OK();
}
void LogBlockManager::ProcessBlockRecord(const BlockRecordPB& record,
LogBlockContainer* container,
UntrackedBlockMap* block_map) {
BlockId block_id(BlockId::FromPB(record.block_id()));
switch (record.op_type()) {
case CREATE: {
scoped_refptr<LogBlock> lb(new LogBlock(container, block_id,
record.offset(), record.length()));
if (!InsertIfNotPresent(block_map, block_id, lb)) {
LOG(FATAL) << "Found duplicate CREATE record for block "
<< block_id.ToString() << " in container "
<< container->ToString() << ": "
<< record.DebugString();
}
VLOG(2) << Substitute("Found CREATE block $0 at offset $1 with length $2",
block_id.ToString(),
record.offset(), record.length());
// This block must be included in the container's logical size, even if
// it has since been deleted. This helps satisfy one of our invariants:
// once a container byte range has been used, it may never be reused in
// the future.
//
// If we ignored deleted blocks, we would end up reusing the space
// belonging to the last deleted block in the container.
container->UpdateBytesWritten(record.length());
break;
}
case DELETE:
if (block_map->erase(block_id) != 1) {
LOG(FATAL) << "Found DELETE record for invalid block "
<< block_id.ToString() << " in container "
<< container->ToString() << ": "
<< record.DebugString();
}
VLOG(2) << Substitute("Found DELETE block $0", block_id.ToString());
break;
default:
LOG(FATAL) << "Found unknown op type in block record: "
<< record.DebugString();
}
}
std::string LogBlockManager::ContainerPathForTests(internal::LogBlockContainer* container) {
return container->ToString();
}
} // namespace fs
} // namespace kudu
| 35.813968 | 100 | 0.668109 | [
"vector"
] |
9161f5e8f5397ff2b13b55b708f5a66c85042887 | 139,890 | cc | C++ | components/service/ucloud/cloudapi/src/CloudAPIClient.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | components/service/ucloud/cloudapi/src/CloudAPIClient.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | components/service/ucloud/cloudapi/src/CloudAPIClient.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/cloudapi/CloudAPIClient.h>
#include <alibabacloud/core/SimpleCredentialsProvider.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Location;
using namespace AlibabaCloud::CloudAPI;
using namespace AlibabaCloud::CloudAPI::Model;
namespace
{
const std::string SERVICE_NAME = "CloudAPI";
}
CloudAPIClient::CloudAPIClient(const Credentials &credentials, const ClientConfiguration &configuration) :
RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(credentials), configuration)
{
auto locationClient = std::make_shared<LocationClient>(credentials, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "cloudapi");
}
CloudAPIClient::CloudAPIClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) :
RpcServiceClient(SERVICE_NAME, credentialsProvider, configuration)
{
auto locationClient = std::make_shared<LocationClient>(credentialsProvider, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "cloudapi");
}
CloudAPIClient::CloudAPIClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) :
RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret), configuration)
{
auto locationClient = std::make_shared<LocationClient>(accessKeyId, accessKeySecret, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "cloudapi");
}
CloudAPIClient::~CloudAPIClient()
{}
CloudAPIClient::AbolishApiOutcome CloudAPIClient::abolishApi(const AbolishApiRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return AbolishApiOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return AbolishApiOutcome(AbolishApiResult(outcome.result()));
else
return AbolishApiOutcome(outcome.error());
}
void CloudAPIClient::abolishApiAsync(const AbolishApiRequest& request, const AbolishApiAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, abolishApi(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::AbolishApiOutcomeCallable CloudAPIClient::abolishApiCallable(const AbolishApiRequest &request) const
{
auto task = std::make_shared<std::packaged_task<AbolishApiOutcome()>>(
[this, request]()
{
return this->abolishApi(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::AddIpControlPolicyItemOutcome CloudAPIClient::addIpControlPolicyItem(const AddIpControlPolicyItemRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return AddIpControlPolicyItemOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return AddIpControlPolicyItemOutcome(AddIpControlPolicyItemResult(outcome.result()));
else
return AddIpControlPolicyItemOutcome(outcome.error());
}
void CloudAPIClient::addIpControlPolicyItemAsync(const AddIpControlPolicyItemRequest& request, const AddIpControlPolicyItemAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, addIpControlPolicyItem(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::AddIpControlPolicyItemOutcomeCallable CloudAPIClient::addIpControlPolicyItemCallable(const AddIpControlPolicyItemRequest &request) const
{
auto task = std::make_shared<std::packaged_task<AddIpControlPolicyItemOutcome()>>(
[this, request]()
{
return this->addIpControlPolicyItem(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::AddTrafficSpecialControlOutcome CloudAPIClient::addTrafficSpecialControl(const AddTrafficSpecialControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return AddTrafficSpecialControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return AddTrafficSpecialControlOutcome(AddTrafficSpecialControlResult(outcome.result()));
else
return AddTrafficSpecialControlOutcome(outcome.error());
}
void CloudAPIClient::addTrafficSpecialControlAsync(const AddTrafficSpecialControlRequest& request, const AddTrafficSpecialControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, addTrafficSpecialControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::AddTrafficSpecialControlOutcomeCallable CloudAPIClient::addTrafficSpecialControlCallable(const AddTrafficSpecialControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<AddTrafficSpecialControlOutcome()>>(
[this, request]()
{
return this->addTrafficSpecialControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::CreateApiOutcome CloudAPIClient::createApi(const CreateApiRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateApiOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateApiOutcome(CreateApiResult(outcome.result()));
else
return CreateApiOutcome(outcome.error());
}
void CloudAPIClient::createApiAsync(const CreateApiRequest& request, const CreateApiAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createApi(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::CreateApiOutcomeCallable CloudAPIClient::createApiCallable(const CreateApiRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateApiOutcome()>>(
[this, request]()
{
return this->createApi(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::CreateApiGroupOutcome CloudAPIClient::createApiGroup(const CreateApiGroupRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateApiGroupOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateApiGroupOutcome(CreateApiGroupResult(outcome.result()));
else
return CreateApiGroupOutcome(outcome.error());
}
void CloudAPIClient::createApiGroupAsync(const CreateApiGroupRequest& request, const CreateApiGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createApiGroup(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::CreateApiGroupOutcomeCallable CloudAPIClient::createApiGroupCallable(const CreateApiGroupRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateApiGroupOutcome()>>(
[this, request]()
{
return this->createApiGroup(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::CreateApiStageVariableOutcome CloudAPIClient::createApiStageVariable(const CreateApiStageVariableRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateApiStageVariableOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateApiStageVariableOutcome(CreateApiStageVariableResult(outcome.result()));
else
return CreateApiStageVariableOutcome(outcome.error());
}
void CloudAPIClient::createApiStageVariableAsync(const CreateApiStageVariableRequest& request, const CreateApiStageVariableAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createApiStageVariable(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::CreateApiStageVariableOutcomeCallable CloudAPIClient::createApiStageVariableCallable(const CreateApiStageVariableRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateApiStageVariableOutcome()>>(
[this, request]()
{
return this->createApiStageVariable(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::CreateAppOutcome CloudAPIClient::createApp(const CreateAppRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateAppOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateAppOutcome(CreateAppResult(outcome.result()));
else
return CreateAppOutcome(outcome.error());
}
void CloudAPIClient::createAppAsync(const CreateAppRequest& request, const CreateAppAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createApp(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::CreateAppOutcomeCallable CloudAPIClient::createAppCallable(const CreateAppRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateAppOutcome()>>(
[this, request]()
{
return this->createApp(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::CreateInstanceOutcome CloudAPIClient::createInstance(const CreateInstanceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateInstanceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateInstanceOutcome(CreateInstanceResult(outcome.result()));
else
return CreateInstanceOutcome(outcome.error());
}
void CloudAPIClient::createInstanceAsync(const CreateInstanceRequest& request, const CreateInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createInstance(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::CreateInstanceOutcomeCallable CloudAPIClient::createInstanceCallable(const CreateInstanceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateInstanceOutcome()>>(
[this, request]()
{
return this->createInstance(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::CreateIntranetDomainOutcome CloudAPIClient::createIntranetDomain(const CreateIntranetDomainRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateIntranetDomainOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateIntranetDomainOutcome(CreateIntranetDomainResult(outcome.result()));
else
return CreateIntranetDomainOutcome(outcome.error());
}
void CloudAPIClient::createIntranetDomainAsync(const CreateIntranetDomainRequest& request, const CreateIntranetDomainAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createIntranetDomain(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::CreateIntranetDomainOutcomeCallable CloudAPIClient::createIntranetDomainCallable(const CreateIntranetDomainRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateIntranetDomainOutcome()>>(
[this, request]()
{
return this->createIntranetDomain(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::CreateIpControlOutcome CloudAPIClient::createIpControl(const CreateIpControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateIpControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateIpControlOutcome(CreateIpControlResult(outcome.result()));
else
return CreateIpControlOutcome(outcome.error());
}
void CloudAPIClient::createIpControlAsync(const CreateIpControlRequest& request, const CreateIpControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createIpControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::CreateIpControlOutcomeCallable CloudAPIClient::createIpControlCallable(const CreateIpControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateIpControlOutcome()>>(
[this, request]()
{
return this->createIpControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::CreateLogConfigOutcome CloudAPIClient::createLogConfig(const CreateLogConfigRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateLogConfigOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateLogConfigOutcome(CreateLogConfigResult(outcome.result()));
else
return CreateLogConfigOutcome(outcome.error());
}
void CloudAPIClient::createLogConfigAsync(const CreateLogConfigRequest& request, const CreateLogConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createLogConfig(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::CreateLogConfigOutcomeCallable CloudAPIClient::createLogConfigCallable(const CreateLogConfigRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateLogConfigOutcome()>>(
[this, request]()
{
return this->createLogConfig(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::CreateSignatureOutcome CloudAPIClient::createSignature(const CreateSignatureRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateSignatureOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateSignatureOutcome(CreateSignatureResult(outcome.result()));
else
return CreateSignatureOutcome(outcome.error());
}
void CloudAPIClient::createSignatureAsync(const CreateSignatureRequest& request, const CreateSignatureAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createSignature(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::CreateSignatureOutcomeCallable CloudAPIClient::createSignatureCallable(const CreateSignatureRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateSignatureOutcome()>>(
[this, request]()
{
return this->createSignature(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::CreateTrafficControlOutcome CloudAPIClient::createTrafficControl(const CreateTrafficControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateTrafficControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateTrafficControlOutcome(CreateTrafficControlResult(outcome.result()));
else
return CreateTrafficControlOutcome(outcome.error());
}
void CloudAPIClient::createTrafficControlAsync(const CreateTrafficControlRequest& request, const CreateTrafficControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createTrafficControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::CreateTrafficControlOutcomeCallable CloudAPIClient::createTrafficControlCallable(const CreateTrafficControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateTrafficControlOutcome()>>(
[this, request]()
{
return this->createTrafficControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteAllTrafficSpecialControlOutcome CloudAPIClient::deleteAllTrafficSpecialControl(const DeleteAllTrafficSpecialControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteAllTrafficSpecialControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteAllTrafficSpecialControlOutcome(DeleteAllTrafficSpecialControlResult(outcome.result()));
else
return DeleteAllTrafficSpecialControlOutcome(outcome.error());
}
void CloudAPIClient::deleteAllTrafficSpecialControlAsync(const DeleteAllTrafficSpecialControlRequest& request, const DeleteAllTrafficSpecialControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteAllTrafficSpecialControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteAllTrafficSpecialControlOutcomeCallable CloudAPIClient::deleteAllTrafficSpecialControlCallable(const DeleteAllTrafficSpecialControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteAllTrafficSpecialControlOutcome()>>(
[this, request]()
{
return this->deleteAllTrafficSpecialControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteApiOutcome CloudAPIClient::deleteApi(const DeleteApiRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteApiOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteApiOutcome(DeleteApiResult(outcome.result()));
else
return DeleteApiOutcome(outcome.error());
}
void CloudAPIClient::deleteApiAsync(const DeleteApiRequest& request, const DeleteApiAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteApi(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteApiOutcomeCallable CloudAPIClient::deleteApiCallable(const DeleteApiRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteApiOutcome()>>(
[this, request]()
{
return this->deleteApi(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteApiGroupOutcome CloudAPIClient::deleteApiGroup(const DeleteApiGroupRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteApiGroupOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteApiGroupOutcome(DeleteApiGroupResult(outcome.result()));
else
return DeleteApiGroupOutcome(outcome.error());
}
void CloudAPIClient::deleteApiGroupAsync(const DeleteApiGroupRequest& request, const DeleteApiGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteApiGroup(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteApiGroupOutcomeCallable CloudAPIClient::deleteApiGroupCallable(const DeleteApiGroupRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteApiGroupOutcome()>>(
[this, request]()
{
return this->deleteApiGroup(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteApiStageVariableOutcome CloudAPIClient::deleteApiStageVariable(const DeleteApiStageVariableRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteApiStageVariableOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteApiStageVariableOutcome(DeleteApiStageVariableResult(outcome.result()));
else
return DeleteApiStageVariableOutcome(outcome.error());
}
void CloudAPIClient::deleteApiStageVariableAsync(const DeleteApiStageVariableRequest& request, const DeleteApiStageVariableAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteApiStageVariable(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteApiStageVariableOutcomeCallable CloudAPIClient::deleteApiStageVariableCallable(const DeleteApiStageVariableRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteApiStageVariableOutcome()>>(
[this, request]()
{
return this->deleteApiStageVariable(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteAppOutcome CloudAPIClient::deleteApp(const DeleteAppRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteAppOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteAppOutcome(DeleteAppResult(outcome.result()));
else
return DeleteAppOutcome(outcome.error());
}
void CloudAPIClient::deleteAppAsync(const DeleteAppRequest& request, const DeleteAppAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteApp(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteAppOutcomeCallable CloudAPIClient::deleteAppCallable(const DeleteAppRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteAppOutcome()>>(
[this, request]()
{
return this->deleteApp(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteDomainOutcome CloudAPIClient::deleteDomain(const DeleteDomainRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteDomainOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteDomainOutcome(DeleteDomainResult(outcome.result()));
else
return DeleteDomainOutcome(outcome.error());
}
void CloudAPIClient::deleteDomainAsync(const DeleteDomainRequest& request, const DeleteDomainAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteDomain(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteDomainOutcomeCallable CloudAPIClient::deleteDomainCallable(const DeleteDomainRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteDomainOutcome()>>(
[this, request]()
{
return this->deleteDomain(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteDomainCertificateOutcome CloudAPIClient::deleteDomainCertificate(const DeleteDomainCertificateRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteDomainCertificateOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteDomainCertificateOutcome(DeleteDomainCertificateResult(outcome.result()));
else
return DeleteDomainCertificateOutcome(outcome.error());
}
void CloudAPIClient::deleteDomainCertificateAsync(const DeleteDomainCertificateRequest& request, const DeleteDomainCertificateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteDomainCertificate(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteDomainCertificateOutcomeCallable CloudAPIClient::deleteDomainCertificateCallable(const DeleteDomainCertificateRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteDomainCertificateOutcome()>>(
[this, request]()
{
return this->deleteDomainCertificate(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteInstanceOutcome CloudAPIClient::deleteInstance(const DeleteInstanceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteInstanceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteInstanceOutcome(DeleteInstanceResult(outcome.result()));
else
return DeleteInstanceOutcome(outcome.error());
}
void CloudAPIClient::deleteInstanceAsync(const DeleteInstanceRequest& request, const DeleteInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteInstance(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteInstanceOutcomeCallable CloudAPIClient::deleteInstanceCallable(const DeleteInstanceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteInstanceOutcome()>>(
[this, request]()
{
return this->deleteInstance(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteIpControlOutcome CloudAPIClient::deleteIpControl(const DeleteIpControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteIpControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteIpControlOutcome(DeleteIpControlResult(outcome.result()));
else
return DeleteIpControlOutcome(outcome.error());
}
void CloudAPIClient::deleteIpControlAsync(const DeleteIpControlRequest& request, const DeleteIpControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteIpControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteIpControlOutcomeCallable CloudAPIClient::deleteIpControlCallable(const DeleteIpControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteIpControlOutcome()>>(
[this, request]()
{
return this->deleteIpControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteLogConfigOutcome CloudAPIClient::deleteLogConfig(const DeleteLogConfigRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteLogConfigOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteLogConfigOutcome(DeleteLogConfigResult(outcome.result()));
else
return DeleteLogConfigOutcome(outcome.error());
}
void CloudAPIClient::deleteLogConfigAsync(const DeleteLogConfigRequest& request, const DeleteLogConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteLogConfig(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteLogConfigOutcomeCallable CloudAPIClient::deleteLogConfigCallable(const DeleteLogConfigRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteLogConfigOutcome()>>(
[this, request]()
{
return this->deleteLogConfig(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteSignatureOutcome CloudAPIClient::deleteSignature(const DeleteSignatureRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteSignatureOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteSignatureOutcome(DeleteSignatureResult(outcome.result()));
else
return DeleteSignatureOutcome(outcome.error());
}
void CloudAPIClient::deleteSignatureAsync(const DeleteSignatureRequest& request, const DeleteSignatureAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteSignature(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteSignatureOutcomeCallable CloudAPIClient::deleteSignatureCallable(const DeleteSignatureRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteSignatureOutcome()>>(
[this, request]()
{
return this->deleteSignature(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteTrafficControlOutcome CloudAPIClient::deleteTrafficControl(const DeleteTrafficControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteTrafficControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteTrafficControlOutcome(DeleteTrafficControlResult(outcome.result()));
else
return DeleteTrafficControlOutcome(outcome.error());
}
void CloudAPIClient::deleteTrafficControlAsync(const DeleteTrafficControlRequest& request, const DeleteTrafficControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteTrafficControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteTrafficControlOutcomeCallable CloudAPIClient::deleteTrafficControlCallable(const DeleteTrafficControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteTrafficControlOutcome()>>(
[this, request]()
{
return this->deleteTrafficControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeleteTrafficSpecialControlOutcome CloudAPIClient::deleteTrafficSpecialControl(const DeleteTrafficSpecialControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteTrafficSpecialControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteTrafficSpecialControlOutcome(DeleteTrafficSpecialControlResult(outcome.result()));
else
return DeleteTrafficSpecialControlOutcome(outcome.error());
}
void CloudAPIClient::deleteTrafficSpecialControlAsync(const DeleteTrafficSpecialControlRequest& request, const DeleteTrafficSpecialControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteTrafficSpecialControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeleteTrafficSpecialControlOutcomeCallable CloudAPIClient::deleteTrafficSpecialControlCallable(const DeleteTrafficSpecialControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteTrafficSpecialControlOutcome()>>(
[this, request]()
{
return this->deleteTrafficSpecialControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DeployApiOutcome CloudAPIClient::deployApi(const DeployApiRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeployApiOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeployApiOutcome(DeployApiResult(outcome.result()));
else
return DeployApiOutcome(outcome.error());
}
void CloudAPIClient::deployApiAsync(const DeployApiRequest& request, const DeployApiAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deployApi(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DeployApiOutcomeCallable CloudAPIClient::deployApiCallable(const DeployApiRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeployApiOutcome()>>(
[this, request]()
{
return this->deployApi(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiOutcome CloudAPIClient::describeApi(const DescribeApiRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiOutcome(DescribeApiResult(outcome.result()));
else
return DescribeApiOutcome(outcome.error());
}
void CloudAPIClient::describeApiAsync(const DescribeApiRequest& request, const DescribeApiAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApi(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiOutcomeCallable CloudAPIClient::describeApiCallable(const DescribeApiRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiOutcome()>>(
[this, request]()
{
return this->describeApi(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiDocOutcome CloudAPIClient::describeApiDoc(const DescribeApiDocRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiDocOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiDocOutcome(DescribeApiDocResult(outcome.result()));
else
return DescribeApiDocOutcome(outcome.error());
}
void CloudAPIClient::describeApiDocAsync(const DescribeApiDocRequest& request, const DescribeApiDocAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiDoc(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiDocOutcomeCallable CloudAPIClient::describeApiDocCallable(const DescribeApiDocRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiDocOutcome()>>(
[this, request]()
{
return this->describeApiDoc(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiErrorDataOutcome CloudAPIClient::describeApiErrorData(const DescribeApiErrorDataRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiErrorDataOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiErrorDataOutcome(DescribeApiErrorDataResult(outcome.result()));
else
return DescribeApiErrorDataOutcome(outcome.error());
}
void CloudAPIClient::describeApiErrorDataAsync(const DescribeApiErrorDataRequest& request, const DescribeApiErrorDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiErrorData(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiErrorDataOutcomeCallable CloudAPIClient::describeApiErrorDataCallable(const DescribeApiErrorDataRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiErrorDataOutcome()>>(
[this, request]()
{
return this->describeApiErrorData(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiGroupOutcome CloudAPIClient::describeApiGroup(const DescribeApiGroupRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiGroupOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiGroupOutcome(DescribeApiGroupResult(outcome.result()));
else
return DescribeApiGroupOutcome(outcome.error());
}
void CloudAPIClient::describeApiGroupAsync(const DescribeApiGroupRequest& request, const DescribeApiGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiGroup(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiGroupOutcomeCallable CloudAPIClient::describeApiGroupCallable(const DescribeApiGroupRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiGroupOutcome()>>(
[this, request]()
{
return this->describeApiGroup(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiGroupVpcWhitelistOutcome CloudAPIClient::describeApiGroupVpcWhitelist(const DescribeApiGroupVpcWhitelistRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiGroupVpcWhitelistOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiGroupVpcWhitelistOutcome(DescribeApiGroupVpcWhitelistResult(outcome.result()));
else
return DescribeApiGroupVpcWhitelistOutcome(outcome.error());
}
void CloudAPIClient::describeApiGroupVpcWhitelistAsync(const DescribeApiGroupVpcWhitelistRequest& request, const DescribeApiGroupVpcWhitelistAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiGroupVpcWhitelist(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiGroupVpcWhitelistOutcomeCallable CloudAPIClient::describeApiGroupVpcWhitelistCallable(const DescribeApiGroupVpcWhitelistRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiGroupVpcWhitelistOutcome()>>(
[this, request]()
{
return this->describeApiGroupVpcWhitelist(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiGroupsOutcome CloudAPIClient::describeApiGroups(const DescribeApiGroupsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiGroupsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiGroupsOutcome(DescribeApiGroupsResult(outcome.result()));
else
return DescribeApiGroupsOutcome(outcome.error());
}
void CloudAPIClient::describeApiGroupsAsync(const DescribeApiGroupsRequest& request, const DescribeApiGroupsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiGroups(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiGroupsOutcomeCallable CloudAPIClient::describeApiGroupsCallable(const DescribeApiGroupsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiGroupsOutcome()>>(
[this, request]()
{
return this->describeApiGroups(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiHistoriesOutcome CloudAPIClient::describeApiHistories(const DescribeApiHistoriesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiHistoriesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiHistoriesOutcome(DescribeApiHistoriesResult(outcome.result()));
else
return DescribeApiHistoriesOutcome(outcome.error());
}
void CloudAPIClient::describeApiHistoriesAsync(const DescribeApiHistoriesRequest& request, const DescribeApiHistoriesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiHistories(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiHistoriesOutcomeCallable CloudAPIClient::describeApiHistoriesCallable(const DescribeApiHistoriesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiHistoriesOutcome()>>(
[this, request]()
{
return this->describeApiHistories(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiHistoryOutcome CloudAPIClient::describeApiHistory(const DescribeApiHistoryRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiHistoryOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiHistoryOutcome(DescribeApiHistoryResult(outcome.result()));
else
return DescribeApiHistoryOutcome(outcome.error());
}
void CloudAPIClient::describeApiHistoryAsync(const DescribeApiHistoryRequest& request, const DescribeApiHistoryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiHistory(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiHistoryOutcomeCallable CloudAPIClient::describeApiHistoryCallable(const DescribeApiHistoryRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiHistoryOutcome()>>(
[this, request]()
{
return this->describeApiHistory(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiIpControlsOutcome CloudAPIClient::describeApiIpControls(const DescribeApiIpControlsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiIpControlsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiIpControlsOutcome(DescribeApiIpControlsResult(outcome.result()));
else
return DescribeApiIpControlsOutcome(outcome.error());
}
void CloudAPIClient::describeApiIpControlsAsync(const DescribeApiIpControlsRequest& request, const DescribeApiIpControlsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiIpControls(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiIpControlsOutcomeCallable CloudAPIClient::describeApiIpControlsCallable(const DescribeApiIpControlsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiIpControlsOutcome()>>(
[this, request]()
{
return this->describeApiIpControls(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiLatencyDataOutcome CloudAPIClient::describeApiLatencyData(const DescribeApiLatencyDataRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiLatencyDataOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiLatencyDataOutcome(DescribeApiLatencyDataResult(outcome.result()));
else
return DescribeApiLatencyDataOutcome(outcome.error());
}
void CloudAPIClient::describeApiLatencyDataAsync(const DescribeApiLatencyDataRequest& request, const DescribeApiLatencyDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiLatencyData(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiLatencyDataOutcomeCallable CloudAPIClient::describeApiLatencyDataCallable(const DescribeApiLatencyDataRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiLatencyDataOutcome()>>(
[this, request]()
{
return this->describeApiLatencyData(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiMarketAttributesOutcome CloudAPIClient::describeApiMarketAttributes(const DescribeApiMarketAttributesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiMarketAttributesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiMarketAttributesOutcome(DescribeApiMarketAttributesResult(outcome.result()));
else
return DescribeApiMarketAttributesOutcome(outcome.error());
}
void CloudAPIClient::describeApiMarketAttributesAsync(const DescribeApiMarketAttributesRequest& request, const DescribeApiMarketAttributesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiMarketAttributes(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiMarketAttributesOutcomeCallable CloudAPIClient::describeApiMarketAttributesCallable(const DescribeApiMarketAttributesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiMarketAttributesOutcome()>>(
[this, request]()
{
return this->describeApiMarketAttributes(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiQpsDataOutcome CloudAPIClient::describeApiQpsData(const DescribeApiQpsDataRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiQpsDataOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiQpsDataOutcome(DescribeApiQpsDataResult(outcome.result()));
else
return DescribeApiQpsDataOutcome(outcome.error());
}
void CloudAPIClient::describeApiQpsDataAsync(const DescribeApiQpsDataRequest& request, const DescribeApiQpsDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiQpsData(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiQpsDataOutcomeCallable CloudAPIClient::describeApiQpsDataCallable(const DescribeApiQpsDataRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiQpsDataOutcome()>>(
[this, request]()
{
return this->describeApiQpsData(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiSignaturesOutcome CloudAPIClient::describeApiSignatures(const DescribeApiSignaturesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiSignaturesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiSignaturesOutcome(DescribeApiSignaturesResult(outcome.result()));
else
return DescribeApiSignaturesOutcome(outcome.error());
}
void CloudAPIClient::describeApiSignaturesAsync(const DescribeApiSignaturesRequest& request, const DescribeApiSignaturesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiSignatures(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiSignaturesOutcomeCallable CloudAPIClient::describeApiSignaturesCallable(const DescribeApiSignaturesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiSignaturesOutcome()>>(
[this, request]()
{
return this->describeApiSignatures(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiStageOutcome CloudAPIClient::describeApiStage(const DescribeApiStageRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiStageOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiStageOutcome(DescribeApiStageResult(outcome.result()));
else
return DescribeApiStageOutcome(outcome.error());
}
void CloudAPIClient::describeApiStageAsync(const DescribeApiStageRequest& request, const DescribeApiStageAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiStage(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiStageOutcomeCallable CloudAPIClient::describeApiStageCallable(const DescribeApiStageRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiStageOutcome()>>(
[this, request]()
{
return this->describeApiStage(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiTrafficControlsOutcome CloudAPIClient::describeApiTrafficControls(const DescribeApiTrafficControlsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiTrafficControlsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiTrafficControlsOutcome(DescribeApiTrafficControlsResult(outcome.result()));
else
return DescribeApiTrafficControlsOutcome(outcome.error());
}
void CloudAPIClient::describeApiTrafficControlsAsync(const DescribeApiTrafficControlsRequest& request, const DescribeApiTrafficControlsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiTrafficControls(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiTrafficControlsOutcomeCallable CloudAPIClient::describeApiTrafficControlsCallable(const DescribeApiTrafficControlsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiTrafficControlsOutcome()>>(
[this, request]()
{
return this->describeApiTrafficControls(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApiTrafficDataOutcome CloudAPIClient::describeApiTrafficData(const DescribeApiTrafficDataRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApiTrafficDataOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApiTrafficDataOutcome(DescribeApiTrafficDataResult(outcome.result()));
else
return DescribeApiTrafficDataOutcome(outcome.error());
}
void CloudAPIClient::describeApiTrafficDataAsync(const DescribeApiTrafficDataRequest& request, const DescribeApiTrafficDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApiTrafficData(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApiTrafficDataOutcomeCallable CloudAPIClient::describeApiTrafficDataCallable(const DescribeApiTrafficDataRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApiTrafficDataOutcome()>>(
[this, request]()
{
return this->describeApiTrafficData(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApisOutcome CloudAPIClient::describeApis(const DescribeApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApisOutcome(DescribeApisResult(outcome.result()));
else
return DescribeApisOutcome(outcome.error());
}
void CloudAPIClient::describeApisAsync(const DescribeApisRequest& request, const DescribeApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApisOutcomeCallable CloudAPIClient::describeApisCallable(const DescribeApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApisOutcome()>>(
[this, request]()
{
return this->describeApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApisByAppOutcome CloudAPIClient::describeApisByApp(const DescribeApisByAppRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApisByAppOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApisByAppOutcome(DescribeApisByAppResult(outcome.result()));
else
return DescribeApisByAppOutcome(outcome.error());
}
void CloudAPIClient::describeApisByAppAsync(const DescribeApisByAppRequest& request, const DescribeApisByAppAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApisByApp(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApisByAppOutcomeCallable CloudAPIClient::describeApisByAppCallable(const DescribeApisByAppRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApisByAppOutcome()>>(
[this, request]()
{
return this->describeApisByApp(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApisByIpControlOutcome CloudAPIClient::describeApisByIpControl(const DescribeApisByIpControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApisByIpControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApisByIpControlOutcome(DescribeApisByIpControlResult(outcome.result()));
else
return DescribeApisByIpControlOutcome(outcome.error());
}
void CloudAPIClient::describeApisByIpControlAsync(const DescribeApisByIpControlRequest& request, const DescribeApisByIpControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApisByIpControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApisByIpControlOutcomeCallable CloudAPIClient::describeApisByIpControlCallable(const DescribeApisByIpControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApisByIpControlOutcome()>>(
[this, request]()
{
return this->describeApisByIpControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApisBySignatureOutcome CloudAPIClient::describeApisBySignature(const DescribeApisBySignatureRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApisBySignatureOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApisBySignatureOutcome(DescribeApisBySignatureResult(outcome.result()));
else
return DescribeApisBySignatureOutcome(outcome.error());
}
void CloudAPIClient::describeApisBySignatureAsync(const DescribeApisBySignatureRequest& request, const DescribeApisBySignatureAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApisBySignature(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApisBySignatureOutcomeCallable CloudAPIClient::describeApisBySignatureCallable(const DescribeApisBySignatureRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApisBySignatureOutcome()>>(
[this, request]()
{
return this->describeApisBySignature(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeApisByTrafficControlOutcome CloudAPIClient::describeApisByTrafficControl(const DescribeApisByTrafficControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeApisByTrafficControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeApisByTrafficControlOutcome(DescribeApisByTrafficControlResult(outcome.result()));
else
return DescribeApisByTrafficControlOutcome(outcome.error());
}
void CloudAPIClient::describeApisByTrafficControlAsync(const DescribeApisByTrafficControlRequest& request, const DescribeApisByTrafficControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApisByTrafficControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeApisByTrafficControlOutcomeCallable CloudAPIClient::describeApisByTrafficControlCallable(const DescribeApisByTrafficControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeApisByTrafficControlOutcome()>>(
[this, request]()
{
return this->describeApisByTrafficControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeAppOutcome CloudAPIClient::describeApp(const DescribeAppRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeAppOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeAppOutcome(DescribeAppResult(outcome.result()));
else
return DescribeAppOutcome(outcome.error());
}
void CloudAPIClient::describeAppAsync(const DescribeAppRequest& request, const DescribeAppAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApp(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeAppOutcomeCallable CloudAPIClient::describeAppCallable(const DescribeAppRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeAppOutcome()>>(
[this, request]()
{
return this->describeApp(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeAppAttributesOutcome CloudAPIClient::describeAppAttributes(const DescribeAppAttributesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeAppAttributesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeAppAttributesOutcome(DescribeAppAttributesResult(outcome.result()));
else
return DescribeAppAttributesOutcome(outcome.error());
}
void CloudAPIClient::describeAppAttributesAsync(const DescribeAppAttributesRequest& request, const DescribeAppAttributesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeAppAttributes(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeAppAttributesOutcomeCallable CloudAPIClient::describeAppAttributesCallable(const DescribeAppAttributesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeAppAttributesOutcome()>>(
[this, request]()
{
return this->describeAppAttributes(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeAppSecurityOutcome CloudAPIClient::describeAppSecurity(const DescribeAppSecurityRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeAppSecurityOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeAppSecurityOutcome(DescribeAppSecurityResult(outcome.result()));
else
return DescribeAppSecurityOutcome(outcome.error());
}
void CloudAPIClient::describeAppSecurityAsync(const DescribeAppSecurityRequest& request, const DescribeAppSecurityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeAppSecurity(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeAppSecurityOutcomeCallable CloudAPIClient::describeAppSecurityCallable(const DescribeAppSecurityRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeAppSecurityOutcome()>>(
[this, request]()
{
return this->describeAppSecurity(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeAppsOutcome CloudAPIClient::describeApps(const DescribeAppsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeAppsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeAppsOutcome(DescribeAppsResult(outcome.result()));
else
return DescribeAppsOutcome(outcome.error());
}
void CloudAPIClient::describeAppsAsync(const DescribeAppsRequest& request, const DescribeAppsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeApps(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeAppsOutcomeCallable CloudAPIClient::describeAppsCallable(const DescribeAppsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeAppsOutcome()>>(
[this, request]()
{
return this->describeApps(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeAuthorizedApisOutcome CloudAPIClient::describeAuthorizedApis(const DescribeAuthorizedApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeAuthorizedApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeAuthorizedApisOutcome(DescribeAuthorizedApisResult(outcome.result()));
else
return DescribeAuthorizedApisOutcome(outcome.error());
}
void CloudAPIClient::describeAuthorizedApisAsync(const DescribeAuthorizedApisRequest& request, const DescribeAuthorizedApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeAuthorizedApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeAuthorizedApisOutcomeCallable CloudAPIClient::describeAuthorizedApisCallable(const DescribeAuthorizedApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeAuthorizedApisOutcome()>>(
[this, request]()
{
return this->describeAuthorizedApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeAuthorizedAppsOutcome CloudAPIClient::describeAuthorizedApps(const DescribeAuthorizedAppsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeAuthorizedAppsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeAuthorizedAppsOutcome(DescribeAuthorizedAppsResult(outcome.result()));
else
return DescribeAuthorizedAppsOutcome(outcome.error());
}
void CloudAPIClient::describeAuthorizedAppsAsync(const DescribeAuthorizedAppsRequest& request, const DescribeAuthorizedAppsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeAuthorizedApps(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeAuthorizedAppsOutcomeCallable CloudAPIClient::describeAuthorizedAppsCallable(const DescribeAuthorizedAppsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeAuthorizedAppsOutcome()>>(
[this, request]()
{
return this->describeAuthorizedApps(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeDeployedApiOutcome CloudAPIClient::describeDeployedApi(const DescribeDeployedApiRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeDeployedApiOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeDeployedApiOutcome(DescribeDeployedApiResult(outcome.result()));
else
return DescribeDeployedApiOutcome(outcome.error());
}
void CloudAPIClient::describeDeployedApiAsync(const DescribeDeployedApiRequest& request, const DescribeDeployedApiAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeDeployedApi(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeDeployedApiOutcomeCallable CloudAPIClient::describeDeployedApiCallable(const DescribeDeployedApiRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeDeployedApiOutcome()>>(
[this, request]()
{
return this->describeDeployedApi(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeDeployedApisOutcome CloudAPIClient::describeDeployedApis(const DescribeDeployedApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeDeployedApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeDeployedApisOutcome(DescribeDeployedApisResult(outcome.result()));
else
return DescribeDeployedApisOutcome(outcome.error());
}
void CloudAPIClient::describeDeployedApisAsync(const DescribeDeployedApisRequest& request, const DescribeDeployedApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeDeployedApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeDeployedApisOutcomeCallable CloudAPIClient::describeDeployedApisCallable(const DescribeDeployedApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeDeployedApisOutcome()>>(
[this, request]()
{
return this->describeDeployedApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeDomainOutcome CloudAPIClient::describeDomain(const DescribeDomainRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeDomainOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeDomainOutcome(DescribeDomainResult(outcome.result()));
else
return DescribeDomainOutcome(outcome.error());
}
void CloudAPIClient::describeDomainAsync(const DescribeDomainRequest& request, const DescribeDomainAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeDomain(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeDomainOutcomeCallable CloudAPIClient::describeDomainCallable(const DescribeDomainRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeDomainOutcome()>>(
[this, request]()
{
return this->describeDomain(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeDomainsResolutionOutcome CloudAPIClient::describeDomainsResolution(const DescribeDomainsResolutionRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeDomainsResolutionOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeDomainsResolutionOutcome(DescribeDomainsResolutionResult(outcome.result()));
else
return DescribeDomainsResolutionOutcome(outcome.error());
}
void CloudAPIClient::describeDomainsResolutionAsync(const DescribeDomainsResolutionRequest& request, const DescribeDomainsResolutionAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeDomainsResolution(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeDomainsResolutionOutcomeCallable CloudAPIClient::describeDomainsResolutionCallable(const DescribeDomainsResolutionRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeDomainsResolutionOutcome()>>(
[this, request]()
{
return this->describeDomainsResolution(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeHistoryApisOutcome CloudAPIClient::describeHistoryApis(const DescribeHistoryApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeHistoryApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeHistoryApisOutcome(DescribeHistoryApisResult(outcome.result()));
else
return DescribeHistoryApisOutcome(outcome.error());
}
void CloudAPIClient::describeHistoryApisAsync(const DescribeHistoryApisRequest& request, const DescribeHistoryApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeHistoryApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeHistoryApisOutcomeCallable CloudAPIClient::describeHistoryApisCallable(const DescribeHistoryApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeHistoryApisOutcome()>>(
[this, request]()
{
return this->describeHistoryApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeIpControlPolicyItemsOutcome CloudAPIClient::describeIpControlPolicyItems(const DescribeIpControlPolicyItemsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeIpControlPolicyItemsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeIpControlPolicyItemsOutcome(DescribeIpControlPolicyItemsResult(outcome.result()));
else
return DescribeIpControlPolicyItemsOutcome(outcome.error());
}
void CloudAPIClient::describeIpControlPolicyItemsAsync(const DescribeIpControlPolicyItemsRequest& request, const DescribeIpControlPolicyItemsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeIpControlPolicyItems(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeIpControlPolicyItemsOutcomeCallable CloudAPIClient::describeIpControlPolicyItemsCallable(const DescribeIpControlPolicyItemsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeIpControlPolicyItemsOutcome()>>(
[this, request]()
{
return this->describeIpControlPolicyItems(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeIpControlsOutcome CloudAPIClient::describeIpControls(const DescribeIpControlsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeIpControlsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeIpControlsOutcome(DescribeIpControlsResult(outcome.result()));
else
return DescribeIpControlsOutcome(outcome.error());
}
void CloudAPIClient::describeIpControlsAsync(const DescribeIpControlsRequest& request, const DescribeIpControlsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeIpControls(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeIpControlsOutcomeCallable CloudAPIClient::describeIpControlsCallable(const DescribeIpControlsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeIpControlsOutcome()>>(
[this, request]()
{
return this->describeIpControls(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeLogConfigOutcome CloudAPIClient::describeLogConfig(const DescribeLogConfigRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeLogConfigOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeLogConfigOutcome(DescribeLogConfigResult(outcome.result()));
else
return DescribeLogConfigOutcome(outcome.error());
}
void CloudAPIClient::describeLogConfigAsync(const DescribeLogConfigRequest& request, const DescribeLogConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeLogConfig(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeLogConfigOutcomeCallable CloudAPIClient::describeLogConfigCallable(const DescribeLogConfigRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeLogConfigOutcome()>>(
[this, request]()
{
return this->describeLogConfig(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribePurchasedApiGroupOutcome CloudAPIClient::describePurchasedApiGroup(const DescribePurchasedApiGroupRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribePurchasedApiGroupOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribePurchasedApiGroupOutcome(DescribePurchasedApiGroupResult(outcome.result()));
else
return DescribePurchasedApiGroupOutcome(outcome.error());
}
void CloudAPIClient::describePurchasedApiGroupAsync(const DescribePurchasedApiGroupRequest& request, const DescribePurchasedApiGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describePurchasedApiGroup(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribePurchasedApiGroupOutcomeCallable CloudAPIClient::describePurchasedApiGroupCallable(const DescribePurchasedApiGroupRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribePurchasedApiGroupOutcome()>>(
[this, request]()
{
return this->describePurchasedApiGroup(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribePurchasedApiGroupsOutcome CloudAPIClient::describePurchasedApiGroups(const DescribePurchasedApiGroupsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribePurchasedApiGroupsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribePurchasedApiGroupsOutcome(DescribePurchasedApiGroupsResult(outcome.result()));
else
return DescribePurchasedApiGroupsOutcome(outcome.error());
}
void CloudAPIClient::describePurchasedApiGroupsAsync(const DescribePurchasedApiGroupsRequest& request, const DescribePurchasedApiGroupsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describePurchasedApiGroups(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribePurchasedApiGroupsOutcomeCallable CloudAPIClient::describePurchasedApiGroupsCallable(const DescribePurchasedApiGroupsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribePurchasedApiGroupsOutcome()>>(
[this, request]()
{
return this->describePurchasedApiGroups(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribePurchasedApisOutcome CloudAPIClient::describePurchasedApis(const DescribePurchasedApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribePurchasedApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribePurchasedApisOutcome(DescribePurchasedApisResult(outcome.result()));
else
return DescribePurchasedApisOutcome(outcome.error());
}
void CloudAPIClient::describePurchasedApisAsync(const DescribePurchasedApisRequest& request, const DescribePurchasedApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describePurchasedApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribePurchasedApisOutcomeCallable CloudAPIClient::describePurchasedApisCallable(const DescribePurchasedApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribePurchasedApisOutcome()>>(
[this, request]()
{
return this->describePurchasedApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeRegionsOutcome CloudAPIClient::describeRegions(const DescribeRegionsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeRegionsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeRegionsOutcome(DescribeRegionsResult(outcome.result()));
else
return DescribeRegionsOutcome(outcome.error());
}
void CloudAPIClient::describeRegionsAsync(const DescribeRegionsRequest& request, const DescribeRegionsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeRegions(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeRegionsOutcomeCallable CloudAPIClient::describeRegionsCallable(const DescribeRegionsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeRegionsOutcome()>>(
[this, request]()
{
return this->describeRegions(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeSignaturesOutcome CloudAPIClient::describeSignatures(const DescribeSignaturesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeSignaturesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeSignaturesOutcome(DescribeSignaturesResult(outcome.result()));
else
return DescribeSignaturesOutcome(outcome.error());
}
void CloudAPIClient::describeSignaturesAsync(const DescribeSignaturesRequest& request, const DescribeSignaturesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeSignatures(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeSignaturesOutcomeCallable CloudAPIClient::describeSignaturesCallable(const DescribeSignaturesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeSignaturesOutcome()>>(
[this, request]()
{
return this->describeSignatures(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeSignaturesByApiOutcome CloudAPIClient::describeSignaturesByApi(const DescribeSignaturesByApiRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeSignaturesByApiOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeSignaturesByApiOutcome(DescribeSignaturesByApiResult(outcome.result()));
else
return DescribeSignaturesByApiOutcome(outcome.error());
}
void CloudAPIClient::describeSignaturesByApiAsync(const DescribeSignaturesByApiRequest& request, const DescribeSignaturesByApiAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeSignaturesByApi(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeSignaturesByApiOutcomeCallable CloudAPIClient::describeSignaturesByApiCallable(const DescribeSignaturesByApiRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeSignaturesByApiOutcome()>>(
[this, request]()
{
return this->describeSignaturesByApi(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeSystemParametersOutcome CloudAPIClient::describeSystemParameters(const DescribeSystemParametersRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeSystemParametersOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeSystemParametersOutcome(DescribeSystemParametersResult(outcome.result()));
else
return DescribeSystemParametersOutcome(outcome.error());
}
void CloudAPIClient::describeSystemParametersAsync(const DescribeSystemParametersRequest& request, const DescribeSystemParametersAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeSystemParameters(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeSystemParametersOutcomeCallable CloudAPIClient::describeSystemParametersCallable(const DescribeSystemParametersRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeSystemParametersOutcome()>>(
[this, request]()
{
return this->describeSystemParameters(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeTrafficControlsOutcome CloudAPIClient::describeTrafficControls(const DescribeTrafficControlsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeTrafficControlsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeTrafficControlsOutcome(DescribeTrafficControlsResult(outcome.result()));
else
return DescribeTrafficControlsOutcome(outcome.error());
}
void CloudAPIClient::describeTrafficControlsAsync(const DescribeTrafficControlsRequest& request, const DescribeTrafficControlsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeTrafficControls(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeTrafficControlsOutcomeCallable CloudAPIClient::describeTrafficControlsCallable(const DescribeTrafficControlsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeTrafficControlsOutcome()>>(
[this, request]()
{
return this->describeTrafficControls(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeTrafficControlsByApiOutcome CloudAPIClient::describeTrafficControlsByApi(const DescribeTrafficControlsByApiRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeTrafficControlsByApiOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeTrafficControlsByApiOutcome(DescribeTrafficControlsByApiResult(outcome.result()));
else
return DescribeTrafficControlsByApiOutcome(outcome.error());
}
void CloudAPIClient::describeTrafficControlsByApiAsync(const DescribeTrafficControlsByApiRequest& request, const DescribeTrafficControlsByApiAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeTrafficControlsByApi(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeTrafficControlsByApiOutcomeCallable CloudAPIClient::describeTrafficControlsByApiCallable(const DescribeTrafficControlsByApiRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeTrafficControlsByApiOutcome()>>(
[this, request]()
{
return this->describeTrafficControlsByApi(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::DescribeVpcAccessesOutcome CloudAPIClient::describeVpcAccesses(const DescribeVpcAccessesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeVpcAccessesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeVpcAccessesOutcome(DescribeVpcAccessesResult(outcome.result()));
else
return DescribeVpcAccessesOutcome(outcome.error());
}
void CloudAPIClient::describeVpcAccessesAsync(const DescribeVpcAccessesRequest& request, const DescribeVpcAccessesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeVpcAccesses(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::DescribeVpcAccessesOutcomeCallable CloudAPIClient::describeVpcAccessesCallable(const DescribeVpcAccessesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeVpcAccessesOutcome()>>(
[this, request]()
{
return this->describeVpcAccesses(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ImportSwaggerOutcome CloudAPIClient::importSwagger(const ImportSwaggerRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ImportSwaggerOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ImportSwaggerOutcome(ImportSwaggerResult(outcome.result()));
else
return ImportSwaggerOutcome(outcome.error());
}
void CloudAPIClient::importSwaggerAsync(const ImportSwaggerRequest& request, const ImportSwaggerAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, importSwagger(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ImportSwaggerOutcomeCallable CloudAPIClient::importSwaggerCallable(const ImportSwaggerRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ImportSwaggerOutcome()>>(
[this, request]()
{
return this->importSwagger(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ListTagResourcesOutcome CloudAPIClient::listTagResources(const ListTagResourcesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListTagResourcesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListTagResourcesOutcome(ListTagResourcesResult(outcome.result()));
else
return ListTagResourcesOutcome(outcome.error());
}
void CloudAPIClient::listTagResourcesAsync(const ListTagResourcesRequest& request, const ListTagResourcesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listTagResources(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ListTagResourcesOutcomeCallable CloudAPIClient::listTagResourcesCallable(const ListTagResourcesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListTagResourcesOutcome()>>(
[this, request]()
{
return this->listTagResources(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ModifyApiOutcome CloudAPIClient::modifyApi(const ModifyApiRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ModifyApiOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ModifyApiOutcome(ModifyApiResult(outcome.result()));
else
return ModifyApiOutcome(outcome.error());
}
void CloudAPIClient::modifyApiAsync(const ModifyApiRequest& request, const ModifyApiAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, modifyApi(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ModifyApiOutcomeCallable CloudAPIClient::modifyApiCallable(const ModifyApiRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ModifyApiOutcome()>>(
[this, request]()
{
return this->modifyApi(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ModifyApiGroupOutcome CloudAPIClient::modifyApiGroup(const ModifyApiGroupRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ModifyApiGroupOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ModifyApiGroupOutcome(ModifyApiGroupResult(outcome.result()));
else
return ModifyApiGroupOutcome(outcome.error());
}
void CloudAPIClient::modifyApiGroupAsync(const ModifyApiGroupRequest& request, const ModifyApiGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, modifyApiGroup(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ModifyApiGroupOutcomeCallable CloudAPIClient::modifyApiGroupCallable(const ModifyApiGroupRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ModifyApiGroupOutcome()>>(
[this, request]()
{
return this->modifyApiGroup(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ModifyApiGroupVpcWhitelistOutcome CloudAPIClient::modifyApiGroupVpcWhitelist(const ModifyApiGroupVpcWhitelistRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ModifyApiGroupVpcWhitelistOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ModifyApiGroupVpcWhitelistOutcome(ModifyApiGroupVpcWhitelistResult(outcome.result()));
else
return ModifyApiGroupVpcWhitelistOutcome(outcome.error());
}
void CloudAPIClient::modifyApiGroupVpcWhitelistAsync(const ModifyApiGroupVpcWhitelistRequest& request, const ModifyApiGroupVpcWhitelistAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, modifyApiGroupVpcWhitelist(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ModifyApiGroupVpcWhitelistOutcomeCallable CloudAPIClient::modifyApiGroupVpcWhitelistCallable(const ModifyApiGroupVpcWhitelistRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ModifyApiGroupVpcWhitelistOutcome()>>(
[this, request]()
{
return this->modifyApiGroupVpcWhitelist(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ModifyApiMarketAttributesOutcome CloudAPIClient::modifyApiMarketAttributes(const ModifyApiMarketAttributesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ModifyApiMarketAttributesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ModifyApiMarketAttributesOutcome(ModifyApiMarketAttributesResult(outcome.result()));
else
return ModifyApiMarketAttributesOutcome(outcome.error());
}
void CloudAPIClient::modifyApiMarketAttributesAsync(const ModifyApiMarketAttributesRequest& request, const ModifyApiMarketAttributesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, modifyApiMarketAttributes(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ModifyApiMarketAttributesOutcomeCallable CloudAPIClient::modifyApiMarketAttributesCallable(const ModifyApiMarketAttributesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ModifyApiMarketAttributesOutcome()>>(
[this, request]()
{
return this->modifyApiMarketAttributes(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ModifyAppOutcome CloudAPIClient::modifyApp(const ModifyAppRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ModifyAppOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ModifyAppOutcome(ModifyAppResult(outcome.result()));
else
return ModifyAppOutcome(outcome.error());
}
void CloudAPIClient::modifyAppAsync(const ModifyAppRequest& request, const ModifyAppAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, modifyApp(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ModifyAppOutcomeCallable CloudAPIClient::modifyAppCallable(const ModifyAppRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ModifyAppOutcome()>>(
[this, request]()
{
return this->modifyApp(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ModifyIpControlOutcome CloudAPIClient::modifyIpControl(const ModifyIpControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ModifyIpControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ModifyIpControlOutcome(ModifyIpControlResult(outcome.result()));
else
return ModifyIpControlOutcome(outcome.error());
}
void CloudAPIClient::modifyIpControlAsync(const ModifyIpControlRequest& request, const ModifyIpControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, modifyIpControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ModifyIpControlOutcomeCallable CloudAPIClient::modifyIpControlCallable(const ModifyIpControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ModifyIpControlOutcome()>>(
[this, request]()
{
return this->modifyIpControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ModifyIpControlPolicyItemOutcome CloudAPIClient::modifyIpControlPolicyItem(const ModifyIpControlPolicyItemRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ModifyIpControlPolicyItemOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ModifyIpControlPolicyItemOutcome(ModifyIpControlPolicyItemResult(outcome.result()));
else
return ModifyIpControlPolicyItemOutcome(outcome.error());
}
void CloudAPIClient::modifyIpControlPolicyItemAsync(const ModifyIpControlPolicyItemRequest& request, const ModifyIpControlPolicyItemAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, modifyIpControlPolicyItem(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ModifyIpControlPolicyItemOutcomeCallable CloudAPIClient::modifyIpControlPolicyItemCallable(const ModifyIpControlPolicyItemRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ModifyIpControlPolicyItemOutcome()>>(
[this, request]()
{
return this->modifyIpControlPolicyItem(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ModifyLogConfigOutcome CloudAPIClient::modifyLogConfig(const ModifyLogConfigRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ModifyLogConfigOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ModifyLogConfigOutcome(ModifyLogConfigResult(outcome.result()));
else
return ModifyLogConfigOutcome(outcome.error());
}
void CloudAPIClient::modifyLogConfigAsync(const ModifyLogConfigRequest& request, const ModifyLogConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, modifyLogConfig(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ModifyLogConfigOutcomeCallable CloudAPIClient::modifyLogConfigCallable(const ModifyLogConfigRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ModifyLogConfigOutcome()>>(
[this, request]()
{
return this->modifyLogConfig(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ModifySignatureOutcome CloudAPIClient::modifySignature(const ModifySignatureRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ModifySignatureOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ModifySignatureOutcome(ModifySignatureResult(outcome.result()));
else
return ModifySignatureOutcome(outcome.error());
}
void CloudAPIClient::modifySignatureAsync(const ModifySignatureRequest& request, const ModifySignatureAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, modifySignature(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ModifySignatureOutcomeCallable CloudAPIClient::modifySignatureCallable(const ModifySignatureRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ModifySignatureOutcome()>>(
[this, request]()
{
return this->modifySignature(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ModifyTrafficControlOutcome CloudAPIClient::modifyTrafficControl(const ModifyTrafficControlRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ModifyTrafficControlOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ModifyTrafficControlOutcome(ModifyTrafficControlResult(outcome.result()));
else
return ModifyTrafficControlOutcome(outcome.error());
}
void CloudAPIClient::modifyTrafficControlAsync(const ModifyTrafficControlRequest& request, const ModifyTrafficControlAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, modifyTrafficControl(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ModifyTrafficControlOutcomeCallable CloudAPIClient::modifyTrafficControlCallable(const ModifyTrafficControlRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ModifyTrafficControlOutcome()>>(
[this, request]()
{
return this->modifyTrafficControl(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ReactivateDomainOutcome CloudAPIClient::reactivateDomain(const ReactivateDomainRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ReactivateDomainOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ReactivateDomainOutcome(ReactivateDomainResult(outcome.result()));
else
return ReactivateDomainOutcome(outcome.error());
}
void CloudAPIClient::reactivateDomainAsync(const ReactivateDomainRequest& request, const ReactivateDomainAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, reactivateDomain(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ReactivateDomainOutcomeCallable CloudAPIClient::reactivateDomainCallable(const ReactivateDomainRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ReactivateDomainOutcome()>>(
[this, request]()
{
return this->reactivateDomain(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::RemoveApisAuthoritiesOutcome CloudAPIClient::removeApisAuthorities(const RemoveApisAuthoritiesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RemoveApisAuthoritiesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RemoveApisAuthoritiesOutcome(RemoveApisAuthoritiesResult(outcome.result()));
else
return RemoveApisAuthoritiesOutcome(outcome.error());
}
void CloudAPIClient::removeApisAuthoritiesAsync(const RemoveApisAuthoritiesRequest& request, const RemoveApisAuthoritiesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, removeApisAuthorities(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::RemoveApisAuthoritiesOutcomeCallable CloudAPIClient::removeApisAuthoritiesCallable(const RemoveApisAuthoritiesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RemoveApisAuthoritiesOutcome()>>(
[this, request]()
{
return this->removeApisAuthorities(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::RemoveAppsAuthoritiesOutcome CloudAPIClient::removeAppsAuthorities(const RemoveAppsAuthoritiesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RemoveAppsAuthoritiesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RemoveAppsAuthoritiesOutcome(RemoveAppsAuthoritiesResult(outcome.result()));
else
return RemoveAppsAuthoritiesOutcome(outcome.error());
}
void CloudAPIClient::removeAppsAuthoritiesAsync(const RemoveAppsAuthoritiesRequest& request, const RemoveAppsAuthoritiesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, removeAppsAuthorities(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::RemoveAppsAuthoritiesOutcomeCallable CloudAPIClient::removeAppsAuthoritiesCallable(const RemoveAppsAuthoritiesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RemoveAppsAuthoritiesOutcome()>>(
[this, request]()
{
return this->removeAppsAuthorities(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::RemoveIpControlApisOutcome CloudAPIClient::removeIpControlApis(const RemoveIpControlApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RemoveIpControlApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RemoveIpControlApisOutcome(RemoveIpControlApisResult(outcome.result()));
else
return RemoveIpControlApisOutcome(outcome.error());
}
void CloudAPIClient::removeIpControlApisAsync(const RemoveIpControlApisRequest& request, const RemoveIpControlApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, removeIpControlApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::RemoveIpControlApisOutcomeCallable CloudAPIClient::removeIpControlApisCallable(const RemoveIpControlApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RemoveIpControlApisOutcome()>>(
[this, request]()
{
return this->removeIpControlApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::RemoveIpControlPolicyItemOutcome CloudAPIClient::removeIpControlPolicyItem(const RemoveIpControlPolicyItemRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RemoveIpControlPolicyItemOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RemoveIpControlPolicyItemOutcome(RemoveIpControlPolicyItemResult(outcome.result()));
else
return RemoveIpControlPolicyItemOutcome(outcome.error());
}
void CloudAPIClient::removeIpControlPolicyItemAsync(const RemoveIpControlPolicyItemRequest& request, const RemoveIpControlPolicyItemAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, removeIpControlPolicyItem(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::RemoveIpControlPolicyItemOutcomeCallable CloudAPIClient::removeIpControlPolicyItemCallable(const RemoveIpControlPolicyItemRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RemoveIpControlPolicyItemOutcome()>>(
[this, request]()
{
return this->removeIpControlPolicyItem(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::RemoveSignatureApisOutcome CloudAPIClient::removeSignatureApis(const RemoveSignatureApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RemoveSignatureApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RemoveSignatureApisOutcome(RemoveSignatureApisResult(outcome.result()));
else
return RemoveSignatureApisOutcome(outcome.error());
}
void CloudAPIClient::removeSignatureApisAsync(const RemoveSignatureApisRequest& request, const RemoveSignatureApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, removeSignatureApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::RemoveSignatureApisOutcomeCallable CloudAPIClient::removeSignatureApisCallable(const RemoveSignatureApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RemoveSignatureApisOutcome()>>(
[this, request]()
{
return this->removeSignatureApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::RemoveTrafficControlApisOutcome CloudAPIClient::removeTrafficControlApis(const RemoveTrafficControlApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RemoveTrafficControlApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RemoveTrafficControlApisOutcome(RemoveTrafficControlApisResult(outcome.result()));
else
return RemoveTrafficControlApisOutcome(outcome.error());
}
void CloudAPIClient::removeTrafficControlApisAsync(const RemoveTrafficControlApisRequest& request, const RemoveTrafficControlApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, removeTrafficControlApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::RemoveTrafficControlApisOutcomeCallable CloudAPIClient::removeTrafficControlApisCallable(const RemoveTrafficControlApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RemoveTrafficControlApisOutcome()>>(
[this, request]()
{
return this->removeTrafficControlApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::RemoveVpcAccessOutcome CloudAPIClient::removeVpcAccess(const RemoveVpcAccessRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RemoveVpcAccessOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RemoveVpcAccessOutcome(RemoveVpcAccessResult(outcome.result()));
else
return RemoveVpcAccessOutcome(outcome.error());
}
void CloudAPIClient::removeVpcAccessAsync(const RemoveVpcAccessRequest& request, const RemoveVpcAccessAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, removeVpcAccess(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::RemoveVpcAccessOutcomeCallable CloudAPIClient::removeVpcAccessCallable(const RemoveVpcAccessRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RemoveVpcAccessOutcome()>>(
[this, request]()
{
return this->removeVpcAccess(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ResetAppCodeOutcome CloudAPIClient::resetAppCode(const ResetAppCodeRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ResetAppCodeOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ResetAppCodeOutcome(ResetAppCodeResult(outcome.result()));
else
return ResetAppCodeOutcome(outcome.error());
}
void CloudAPIClient::resetAppCodeAsync(const ResetAppCodeRequest& request, const ResetAppCodeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, resetAppCode(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ResetAppCodeOutcomeCallable CloudAPIClient::resetAppCodeCallable(const ResetAppCodeRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ResetAppCodeOutcome()>>(
[this, request]()
{
return this->resetAppCode(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::ResetAppSecretOutcome CloudAPIClient::resetAppSecret(const ResetAppSecretRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ResetAppSecretOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ResetAppSecretOutcome(ResetAppSecretResult(outcome.result()));
else
return ResetAppSecretOutcome(outcome.error());
}
void CloudAPIClient::resetAppSecretAsync(const ResetAppSecretRequest& request, const ResetAppSecretAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, resetAppSecret(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::ResetAppSecretOutcomeCallable CloudAPIClient::resetAppSecretCallable(const ResetAppSecretRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ResetAppSecretOutcome()>>(
[this, request]()
{
return this->resetAppSecret(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SdkGenerateByAppOutcome CloudAPIClient::sdkGenerateByApp(const SdkGenerateByAppRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SdkGenerateByAppOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SdkGenerateByAppOutcome(SdkGenerateByAppResult(outcome.result()));
else
return SdkGenerateByAppOutcome(outcome.error());
}
void CloudAPIClient::sdkGenerateByAppAsync(const SdkGenerateByAppRequest& request, const SdkGenerateByAppAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, sdkGenerateByApp(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SdkGenerateByAppOutcomeCallable CloudAPIClient::sdkGenerateByAppCallable(const SdkGenerateByAppRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SdkGenerateByAppOutcome()>>(
[this, request]()
{
return this->sdkGenerateByApp(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SdkGenerateByGroupOutcome CloudAPIClient::sdkGenerateByGroup(const SdkGenerateByGroupRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SdkGenerateByGroupOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SdkGenerateByGroupOutcome(SdkGenerateByGroupResult(outcome.result()));
else
return SdkGenerateByGroupOutcome(outcome.error());
}
void CloudAPIClient::sdkGenerateByGroupAsync(const SdkGenerateByGroupRequest& request, const SdkGenerateByGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, sdkGenerateByGroup(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SdkGenerateByGroupOutcomeCallable CloudAPIClient::sdkGenerateByGroupCallable(const SdkGenerateByGroupRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SdkGenerateByGroupOutcome()>>(
[this, request]()
{
return this->sdkGenerateByGroup(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SetApisAuthoritiesOutcome CloudAPIClient::setApisAuthorities(const SetApisAuthoritiesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetApisAuthoritiesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetApisAuthoritiesOutcome(SetApisAuthoritiesResult(outcome.result()));
else
return SetApisAuthoritiesOutcome(outcome.error());
}
void CloudAPIClient::setApisAuthoritiesAsync(const SetApisAuthoritiesRequest& request, const SetApisAuthoritiesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setApisAuthorities(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SetApisAuthoritiesOutcomeCallable CloudAPIClient::setApisAuthoritiesCallable(const SetApisAuthoritiesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetApisAuthoritiesOutcome()>>(
[this, request]()
{
return this->setApisAuthorities(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SetAppsAuthoritiesOutcome CloudAPIClient::setAppsAuthorities(const SetAppsAuthoritiesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetAppsAuthoritiesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetAppsAuthoritiesOutcome(SetAppsAuthoritiesResult(outcome.result()));
else
return SetAppsAuthoritiesOutcome(outcome.error());
}
void CloudAPIClient::setAppsAuthoritiesAsync(const SetAppsAuthoritiesRequest& request, const SetAppsAuthoritiesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setAppsAuthorities(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SetAppsAuthoritiesOutcomeCallable CloudAPIClient::setAppsAuthoritiesCallable(const SetAppsAuthoritiesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetAppsAuthoritiesOutcome()>>(
[this, request]()
{
return this->setAppsAuthorities(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SetDomainOutcome CloudAPIClient::setDomain(const SetDomainRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetDomainOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetDomainOutcome(SetDomainResult(outcome.result()));
else
return SetDomainOutcome(outcome.error());
}
void CloudAPIClient::setDomainAsync(const SetDomainRequest& request, const SetDomainAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setDomain(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SetDomainOutcomeCallable CloudAPIClient::setDomainCallable(const SetDomainRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetDomainOutcome()>>(
[this, request]()
{
return this->setDomain(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SetDomainCertificateOutcome CloudAPIClient::setDomainCertificate(const SetDomainCertificateRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetDomainCertificateOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetDomainCertificateOutcome(SetDomainCertificateResult(outcome.result()));
else
return SetDomainCertificateOutcome(outcome.error());
}
void CloudAPIClient::setDomainCertificateAsync(const SetDomainCertificateRequest& request, const SetDomainCertificateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setDomainCertificate(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SetDomainCertificateOutcomeCallable CloudAPIClient::setDomainCertificateCallable(const SetDomainCertificateRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetDomainCertificateOutcome()>>(
[this, request]()
{
return this->setDomainCertificate(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SetDomainWebSocketStatusOutcome CloudAPIClient::setDomainWebSocketStatus(const SetDomainWebSocketStatusRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetDomainWebSocketStatusOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetDomainWebSocketStatusOutcome(SetDomainWebSocketStatusResult(outcome.result()));
else
return SetDomainWebSocketStatusOutcome(outcome.error());
}
void CloudAPIClient::setDomainWebSocketStatusAsync(const SetDomainWebSocketStatusRequest& request, const SetDomainWebSocketStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setDomainWebSocketStatus(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SetDomainWebSocketStatusOutcomeCallable CloudAPIClient::setDomainWebSocketStatusCallable(const SetDomainWebSocketStatusRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetDomainWebSocketStatusOutcome()>>(
[this, request]()
{
return this->setDomainWebSocketStatus(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SetIpControlApisOutcome CloudAPIClient::setIpControlApis(const SetIpControlApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetIpControlApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetIpControlApisOutcome(SetIpControlApisResult(outcome.result()));
else
return SetIpControlApisOutcome(outcome.error());
}
void CloudAPIClient::setIpControlApisAsync(const SetIpControlApisRequest& request, const SetIpControlApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setIpControlApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SetIpControlApisOutcomeCallable CloudAPIClient::setIpControlApisCallable(const SetIpControlApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetIpControlApisOutcome()>>(
[this, request]()
{
return this->setIpControlApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SetSignatureApisOutcome CloudAPIClient::setSignatureApis(const SetSignatureApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetSignatureApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetSignatureApisOutcome(SetSignatureApisResult(outcome.result()));
else
return SetSignatureApisOutcome(outcome.error());
}
void CloudAPIClient::setSignatureApisAsync(const SetSignatureApisRequest& request, const SetSignatureApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setSignatureApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SetSignatureApisOutcomeCallable CloudAPIClient::setSignatureApisCallable(const SetSignatureApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetSignatureApisOutcome()>>(
[this, request]()
{
return this->setSignatureApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SetTrafficControlApisOutcome CloudAPIClient::setTrafficControlApis(const SetTrafficControlApisRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetTrafficControlApisOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetTrafficControlApisOutcome(SetTrafficControlApisResult(outcome.result()));
else
return SetTrafficControlApisOutcome(outcome.error());
}
void CloudAPIClient::setTrafficControlApisAsync(const SetTrafficControlApisRequest& request, const SetTrafficControlApisAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setTrafficControlApis(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SetTrafficControlApisOutcomeCallable CloudAPIClient::setTrafficControlApisCallable(const SetTrafficControlApisRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetTrafficControlApisOutcome()>>(
[this, request]()
{
return this->setTrafficControlApis(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SetVpcAccessOutcome CloudAPIClient::setVpcAccess(const SetVpcAccessRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetVpcAccessOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetVpcAccessOutcome(SetVpcAccessResult(outcome.result()));
else
return SetVpcAccessOutcome(outcome.error());
}
void CloudAPIClient::setVpcAccessAsync(const SetVpcAccessRequest& request, const SetVpcAccessAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setVpcAccess(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SetVpcAccessOutcomeCallable CloudAPIClient::setVpcAccessCallable(const SetVpcAccessRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetVpcAccessOutcome()>>(
[this, request]()
{
return this->setVpcAccess(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SetWildcardDomainPatternsOutcome CloudAPIClient::setWildcardDomainPatterns(const SetWildcardDomainPatternsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetWildcardDomainPatternsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetWildcardDomainPatternsOutcome(SetWildcardDomainPatternsResult(outcome.result()));
else
return SetWildcardDomainPatternsOutcome(outcome.error());
}
void CloudAPIClient::setWildcardDomainPatternsAsync(const SetWildcardDomainPatternsRequest& request, const SetWildcardDomainPatternsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setWildcardDomainPatterns(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SetWildcardDomainPatternsOutcomeCallable CloudAPIClient::setWildcardDomainPatternsCallable(const SetWildcardDomainPatternsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetWildcardDomainPatternsOutcome()>>(
[this, request]()
{
return this->setWildcardDomainPatterns(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::SwitchApiOutcome CloudAPIClient::switchApi(const SwitchApiRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SwitchApiOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SwitchApiOutcome(SwitchApiResult(outcome.result()));
else
return SwitchApiOutcome(outcome.error());
}
void CloudAPIClient::switchApiAsync(const SwitchApiRequest& request, const SwitchApiAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, switchApi(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::SwitchApiOutcomeCallable CloudAPIClient::switchApiCallable(const SwitchApiRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SwitchApiOutcome()>>(
[this, request]()
{
return this->switchApi(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::TagResourcesOutcome CloudAPIClient::tagResources(const TagResourcesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return TagResourcesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return TagResourcesOutcome(TagResourcesResult(outcome.result()));
else
return TagResourcesOutcome(outcome.error());
}
void CloudAPIClient::tagResourcesAsync(const TagResourcesRequest& request, const TagResourcesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, tagResources(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::TagResourcesOutcomeCallable CloudAPIClient::tagResourcesCallable(const TagResourcesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<TagResourcesOutcome()>>(
[this, request]()
{
return this->tagResources(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CloudAPIClient::UntagResourcesOutcome CloudAPIClient::untagResources(const UntagResourcesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return UntagResourcesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return UntagResourcesOutcome(UntagResourcesResult(outcome.result()));
else
return UntagResourcesOutcome(outcome.error());
}
void CloudAPIClient::untagResourcesAsync(const UntagResourcesRequest& request, const UntagResourcesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, untagResources(request), context);
};
asyncExecute(new Runnable(fn));
}
CloudAPIClient::UntagResourcesOutcomeCallable CloudAPIClient::untagResourcesCallable(const UntagResourcesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<UntagResourcesOutcome()>>(
[this, request]()
{
return this->untagResources(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
| 35.165913 | 233 | 0.786282 | [
"model"
] |
9166b4675e5434b40c3358501927118a98640eeb | 852 | cpp | C++ | CPP/CombinationSum2.cpp | ceccs17d55/open-source-contribution | 63d95a990cdcc1e31c5fca3cb61f2fa34dae9e1f | [
"MIT"
] | 2 | 2021-10-04T16:33:30.000Z | 2021-10-04T17:21:59.000Z | CPP/CombinationSum2.cpp | ceccs17d55/open-source-contribution | 63d95a990cdcc1e31c5fca3cb61f2fa34dae9e1f | [
"MIT"
] | 1 | 2021-10-03T19:52:07.000Z | 2021-10-03T19:52:07.000Z | CPP/CombinationSum2.cpp | ceccs17d55/open-source-contribution | 63d95a990cdcc1e31c5fca3cb61f2fa34dae9e1f | [
"MIT"
] | 1 | 2021-10-18T20:49:51.000Z | 2021-10-18T20:49:51.000Z | class Solution
{
public:
void findCombination(int ind, int target, vector<int> &arr, vector<vector<int>> &ans, vector<int> &ds)
{
if (target == 0)
{
ans.push_back(ds);
return;
}
for (int i = ind; i < arr.size(); i++)
{
if (i > ind && arr[i] == arr[i - 1])
continue;
if (arr[i] > target)
break;
ds.push_back(arr[i]);
findCombination(i + 1, target - arr[i], arr, ans, ds);
ds.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int> &candidates, int target)
{
sort(candidates.begin(), candidates.end());
vector<vector<int>> ans;
vector<int> ds;
findCombination(0, target, candidates, ans, ds);
return ans;
}
}; | 26.625 | 106 | 0.484742 | [
"vector"
] |
916e795070a221cc1a61379d9a05fae3631ea1d5 | 3,552 | cpp | C++ | modcc/io/prefixbuf.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 53 | 2018-10-18T12:08:21.000Z | 2022-03-26T22:03:51.000Z | modcc/io/prefixbuf.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 864 | 2018-10-01T08:06:00.000Z | 2022-03-31T08:06:48.000Z | modcc/io/prefixbuf.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 37 | 2019-03-03T16:18:49.000Z | 2022-03-24T10:39:51.000Z | #include <iostream>
#include <stack>
#include <string>
#include <vector>
#include "io/prefixbuf.hpp"
namespace io {
// prefixbuf implementation:
std::streamsize prefixbuf::xsputn(const char_type* s, std::streamsize count) {
std::streamsize written = 0;
while (count>0) {
if (bol_) {
if (prefix_empty_lines_ || s[0]!='\n') {
inner_->sputn(&prefix[0], prefix.size());
}
bol_ = false;
}
std::streamsize i = 0;
while (i<count && s[i]!='\n') {
++i;
}
if (i<count) { // encountered '\n'
++i;
bol_ = true;
}
std::streamsize n = inner_->sputn(s, i);
written += n;
if (n<i) {
break;
}
s += i;
count -= i;
}
return written;
}
prefixbuf::int_type prefixbuf::overflow(int_type ch) {
static int_type eof = traits_type::eof();
if (ch!=eof) {
char_type c = (char_type)ch;
return xsputn(&c, 1)? 0: eof;
}
return eof;
}
// setprefix implementation:
std::ostream& operator<<(std::ostream& os, const setprefix& sp) {
if (auto pbuf = dynamic_cast<prefixbuf*>(os.rdbuf())) {
pbuf->prefix = sp.prefix_;
}
return os;
}
// indent_manip implementation:
using indent_stack = std::stack<unsigned, std::vector<unsigned>>;
int indent_manip::xindex() {
static int i = std::ios_base::xalloc();
return i;
}
static void apply_indent_prefix(std::ios& s, int index) {
if (auto pbuf = dynamic_cast<prefixbuf*>(s.rdbuf())) {
indent_stack* stack_ptr = static_cast<indent_stack*>(s.pword(index));
unsigned tabwidth = s.iword(index);
unsigned tabs = (!stack_ptr || stack_ptr->empty())? 0: stack_ptr->top();
pbuf->prefix = std::string(tabs*tabwidth, ' ');
}
}
static void indent_stack_callback(std::ios_base::event ev, std::ios_base& ios, int index) {
void*& pword = ios.pword(index);
switch (ev) {
case std::ios_base::erase_event:
if (pword) {
indent_stack* stack_ptr = static_cast<indent_stack*>(pword);
delete stack_ptr;
pword = nullptr;
}
break;
case std::ios_base::copyfmt_event:
if (pword) {
// Clone stack:
indent_stack* stack_ptr = static_cast<indent_stack*>(pword);
pword = new indent_stack(*stack_ptr);
// Set prefix if streambuf is a prefixbuf:
if (auto stream_ptr = dynamic_cast<std::ios*>(&ios)) {
apply_indent_prefix(*stream_ptr, index);
}
}
break;
default:
;
}
}
std::ostream& operator<<(std::ostream& os, indent_manip in) {
int xindex = indent_manip::xindex();
void*& pword = os.pword(xindex);
long& iword = os.iword(xindex);
if (!pword) {
os.register_callback(&indent_stack_callback, xindex);
pword = new indent_stack();
iword = static_cast<long>(indent_manip::default_tabwidth);
}
indent_stack& stack = *static_cast<indent_stack*>(pword);
switch (in.action_) {
case indent_manip::pop:
while (!stack.empty() && in.value_--) {
stack.pop();
}
break;
case indent_manip::push:
stack.push(stack.empty()? in.value_: in.value_+stack.top());
break;
case indent_manip::settab:
iword = static_cast<long>(in.value_);
break;
}
apply_indent_prefix(os, xindex);
return os;
}
} // namespace io
| 24.496552 | 91 | 0.563626 | [
"vector"
] |
91708843b1caf723942971ee0d0ed45bcc4e4c09 | 3,113 | cpp | C++ | src/button.cpp | nek0bit/LoopCube | 882296f32bfe3a8b1765950a9b8c9e24af75d009 | [
"MIT"
] | 9 | 2020-04-03T21:20:02.000Z | 2021-08-23T19:57:57.000Z | src/button.cpp | nek0bit/LoopCube | 882296f32bfe3a8b1765950a9b8c9e24af75d009 | [
"MIT"
] | 2 | 2020-12-05T01:05:58.000Z | 2021-01-23T04:41:24.000Z | src/button.cpp | nek0bit/LoopCube | 882296f32bfe3a8b1765950a9b8c9e24af75d009 | [
"MIT"
] | 4 | 2020-07-04T13:47:33.000Z | 2021-09-11T15:29:08.000Z | #include "button.hpp"
// Size has fixed width
UI::Button::Button(const std::string& text,
const int sizeX,
const glm::ivec2& position,
const Margin& margin)
: GenericComponent(COMPONENT_BUTTON, position, {sizeX, 32}, margin),
model{UI::_ImmediateMode::_SHADER},
// TODO don't hardcode color!
textModel{UI::_ImmediateMode::_SHADER, text,
SDL_Color{255, 255, 255, 255},
UI::_ImmediateMode::_FONT}
{
fixed = FIXED_H;
generateButtonMesh();
}
UI::Button::~Button()
{}
void UI::Button::generateButtonMesh()
{
constexpr float BUTTON_BL_W = 32.0f;
const float BUTTON_MID_W = size.x - BUTTON_BL_W;
const float BUTTON_END_W = BUTTON_MID_W + BUTTON_BL_W;
std::vector<Vertex> mesh{};
const TextureInfo tInfo = constants::textureInfo[TEXTURE_UI_BUTTON];
const texcoord_info info = {
static_cast<unsigned>(tInfo.sizeX),
static_cast<unsigned>(tInfo.sizeY),
static_cast<unsigned>(tInfo.tilemapX),
static_cast<unsigned>(tInfo.tilemapY)
};
const texcoord_t tCoord[3] = {
Texture::getTilemapCoord(info, 0, 0),
Texture::getTilemapCoord(info, 1, 0),
Texture::getTilemapCoord(info, 2, 0)
};
// Begin vertices
Generic::Render::generateSquare(mesh, 0.0f, 0.0f, BUTTON_BL_W, size.y,
tCoord[0].begX, tCoord[0].begY, tCoord[0].endX, tCoord[0].endY);
// Don't bother drawing if too small
if (size.x > BUTTON_BL_W * 2)
{
// Middle vertices
Generic::Render::generateSquare(mesh, BUTTON_BL_W, 0.0f, BUTTON_MID_W, size.y,
tCoord[1].begX, tCoord[1].begY, tCoord[1].endX, tCoord[1].endY);
}
// End vertices
Generic::Render::generateSquare(mesh, BUTTON_MID_W, 0.0f, BUTTON_END_W, size.y,
tCoord[2].begX, tCoord[2].begY, tCoord[2].endX, tCoord[2].endY);
// Bind data
model.setBufferData(mesh);
updateButtonText();
}
void UI::Button::setText(const std::string& text)
{
textModel.setText(text);
}
void UI::Button::refreshContent()
{
generateButtonMesh();
}
void UI::Button::updateButtonText()
{
const uint16_t offsetX = size.x / 2 - (textModel.size.x / 2);
const uint16_t offsetY = size.y / 2 - (textModel.size.y / 2);
textModel.scale = glm::vec3(scale.x, scale.y, 0.0f);
textModel.position = glm::vec3(position.x + offsetX * scale.x,
position.y + offsetY * scale.y, 0.0f);
}
void UI::Button::update(const Camera& camera, const EventWrapper& events, Transform transform)
{
handleEvents(camera, events, transform);
}
void UI::Button::draw(const Graphics& graphics, Transform transform) const noexcept
{
graphics.textures.getTexture(TEXTURE_UI_BUTTON)->bind();
model.draw(graphics.uniforms.model, graphics.uniforms.tex,
glm::vec3(position.x, position.y, 0.0f) + transform.translate,
scale + transform.scale);
// Draw text
textModel.draw(graphics, transform);
}
| 30.821782 | 104 | 0.624157 | [
"mesh",
"render",
"vector",
"model",
"transform"
] |
917399b32a740ce6b43128ccf12d7f66d8d57816 | 1,138 | cpp | C++ | tests/gx-test-main.cpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 35 | 2018-01-07T02:34:38.000Z | 2022-02-09T05:19:03.000Z | tests/gx-test-main.cpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 111 | 2017-09-20T09:12:36.000Z | 2020-12-27T12:52:03.000Z | tests/gx-test-main.cpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 5 | 2020-02-11T11:17:37.000Z | 2021-01-08T17:55:43.000Z | #define BOOST_TEST_MODULE "Tests for Gearoenix game engine"
#include <boost/test/included/unit_test.hpp>
// Making types printable for boost
#include <gearoenix/math/gx-math-intersection-status.hpp>
#define GX_TEST_PRINT_TYPE_VAL(x) \
namespace boost::test_tools::tt_detail { \
template <> \
struct print_log_value<gearoenix::x> { \
void operator()(std::ostream& os, const gearoenix::x v) { ::operator<<(os, v); } \
}; \
}
GX_TEST_PRINT_TYPE_VAL(math::IntersectionStatus)
// Test units
#include "gx-test-ai-dijkstra.hpp"
#include "gx-test-ai-graph.hpp"
#include "gx-test-cr-allocator.hpp"
#include "gx-test-cr-pool.hpp"
#include "gx-test-cr-sync-influence-manager.hpp"
#include "gx-test-math-frustum.hpp"
#include "gx-test-math-vector.hpp"
#include "gx-test-phs-acc-bvh.hpp"
#include "gx-test-rnd-texture.hpp" | 49.478261 | 90 | 0.532513 | [
"vector"
] |
91763fc21bb296bc01bbba1bca39836fc60cd8d9 | 16,356 | cpp | C++ | sdktools/debuggers/oca/services/kdmon/kdmonsvc.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | sdktools/debuggers/oca/services/kdmon/kdmonsvc.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | sdktools/debuggers/oca/services/kdmon/kdmonsvc.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // kdMonSvc.cpp : Implementation of WinMain
// Note: Proxy/Stub Information
// To build a separate proxy/stub DLL,
// run nmake -f kdMonSvcps.mk in the project directory.
#include "stdafx.h"
#include "resource.h"
#include <initguid.h>
#include "kdMonSvc.h"
#include "kdMonSvc_i.c"
#include "global.h"
// The name of current service
// This variable is declared in global.cpp
extern _TCHAR szServiceName[MAX_PATH];
// just to get any kind of error through GetError() routine
// This variable is declared in global.cpp
extern _TCHAR szError[MAX_PATH];
CServiceModule _Module;
BEGIN_OBJECT_MAP(ObjectMap)
END_OBJECT_MAP()
// worker thread function
DWORD WINAPI WorkerThread( LPVOID lpParam );
LPCTSTR FindOneOf(LPCTSTR p1, LPCTSTR p2)
{
while (p1 != NULL && *p1 != NULL)
{
LPCTSTR p = p2;
while (p != NULL && *p != NULL)
{
if (*p1 == *p)
return CharNext(p1);
p = CharNext(p);
}
p1 = CharNext(p1);
}
return NULL;
}
// Although some of these functions are big they are declared inline since they are only used once
inline HRESULT CServiceModule::RegisterServer(BOOL bRegTypeLib, BOOL bService)
{
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr))
return hr;
// -- Added code to default --
// Setup event logging
//
LONG lResult;
lResult = SetupEventLog(TRUE);
if (lResult != ERROR_SUCCESS)
return lResult;
// -- Added code to default --
// if the service is already installed then dont do anything.
// RegisterServer(..) tries to Uninstall() a service before trying to
// Register it again. If you have already started a service, created a thread,
// and waiting for that thread to finish and you issue command
// kdMonSvc /service then RegisterServer() tries to call Uninstall().
// And you can not Uninstall() in this state since MainThread is waiting for
// WorkerThread to finish. So just return back from here
if(IsInstalled()){
MessageBox(NULL, _T("Service is already installed.\n Please unregister the service useing: kdMonSvc /unregserver"), NULL, MB_OK|MB_ICONEXCLAMATION);
return ERROR_SUCCESS;
}
// Remove any previous service since it may point to
// the incorrect file
Uninstall();
// Add service entries
UpdateRegistryFromResource(IDR_kdMonSvc, TRUE);
// Adjust the AppID for Local Server or Service
CRegKey keyAppID;
LONG lRes = keyAppID.Open(HKEY_CLASSES_ROOT, _T("AppID"), KEY_WRITE);
if (lRes != ERROR_SUCCESS)
return lRes;
CRegKey key;
lRes = key.Open(keyAppID, _T("{6961AED3-A5FA-46EE-862F-B50433EEF17E}"), KEY_WRITE);
if (lRes != ERROR_SUCCESS)
return lRes;
key.DeleteValue(_T("LocalService"));
if (bService)
{
key.SetValue(_T("kdMonSvc"), _T("LocalService"));
key.SetValue(_T("-Service"), _T("ServiceParameters"));
// Create service
Install();
}
// Add object entries
hr = CComModule::RegisterServer(bRegTypeLib);
CoUninitialize();
return hr;
}
inline HRESULT CServiceModule::UnregisterServer()
{
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr))
return hr;
//
// Remove eventlog stuff
//
SetupEventLog(FALSE);
// Remove service entries
UpdateRegistryFromResource(IDR_kdMonSvc, FALSE);
// Remove service
Uninstall();
// Remove object entries
CComModule::UnregisterServer(TRUE);
CoUninitialize();
return S_OK;
}
inline void CServiceModule::Init(_ATL_OBJMAP_ENTRY* p, HINSTANCE h, UINT nServiceNameID, const GUID* plibid)
{
CComModule::Init(p, h, plibid);
m_bService = TRUE;
LoadString(h, nServiceNameID, m_szServiceName, sizeof(m_szServiceName) / sizeof(_TCHAR));
// -- Added code to default --
// copy the service name into szServiceName, a global variable
_tcscpy(szServiceName, m_szServiceName);
// set up the initial service status
m_hServiceStatus = NULL;
m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
m_status.dwCurrentState = SERVICE_STOPPED;
m_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
m_status.dwWin32ExitCode = 0;
m_status.dwServiceSpecificExitCode = 0;
m_status.dwCheckPoint = 0;
m_status.dwWaitHint = 0;
}
LONG CServiceModule::Unlock()
{
LONG l = CComModule::Unlock();
if (l == 0 && !m_bService)
PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
return l;
}
BOOL CServiceModule::IsInstalled()
{
BOOL bResult = FALSE;
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM != NULL)
{
SC_HANDLE hService = ::OpenService(hSCM, m_szServiceName, SERVICE_QUERY_CONFIG);
if (hService != NULL)
{
bResult = TRUE;
::CloseServiceHandle(hService);
}
::CloseServiceHandle(hSCM);
}
return bResult;
}
inline BOOL CServiceModule::Install()
{
if (IsInstalled())
return TRUE;
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
{
MessageBox(NULL, _T("Couldn't open service manager"), m_szServiceName, MB_OK);
return FALSE;
}
// Get the executable file path
_TCHAR szFilePath[_MAX_PATH];
::GetModuleFileName(NULL, szFilePath, _MAX_PATH);
SC_HANDLE hService = ::CreateService(
hSCM, m_szServiceName, m_szServiceName,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
szFilePath, NULL, NULL, _T("RPCSS\0"), NULL, NULL);
if (hService == NULL)
{
::CloseServiceHandle(hSCM);
MessageBox(NULL, _T("Couldn't create service"), m_szServiceName, MB_OK);
return FALSE;
}
::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM);
return TRUE;
}
inline BOOL CServiceModule::Uninstall()
{
if (!IsInstalled())
return TRUE;
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
{
MessageBox(NULL, _T("Couldn't open service manager"), m_szServiceName, MB_OK);
return FALSE;
}
SC_HANDLE hService = ::OpenService(hSCM, m_szServiceName, SERVICE_STOP | DELETE);
if (hService == NULL)
{
::CloseServiceHandle(hSCM);
MessageBox(NULL, _T("Couldn't open service"), m_szServiceName, MB_OK);
return FALSE;
}
SERVICE_STATUS status;
::ControlService(hService, SERVICE_CONTROL_STOP, &status);
BOOL bDelete = ::DeleteService(hService);
::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM);
if (bDelete)
return TRUE;
MessageBox(NULL, _T("Service could not be deleted"), m_szServiceName, MB_OK);
return FALSE;
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Service startup and registration
inline void CServiceModule::Start()
{
SERVICE_TABLE_ENTRY st[] =
{
{ m_szServiceName, _ServiceMain },
{ NULL, NULL }
};
if (m_bService && !::StartServiceCtrlDispatcher(st))
{
m_bService = FALSE;
}
if (m_bService == FALSE)
Run();
}
inline void CServiceModule::ServiceMain(DWORD /* dwArgc */, LPTSTR* /* lpszArgv */)
{
// Register the control request handler
m_status.dwCurrentState = SERVICE_START_PENDING;
m_hServiceStatus = RegisterServiceCtrlHandler(m_szServiceName, _Handler);
if (m_hServiceStatus == NULL)
{
LogEvent(_T("Handler not installed"));
return;
}
SetServiceStatus(SERVICE_START_PENDING);
m_status.dwWin32ExitCode = S_OK;
m_status.dwCheckPoint = 0;
m_status.dwWaitHint = 0;
// When the Run function returns, the service has stopped.
Run();
SetServiceStatus(SERVICE_STOPPED);
LogEvent(_T("Service stopped"));
}
inline void CServiceModule::Handler(DWORD dwOpcode)
{
switch (dwOpcode)
{
case SERVICE_CONTROL_STOP:
SetServiceStatus(SERVICE_STOP_PENDING);
// post WM_QUIT message to current thread
// the GetMessage() loop will get this message and terminate the service
PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
break;
case SERVICE_CONTROL_PAUSE:
break;
case SERVICE_CONTROL_CONTINUE:
break;
case SERVICE_CONTROL_INTERROGATE:
break;
case SERVICE_CONTROL_SHUTDOWN:
break;
default:
LogEvent(_T("Bad service request"));
}
}
void WINAPI CServiceModule::_ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
{
_Module.ServiceMain(dwArgc, lpszArgv);
}
void WINAPI CServiceModule::_Handler(DWORD dwOpcode)
{
_Module.Handler(dwOpcode);
}
void CServiceModule::SetServiceStatus(DWORD dwState)
{
m_status.dwCurrentState = dwState;
::SetServiceStatus(m_hServiceStatus, &m_status);
}
void CServiceModule::Run()
{
_Module.dwThreadID = GetCurrentThreadId();
HRESULT hr = CoInitialize(NULL);
// If you are running on NT 4.0 or higher you can use the following call
// instead to make the EXE free threaded.
// This means that calls come in on a random RPC thread
// HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
_ASSERTE(SUCCEEDED(hr));
// This provides a NULL DACL which will allow access to everyone.
CSecurityDescriptor sd;
sd.InitializeFromThreadToken();
hr = CoInitializeSecurity(sd, -1, NULL, NULL,
RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
_ASSERTE(SUCCEEDED(hr));
hr = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER, REGCLS_MULTIPLEUSE);
_ASSERTE(SUCCEEDED(hr));
AddServiceLog(_T("kdMon service starting\r\n"));
if (m_bService)
SetServiceStatus(SERVICE_RUNNING);
// create a named event which the thread will open and refer to
// this event is used to signal "Stop" to WorkerThread
HANDLE hStopEvent = NULL;
hStopEvent = CreateEvent( NULL, // security attributes
FALSE, // = Automatic reset of event by system
FALSE,
(LPCTSTR)_T(cszStopEvent));
if ( hStopEvent == NULL ) {
GetError(szError);
LogFatalEvent(_T("Run->CreateEvent : %s"), szError);
AddServiceLog(_T("Error: Run->CreateEvent : %s\r\n"), szError);
goto done;
}
// -- Added code to default --
//
// Create worker thread here
//
LogEvent(_T("Creating worker thread"));
AddServiceLog(_T("Creating worker thread\r\n"));
DWORD dwWorkerThreadId;
HANDLE hWorkerThread;
hWorkerThread = CreateThread( NULL, // security descriptor
0, // initial stack size
WorkerThread, // thread start address
&dwThreadID, // thread arguments (current threadID)
0, // creation flags = run immediately
&dwWorkerThreadId);
if ( hWorkerThread == NULL ) {
GetError(szError);
LogFatalEvent(_T("Run->CreateThread : %s"), szError);
AddServiceLog(_T("Error: Run->CreateThread : %s\r\n"), szError);
goto done;
}
MSG msg;
BOOL bRetVal;
// GetMessage ():
// If the function retrieves a message other than WM_QUIT, the return value is nonzero.
// If the function retrieves the WM_QUIT message, the return value is zero.
while ( (bRetVal = GetMessage(&msg, NULL, 0, 0)) != 0 ) {
// send it to default dispatcher
DispatchMessage(&msg);
}
AddServiceLog(_T("Main thread received WM_QUIT message\r\n"));
AddServiceLog(_T("Terminating kdMon Service\r\n"));
LogEvent(_T("Terminating kdMon Service"));
// check if worker thread is still active.
// i.e. check hWorkerThread for a signalled state
DWORD dwRetVal;
AddServiceLog(_T("Main thread checking if WorkerThread is still active\r\n"));
dwRetVal = WaitForSingleObject( hWorkerThread, 0 );
if ( dwRetVal == WAIT_FAILED ) {
GetError(szError);
LogFatalEvent(_T("Run->WaitForSingleObject : %s"), szError);
AddServiceLog(_T("Error: Run->WaitForSingleObject : %s\r\n"), szError);
goto done;
}
// if hWorkerThread is not in signalled state then try to signal it
if ( dwRetVal != WAIT_OBJECT_0 ) {
// Signal the Stop Event, so that the worker thread stops
AddServiceLog(_T("Signalling Stop Event to Worker Thread\r\n"));
bRetVal = SetEvent(hStopEvent);
if ( bRetVal == 0 ) {
GetError(szError);
LogFatalEvent(_T("Run->SetEvent : %s"), szError);
AddServiceLog(_T("Error: Run->SetEvent : %s\r\n"), szError);
goto done;
}
// Now we have signalled the thread to end, wait till the thread ends gracefully
// We can use WaitForSingleObject API for this purpose
// CreateThread () : When a thread terminates, the thread object
// attains a signaled state, satisfying any threads that were waiting on the object.
// so we can make this main thread to wait for the WorkerThread to terminate
AddServiceLog(_T("Main thread waiting for WorkerThread to exit\r\n"));
dwRetVal = WaitForSingleObject( hWorkerThread, INFINITE );
if ( dwRetVal == WAIT_FAILED ) {
GetError(szError);
LogFatalEvent(_T("Run->WaitForSingleObject : %s"), szError);
AddServiceLog(_T("Error: Run->WaitForSingleObject : %s\r\n"), szError);
goto done;
}
}
done:
if ( hWorkerThread != NULL ) CloseHandle(hWorkerThread);
if ( hStopEvent != NULL ) CloseHandle(hStopEvent);
_Module.RevokeClassObjects();
CoUninitialize();
}
/////////////////////////////////////////////////////////////////////////////
//
extern "C" int WINAPI _tWinMain(HINSTANCE hInstance,
HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/)
{
lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT
_Module.Init(ObjectMap, hInstance, IDS_SERVICENAME, &LIBID_KDMONSVCLib);
_Module.m_bService = TRUE;
AddServiceLog(_T("Command received : %s\r\n"), lpCmdLine);
// tokenize on '-' or '/' characters
_TCHAR szTokens[] = _T("-/");
LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
while (lpszToken != NULL)
{
if (lstrcmpi(lpszToken, _T("UnregServer"))==0)
return _Module.UnregisterServer();
// Register as Local Server
if (lstrcmpi(lpszToken, _T("RegServer"))==0)
return _Module.RegisterServer(TRUE, FALSE);
// Register as Service
if (lstrcmpi(lpszToken, _T("Service"))==0)
return _Module.RegisterServer(TRUE, TRUE);
lpszToken = FindOneOf(lpszToken, szTokens);
}
// Are we Service or Local Server
CRegKey keyAppID;
LONG lRes = keyAppID.Open(HKEY_CLASSES_ROOT, _T("AppID"), KEY_READ);
if (lRes != ERROR_SUCCESS)
return lRes;
CRegKey key;
lRes = key.Open(keyAppID, _T("{6961AED3-A5FA-46EE-862F-B50433EEF17E}"), KEY_READ);
if (lRes != ERROR_SUCCESS)
return lRes;
_TCHAR szValue[_MAX_PATH];
DWORD dwLen = _MAX_PATH;
lRes = key.QueryValue(szValue, _T("LocalService"), &dwLen);
_Module.m_bService = FALSE;
if (lRes == ERROR_SUCCESS)
_Module.m_bService = TRUE;
_Module.Start();
// When we get here, the service has been stopped
return _Module.m_status.dwWin32ExitCode;
}
///////////////////////////////////////////////////////////////////////////////////////
// Worker thread. Main thread that does all the kdMon work
DWORD WINAPI WorkerThread(LPVOID lpParam)
{
// get the parent thread ID
// dwParentThreadID is the parent thread ID. This is used to signal
// main thread that worker thread is ending due to some reason
// and then main thread should also end and stop the service
DWORD dwParentThreadID = *(DWORD*) lpParam;
AddServiceLog(_T("Worker thread starting kdMon routine\r\n"));
// main kdMon method which is a while(1) loop.
kdMon();
LogEvent(_T("Worker Thread ending"));
AddServiceLog(_T("Worker Thread ending\r\n"));
// signal the parent thread with WM_QUIT before exiting
PostThreadMessage(dwParentThreadID, WM_QUIT, 0, 0);
return GetLastError();
} | 30.288889 | 151 | 0.645268 | [
"object"
] |
91794ed047d4bd9d2da0d98c8f6b8e30dc7c01ff | 360 | cpp | C++ | src/MatrixToVector.cpp | jjuniorc/marketdecision | 32bb632f51aaa9746aa19e18008de242466aad8c | [
"MIT"
] | null | null | null | src/MatrixToVector.cpp | jjuniorc/marketdecision | 32bb632f51aaa9746aa19e18008de242466aad8c | [
"MIT"
] | null | null | null | src/MatrixToVector.cpp | jjuniorc/marketdecision | 32bb632f51aaa9746aa19e18008de242466aad8c | [
"MIT"
] | null | null | null | #include "MarixToVector.h"
MatrixToVector::MatrixToVector(Matrix *a)
{
this->a = a;
}
vector<double> MatrixToVector::execute()
{
vector<double> result;
for(int r = 0; r < a->getNumRows(); r++)
{
for(int c = 0; c < a->getNumCols(); c++)
{
result.push_back(a->getValue(r, c));
}
}
return result;
}
| 16.363636 | 48 | 0.536111 | [
"vector"
] |
91797c5e695949b407504480d539fc8bdc338472 | 2,920 | hpp | C++ | lib/libflatarray/include/libflatarray/testbed/cpu_benchmark.hpp | Teslos/libgeodecomp | 3776c65965a02b02e986989b45a0d1d9b29ecf2d | [
"BSL-1.0"
] | null | null | null | lib/libflatarray/include/libflatarray/testbed/cpu_benchmark.hpp | Teslos/libgeodecomp | 3776c65965a02b02e986989b45a0d1d9b29ecf2d | [
"BSL-1.0"
] | null | null | null | lib/libflatarray/include/libflatarray/testbed/cpu_benchmark.hpp | Teslos/libgeodecomp | 3776c65965a02b02e986989b45a0d1d9b29ecf2d | [
"BSL-1.0"
] | 1 | 2019-12-17T03:00:58.000Z | 2019-12-17T03:00:58.000Z | /**
* Copyright 2014-2017 Andreas Schäfer
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef FLAT_ARRAY_TESTBED_CPU_BENCHMARK_HPP
#define FLAT_ARRAY_TESTBED_CPU_BENCHMARK_HPP
#include <libflatarray/testbed/benchmark.hpp>
// disable certain warnings from system headers when compiling with
// Microsoft Visual Studio:
#ifdef _MSC_BUILD
#pragma warning( push )
#pragma warning( disable : 4514 )
#endif
#include <fstream>
#include <iostream>
#ifdef _MSC_BUILD
#pragma warning( pop )
#endif
namespace LibFlatArray {
class cpu_benchmark : public benchmark
{
public:
std::string order()
{
return "CPU";
}
std::string device()
{
std::ifstream file("/proc/cpuinfo");
const std::size_t bufferSize = 1 << 12;
char buffer[bufferSize];
while (file.getline(&buffer[0], bufferSize)) {
std::vector<std::string> tokens = tokenize(buffer, ':');
std::vector<std::string> fields = tokenize(tokens[0], '\t');
if ((fields.size() == 1) && (fields[0] == "cpu")) {
return tokens[1];
}
if ((fields.size() == 1) && (fields[0] == "model name")) {
tokens = tokenize(tokens[1], ' ');
std::string buf = join(tokens, " ");
if (buf[buf.size() - 1] == 0) {
buf.resize(buf.size() - 1);
}
return buf;
}
}
throw std::runtime_error("could not parse /proc/cpuinfo");
}
private:
static std::string trim(const std::string& string)
{
if (string.size() == 0) {
return string;
}
std::size_t start = 0;
while ((string[start] == ' ') && (start < string.size())) {
start += 1;
}
std::size_t end = string.size() - 1;
while ((string[end] == ' ') && (end > 1)) {
end -= 1;
}
if ((string[end] != ' ') && (end < string.size())) {
end += 1;
}
return std::string(string, start, end - start);
}
static std::vector<std::string> tokenize(const std::string& line, char delimiter = ';')
{
std::vector<std::string> ret;
std::stringstream buf(line);
std::string item;
while (std::getline(buf, item, delimiter)) {
ret.push_back(trim(item));
}
return ret;
}
static std::string join(const std::vector<std::string>& tokens, const std::string& delimiter)
{
std::stringstream buf;
for (std::vector<std::string>::const_iterator i = tokens.begin(); i != tokens.end(); ++i) {
if (i != tokens.begin()) {
buf << delimiter;
}
buf << *i;
}
return buf.str();
}
};
}
#endif
| 24.132231 | 99 | 0.52911 | [
"vector",
"model"
] |
917ba3445ce5d5c0b2bf80d43ccbe8b394372946 | 40,142 | cpp | C++ | dev/Code/CryEngine/Cry3DEngine/VisAreas.cpp | CJoriginal/cjlumberyard | 2e3184a7d8e59ba05e5707371b8cb6fe40b0ca60 | [
"AML"
] | 8 | 2019-10-07T16:33:47.000Z | 2020-12-07T03:59:58.000Z | dev/Code/CryEngine/Cry3DEngine/VisAreas.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/CryEngine/Cry3DEngine/VisAreas.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Visibility areas
#include "StdAfx.h"
#include "StatObj.h"
#include "ObjMan.h"
#include "VisAreas.h"
#include "terrain_sector.h"
#include "3dEngine.h"
#include "TimeOfDay.h"
PodArray<CVisArea*> CVisArea::m_lUnavailableAreas;
PodArray<Vec3> CVisArea::s_tmpLstPortVertsClipped;
PodArray<Vec3> CVisArea::s_tmpLstPortVertsSS;
PodArray<Vec3> CVisArea::s_tmpPolygonA;
PodArray<IRenderNode*> CVisArea::s_tmpLstLights;
PodArray<CTerrainNode*> CVisArea::s_tmpLstTerrainNodeResult;
CPolygonClipContext CVisArea::s_tmpClipContext;
PodArray<CCamera> CVisArea::s_tmpCameras;
int CVisArea::s_nGetDistanceThruVisAreasCallCounter = 0;
void CVisArea::Update(const Vec3* pPoints, int nCount, const char* szName, const SVisAreaInfo& info)
{
assert(m_pVisAreaColdData);
cry_strcpy(m_pVisAreaColdData->m_sName, szName);
_strlwr_s(m_pVisAreaColdData->m_sName, sizeof(m_pVisAreaColdData->m_sName));
m_bThisIsPortal = strstr(m_pVisAreaColdData->m_sName, "portal") != 0;
m_bIgnoreSky = (strstr(m_pVisAreaColdData->m_sName, "ignoresky") != 0) || info.bIgnoreSkyColor;
m_fHeight = info.fHeight;
m_vAmbientColor = info.vAmbientColor;
m_bAffectedByOutLights = info.bAffectedByOutLights;
m_bSkyOnly = info.bSkyOnly;
m_fViewDistRatio = info.fViewDistRatio;
m_bDoubleSide = info.bDoubleSide;
m_bUseDeepness = info.bUseDeepness;
m_bUseInIndoors = info.bUseInIndoors;
m_bOceanVisible = info.bOceanIsVisible;
m_bIgnoreGI = info.bIgnoreGI;
m_bIgnoreOutdoorAO = info.bIgnoreOutdoorAO;
m_fPortalBlending = info.fPortalBlending;
m_lstShapePoints.PreAllocate(nCount, nCount);
if (nCount)
{
memcpy(&m_lstShapePoints[0], pPoints, sizeof(Vec3) * nCount);
}
// update bbox
m_boxArea.max = SetMinBB();
m_boxArea.min = SetMaxBB();
for (int i = 0; i < nCount; i++)
{
m_boxArea.max.CheckMax(pPoints[i]);
m_boxArea.min.CheckMin(pPoints[i]);
m_boxArea.max.CheckMax(pPoints[i] + Vec3(0, 0, m_fHeight));
m_boxArea.min.CheckMin(pPoints[i] + Vec3(0, 0, m_fHeight));
}
UpdateGeometryBBox();
UpdateClipVolume();
}
void CVisArea::StaticReset()
{
stl::free_container(m_lUnavailableAreas);
stl::free_container(s_tmpLstPortVertsClipped);
stl::free_container(s_tmpLstPortVertsSS);
stl::free_container(s_tmpPolygonA);
stl::free_container(s_tmpLstLights);
stl::free_container(s_tmpLstTerrainNodeResult);
stl::free_container(s_tmpCameras);
s_tmpClipContext.Reset();
}
void CVisArea::Init()
{
m_fGetDistanceThruVisAreasMinDistance = 10000.f;
m_nGetDistanceThruVisAreasLastCallID = -1;
m_pVisAreaColdData = NULL;
m_boxStatics.min = m_boxStatics.max = m_boxArea.min = m_boxArea.max = Vec3(0, 0, 0);
m_nRndFrameId = -1;
m_bActive = true;
m_fHeight = 0;
m_vAmbientColor(0, 0, 0);
m_vConnNormals[0] = m_vConnNormals[1] = Vec3(0, 0, 0);
m_bAffectedByOutLights = false;
m_fDistance = 0;
m_bOceanVisible = m_bSkyOnly = false;
memset(m_arrOcclCamera, 0, sizeof(m_arrOcclCamera));
m_fViewDistRatio = 100.f;
m_bDoubleSide = true;
m_bUseDeepness = false;
m_bUseInIndoors = false;
m_bIgnoreSky = m_bThisIsPortal = false;
m_bIgnoreGI = false;
m_bIgnoreOutdoorAO = false;
m_lstCurCamerasCap = 0;
m_lstCurCamerasLen = 0;
m_lstCurCamerasIdx = 0;
m_nVisGUID = 0;
m_fPortalBlending = 0.5f;
m_nStencilRef = 0;
}
CVisArea::CVisArea()
{
Init();
}
CVisArea::CVisArea(VisAreaGUID visGUID)
{
Init();
m_nVisGUID = visGUID;
}
CVisArea::~CVisArea()
{
for (int i = 0; i < MAX_RECURSION_LEVELS; i++)
{
SAFE_DELETE(m_arrOcclCamera[i]);
}
GetVisAreaManager()->OnVisAreaDeleted(this);
if (m_pVisAreaColdData->m_dataType == eCDT_Portal)
{
SPortalColdData* pPortalColdData = static_cast<SPortalColdData*>(m_pVisAreaColdData);
if (pPortalColdData->m_pRNTmpData)
{
Get3DEngine()->FreeRNTmpData(&pPortalColdData->m_pRNTmpData);
}
}
}
float LineSegDistanceSqr(const Vec3& vPos, const Vec3& vP0, const Vec3& vP1)
{
// Dist of line seg A(+D) from origin:
// P = A + D t[0..1]
// d^2(t) = (A + D t)^2 = A^2 + 2 A*D t + D^2 t^2
// d^2\t = 2 A*D + 2 D^2 t = 0
// tmin = -A*D / D^2 clamp_tpl(0,1)
// Pmin = A + D tmin
Vec3 vP = vP0 - vPos;
Vec3 vD = vP1 - vP0;
float fN = -(vP * vD);
if (fN > 0.f)
{
float fD = vD.GetLengthSquared();
if (fN >= fD)
{
vP += vD;
}
else
{
vP += vD * (fN / fD);
}
}
return vP.GetLengthSquared();
}
void CVisArea::FindSurroundingVisAreaReqursive(int nMaxReqursion, bool bSkipDisabledPortals, PodArray<IVisArea*>* pVisitedAreas, int nMaxVisitedAreas, int nDeepness, PodArray<CVisArea*>* pUnavailableAreas)
{
pUnavailableAreas->Add(this);
if (pVisitedAreas && pVisitedAreas->Count() < nMaxVisitedAreas)
{
pVisitedAreas->Add(this);
}
if (nMaxReqursion > (nDeepness + 1))
{
for (int p = 0; p < m_lstConnections.Count(); p++)
{
if (!bSkipDisabledPortals || m_lstConnections[p]->IsActive())
{
if (-1 == pUnavailableAreas->Find(m_lstConnections[p]))
{
m_lstConnections[p]->FindSurroundingVisAreaReqursive(nMaxReqursion, bSkipDisabledPortals, pVisitedAreas, nMaxVisitedAreas, nDeepness + 1, pUnavailableAreas);
}
}
}
}
}
void CVisArea::FindSurroundingVisArea(int nMaxReqursion, bool bSkipDisabledPortals, PodArray<IVisArea*>* pVisitedAreas, int nMaxVisitedAreas, int nDeepness)
{
if (pVisitedAreas)
{
if (pVisitedAreas->capacity() < (uint32)nMaxVisitedAreas)
{
pVisitedAreas->PreAllocate(nMaxVisitedAreas);
}
}
m_lUnavailableAreas.Clear();
m_lUnavailableAreas.PreAllocate(nMaxVisitedAreas, 0);
FindSurroundingVisAreaReqursive(nMaxReqursion, bSkipDisabledPortals, pVisitedAreas, nMaxVisitedAreas, nDeepness, &m_lUnavailableAreas);
}
int CVisArea::GetVisFrameId()
{
return m_nRndFrameId;
}
bool Is2dLinesIntersect(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4)
{
float fDiv = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
if (fabs(fDiv) < 0.00001f)
{
return false;
}
float ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / fDiv;
float ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / fDiv;
return ua > 0 && ua < 1 && ub > 0 && ub < 1;
}
Vec3 CVisArea::GetConnectionNormal(CVisArea* pPortal)
{
assert(m_lstShapePoints.Count() >= 3);
// find side of shape intersecting with portal
int nIntersNum = 0;
Vec3 arrNormals[2] = {Vec3(0, 0, 0), Vec3(0, 0, 0)};
for (int v = 0; v < m_lstShapePoints.Count(); v++)
{
nIntersNum = 0;
arrNormals[0] = Vec3(0, 0, 0);
arrNormals[1] = Vec3(0, 0, 0);
const Vec3& v0 = m_lstShapePoints[v];
const Vec3& v1 = m_lstShapePoints[(v + 1) % m_lstShapePoints.Count()];
for (int p = 0; p < pPortal->m_lstShapePoints.Count(); p++)
{
const Vec3& p0 = pPortal->m_lstShapePoints[p];
const Vec3& p1 = pPortal->m_lstShapePoints[(p + 1) % pPortal->m_lstShapePoints.Count()];
if (Is2dLinesIntersect(v0.x, v0.y, v1.x, v1.y, p0.x, p0.y, p1.x, p1.y))
{
Vec3 vNormal = (v0 - v1).GetNormalized().Cross(Vec3(0, 0, 1.f));
if (nIntersNum < 2)
{
arrNormals[nIntersNum++] = (IsShapeClockwise()) ? -vNormal : vNormal;
}
}
}
if (nIntersNum == 2)
{
break;
}
}
if (nIntersNum == 2 &&
//IsEquivalent(arrNormals[0] == arrNormals[1])
arrNormals[0].IsEquivalent(arrNormals[1], VEC_EPSILON)
)
{
return arrNormals[0];
}
{
int nBottomPoints = 0;
for (int p = 0; p < pPortal->m_lstShapePoints.Count() && p < 4; p++)
{
if (IsPointInsideVisArea(pPortal->m_lstShapePoints[p]))
{
nBottomPoints++;
}
}
int nUpPoints = 0;
for (int p = 0; p < pPortal->m_lstShapePoints.Count() && p < 4; p++)
{
if (IsPointInsideVisArea(pPortal->m_lstShapePoints[p] + Vec3(0, 0, pPortal->m_fHeight)))
{
nUpPoints++;
}
}
if (nBottomPoints == 0 && nUpPoints == 4)
{
return Vec3(0, 0, 1);
}
if (nBottomPoints == 4 && nUpPoints == 0)
{
return Vec3(0, 0, -1);
}
}
return Vec3(0, 0, 0);
}
void CVisArea::UpdatePortalCameraPlanes(CCamera& cam, Vec3* pVerts, bool NotForcePlaneSet, const SRenderingPassInfo& passInfo)
{
const Vec3& vCamPos = passInfo.GetCamera().GetPosition();
Plane plane, farPlane;
farPlane = *passInfo.GetCamera().GetFrustumPlane(FR_PLANE_FAR);
cam.SetFrustumPlane(FR_PLANE_FAR, farPlane);
//plane.SetPlane(pVerts[0],pVerts[2],pVerts[1]); // can potentially create a plane facing the wrong way
plane.SetPlane(-farPlane.n, pVerts[0]);
cam.SetFrustumPlane(FR_PLANE_NEAR, plane);
plane.SetPlane(vCamPos, pVerts[3], pVerts[2]); // update plane only if it reduces fov
if (!NotForcePlaneSet || plane.n.Dot(cam.GetFrustumPlane(FR_PLANE_LEFT)->n) <
cam.GetFrustumPlane(FR_PLANE_RIGHT)->n.Dot(cam.GetFrustumPlane(FR_PLANE_LEFT)->n))
{
cam.SetFrustumPlane(FR_PLANE_RIGHT, plane);
}
plane.SetPlane(vCamPos, pVerts[1], pVerts[0]); // update plane only if it reduces fov
if (!NotForcePlaneSet || plane.n.Dot(cam.GetFrustumPlane(FR_PLANE_RIGHT)->n) <
cam.GetFrustumPlane(FR_PLANE_LEFT)->n.Dot(cam.GetFrustumPlane(FR_PLANE_RIGHT)->n))
{
cam.SetFrustumPlane(FR_PLANE_LEFT, plane);
}
plane.SetPlane(vCamPos, pVerts[0], pVerts[3]); // update plane only if it reduces fov
if (!NotForcePlaneSet || plane.n.Dot(cam.GetFrustumPlane(FR_PLANE_TOP)->n) <
cam.GetFrustumPlane(FR_PLANE_BOTTOM)->n.Dot(cam.GetFrustumPlane(FR_PLANE_TOP)->n))
{
cam.SetFrustumPlane(FR_PLANE_BOTTOM, plane);
}
plane.SetPlane(vCamPos, pVerts[2], pVerts[1]); // update plane only if it reduces fov
if (!NotForcePlaneSet || plane.n.Dot(cam.GetFrustumPlane(FR_PLANE_BOTTOM)->n) <
cam.GetFrustumPlane(FR_PLANE_TOP)->n.Dot(cam.GetFrustumPlane(FR_PLANE_BOTTOM)->n))
{
cam.SetFrustumPlane(FR_PLANE_TOP, plane);
}
Vec3 arrvPortVertsCamSpace[4];
for (int i = 0; i < 4; i++)
{
arrvPortVertsCamSpace[i] = pVerts[i] - cam.GetPosition();
}
cam.SetFrustumVertices(arrvPortVertsCamSpace);
//cam.UpdateFrustum();
if (GetCVars()->e_Portals == 5)
{
float farrColor[4] = {1, 1, 1, 1};
// GetRenderer()->SetMaterialColor(1,1,1,1);
DrawLine(pVerts[0], pVerts[1]);
GetRenderer()->DrawLabelEx(pVerts[0], 1, farrColor, false, true, "0");
DrawLine(pVerts[1], pVerts[2]);
GetRenderer()->DrawLabelEx(pVerts[1], 1, farrColor, false, true, "1");
DrawLine(pVerts[2], pVerts[3]);
GetRenderer()->DrawLabelEx(pVerts[2], 1, farrColor, false, true, "2");
DrawLine(pVerts[3], pVerts[0]);
GetRenderer()->DrawLabelEx(pVerts[3], 1, farrColor, false, true, "3");
}
}
int __cdecl CVisAreaManager__CmpDistToPortal(const void* v1, const void* v2);
void CVisArea::PreRender(int nReqursionLevel,
CCamera CurCamera, CVisArea* pParent, CVisArea* pCurPortal,
bool* pbOutdoorVisible, PodArray<CCamera>* plstOutPortCameras, bool* pbSkyVisible, bool* pbOceanVisible,
PodArray<CVisArea*>& lstVisibleAreas,
const SRenderingPassInfo& passInfo)
{
// mark as rendered
if (m_nRndFrameId != passInfo.GetFrameID())
{
m_lstCurCamerasIdx = 0;
m_lstCurCamerasLen = 0;
if (m_lstCurCamerasCap)
{
m_lstCurCamerasIdx = s_tmpCameras.size();
s_tmpCameras.resize(s_tmpCameras.size() + m_lstCurCamerasCap);
}
}
m_nRndFrameId = passInfo.GetFrameID();
if (m_bAffectedByOutLights)
{
GetVisAreaManager()->m_bSunIsNeeded = true;
}
if (m_lstCurCamerasLen == m_lstCurCamerasCap)
{
int newIdx = s_tmpCameras.size();
m_lstCurCamerasCap += max(1, m_lstCurCamerasCap / 2);
s_tmpCameras.resize(newIdx + m_lstCurCamerasCap);
if (m_lstCurCamerasLen)
{
memcpy(&s_tmpCameras[newIdx], &s_tmpCameras[m_lstCurCamerasIdx], m_lstCurCamerasLen * sizeof(CCamera));
}
m_lstCurCamerasIdx = newIdx;
}
s_tmpCameras[m_lstCurCamerasIdx + m_lstCurCamerasLen] = CurCamera;
++m_lstCurCamerasLen;
if (lstVisibleAreas.Find(this) < 0)
{
lstVisibleAreas.Add(this);
m_nStencilRef = GetRenderer()->EF_AddDeferredClipVolume(this);
}
// check recursion and portal activity
if (!nReqursionLevel || !m_bActive)
{
return;
}
if (pParent && m_bThisIsPortal && m_lstConnections.Count() == 1 && // detect entrance
!IsPointInsideVisArea(passInfo.GetCamera().GetPosition())) // detect camera in outdoors
{
AABB boxAreaEx = m_boxArea;
float fZNear = CurCamera.GetNearPlane();
boxAreaEx.min -= Vec3(fZNear, fZNear, fZNear);
boxAreaEx.max += Vec3(fZNear, fZNear, fZNear);
if (!CurCamera.IsAABBVisible_E(boxAreaEx)) // if portal is invisible
{
return; // stop recursion
}
}
bool bCanSeeThruThisArea = true;
// prepare new camera for next areas
if (m_bThisIsPortal && m_lstConnections.Count() &&
(this != pCurPortal || !pCurPortal->IsPointInsideVisArea(CurCamera.GetPosition())))
{
Vec3 vCenter = m_boxArea.GetCenter();
float fRadius = m_boxArea.GetRadius();
Vec3 vPortNorm = (!pParent || pParent == m_lstConnections[0] || m_lstConnections.Count() == 1) ?
m_vConnNormals[0] : m_vConnNormals[1];
// exit/entrance portal has only one normal in direction to outdoors, so flip it to the camera
if (m_lstConnections.Count() == 1 && !pParent)
{
vPortNorm = -vPortNorm;
}
// back face check
Vec3 vPortToCamDir = CurCamera.GetPosition() - vCenter;
if (vPortToCamDir.Dot(vPortNorm) < 0)
{
return;
}
if (!m_bDoubleSide)
{
if (vPortToCamDir.Dot(m_vConnNormals[0]) < 0)
{
return;
}
}
Vec3 arrPortVerts[4];
Vec3 arrPortVertsOtherSide[4];
bool barrPortVertsOtherSideValid = false;
if (pParent && !vPortNorm.IsEquivalent(Vec3(0, 0, 0), VEC_EPSILON) && vPortNorm.z)
{ // up/down portal
int nEven = IsShapeClockwise();
if (vPortNorm.z > 0)
{
nEven = !nEven;
}
for (int i = 0; i < 4; i++)
{
arrPortVerts[i] = m_lstShapePoints[nEven ? (3 - i) : i] + Vec3(0, 0, m_fHeight) * (vPortNorm.z > 0);
arrPortVertsOtherSide[i] = m_lstShapePoints[nEven ? (3 - i) : i] + Vec3(0, 0, m_fHeight) * (vPortNorm.z < 0);
}
barrPortVertsOtherSideValid = true;
}
else if (!vPortNorm.IsEquivalent(Vec3(0, 0, 0), VEC_EPSILON) && vPortNorm.z == 0)
{ // basic portal
Vec3 arrInAreaPoint[2] = {Vec3(0, 0, 0), Vec3(0, 0, 0)};
int arrInAreaPointId[2] = {-1, -1};
int nInAreaPointCounter = 0;
Vec3 arrOutAreaPoint[2] = {Vec3(0, 0, 0), Vec3(0, 0, 0)};
int nOutAreaPointCounter = 0;
// find 2 points of portal in this area (or in this outdoors)
for (int i = 0; i < m_lstShapePoints.Count() && nInAreaPointCounter < 2; i++)
{
Vec3 vTestPoint = m_lstShapePoints[i] + Vec3(0, 0, m_fHeight * 0.5f);
CVisArea* pAnotherArea = m_lstConnections[0];
if ((pParent && (pParent->IsPointInsideVisArea(vTestPoint))) ||
(!pParent && (!pAnotherArea->IsPointInsideVisArea(vTestPoint))))
{
arrInAreaPointId[nInAreaPointCounter] = i;
arrInAreaPoint[nInAreaPointCounter++] = m_lstShapePoints[i];
}
}
// find 2 points of portal not in this area (or not in this outdoors)
for (int i = 0; i < m_lstShapePoints.Count() && nOutAreaPointCounter < 2; i++)
{
Vec3 vTestPoint = m_lstShapePoints[i] + Vec3(0, 0, m_fHeight * 0.5f);
CVisArea* pAnotherArea = m_lstConnections[0];
if ((pParent && (pParent->IsPointInsideVisArea(vTestPoint))) ||
(!pParent && (!pAnotherArea->IsPointInsideVisArea(vTestPoint))))
{
}
else
{
arrOutAreaPoint[nOutAreaPointCounter++] = m_lstShapePoints[i];
}
}
if (nInAreaPointCounter == 2)
{ // success, take into account volume and portal shape versts order
int nEven = IsShapeClockwise();
if (arrInAreaPointId[1] - arrInAreaPointId[0] != 1)
{
nEven = !nEven;
}
arrPortVerts[0] = arrInAreaPoint[nEven];
arrPortVerts[1] = arrInAreaPoint[nEven] + Vec3(0, 0, m_fHeight);
arrPortVerts[2] = arrInAreaPoint[!nEven] + Vec3(0, 0, m_fHeight);
arrPortVerts[3] = arrInAreaPoint[!nEven];
nEven = !nEven;
arrPortVertsOtherSide[0] = arrOutAreaPoint[nEven];
arrPortVertsOtherSide[1] = arrOutAreaPoint[nEven] + Vec3(0, 0, m_fHeight);
arrPortVertsOtherSide[2] = arrOutAreaPoint[!nEven] + Vec3(0, 0, m_fHeight);
arrPortVertsOtherSide[3] = arrOutAreaPoint[!nEven];
barrPortVertsOtherSideValid = true;
}
else
{ // something wrong
Warning("CVisArea::PreRender: Invalid portal: %s", m_pVisAreaColdData->m_sName);
return;
}
}
else if (!pParent && vPortNorm.z == 0 && m_lstConnections.Count() == 1)
{ // basic entrance portal
Vec3 vBorder = (vPortNorm.Cross(Vec3(0, 0, 1.f))).GetNormalized() * fRadius;
arrPortVerts[0] = vCenter - Vec3(0, 0, 1.f) * fRadius - vBorder;
arrPortVerts[1] = vCenter + Vec3(0, 0, 1.f) * fRadius - vBorder;
arrPortVerts[2] = vCenter + Vec3(0, 0, 1.f) * fRadius + vBorder;
arrPortVerts[3] = vCenter - Vec3(0, 0, 1.f) * fRadius + vBorder;
}
else if (!pParent && vPortNorm.z != 0 && m_lstConnections.Count() == 1)
{ // up/down entrance portal
Vec3 vBorder = (vPortNorm.Cross(Vec3(0, 1, 0.f))).GetNormalized() * fRadius;
arrPortVerts[0] = vCenter - Vec3(0, 1, 0.f) * fRadius + vBorder;
arrPortVerts[1] = vCenter + Vec3(0, 1, 0.f) * fRadius + vBorder;
arrPortVerts[2] = vCenter + Vec3(0, 1, 0.f) * fRadius - vBorder;
arrPortVerts[3] = vCenter - Vec3(0, 1, 0.f) * fRadius - vBorder;
}
else
{ // something wrong or areabox portal - use simple solution
if (vPortNorm.IsEquivalent(Vec3(0, 0, 0), VEC_EPSILON))
{
vPortNorm = (vCenter - passInfo.GetCamera().GetPosition()).GetNormalized();
}
Vec3 vBorder = (vPortNorm.Cross(Vec3(0, 0, 1.f))).GetNormalized() * fRadius;
arrPortVerts[0] = vCenter - Vec3(0, 0, 1.f) * fRadius - vBorder;
arrPortVerts[1] = vCenter + Vec3(0, 0, 1.f) * fRadius - vBorder;
arrPortVerts[2] = vCenter + Vec3(0, 0, 1.f) * fRadius + vBorder;
arrPortVerts[3] = vCenter - Vec3(0, 0, 1.f) * fRadius + vBorder;
}
if (GetCVars()->e_Portals == 4) // make color recursion dependent
{
GetRenderer()->SetMaterialColor(1, 1, passInfo.IsGeneralPass(), 1);
}
Vec3 vPortalFaceCenter = (arrPortVerts[0] + arrPortVerts[1] + arrPortVerts[2] + arrPortVerts[3]) / 4;
vPortToCamDir = CurCamera.GetPosition() - vPortalFaceCenter;
if (vPortToCamDir.GetNormalized().Dot(vPortNorm) < -0.01f)
{
UpdatePortalBlendInfo();
return;
}
const bool Upright = (fabsf(vPortNorm.z) < FLT_EPSILON);
CCamera camParent = CurCamera;
// clip portal quad by camera planes
PodArray<Vec3>& lstPortVertsClipped = s_tmpLstPortVertsClipped;
lstPortVertsClipped.Clear();
lstPortVertsClipped.AddList(arrPortVerts, 4);
ClipPortalVerticesByCameraFrustum(&lstPortVertsClipped, camParent);
AABB aabb;
aabb.Reset();
if (lstPortVertsClipped.Count() > 2)
{
// find screen space bounds of clipped portal
for (int i = 0; i < lstPortVertsClipped.Count(); i++)
{
Vec3 vSS;
GetRenderer()->ProjectToScreen(lstPortVertsClipped[i].x, lstPortVertsClipped[i].y, lstPortVertsClipped[i].z, &vSS.x, &vSS.y, &vSS.z);
vSS.y = 100 - vSS.y;
aabb.Add(vSS);
}
}
else
{
if (!CVisArea::IsSphereInsideVisArea(CurCamera.GetPosition(), CurCamera.GetNearPlane()))
{
bCanSeeThruThisArea = false;
}
}
if (lstPortVertsClipped.Count() > 2 && aabb.min.z > 0.01f)
{
PodArray<Vec3>& lstPortVertsSS = s_tmpLstPortVertsSS;
lstPortVertsSS.PreAllocate(4, 4);
// get 3d positions of portal bounds
{
int i = 0;
float w = (float)GetRenderer()->GetWidth();
float h = (float)GetRenderer()->GetHeight();
float d = 0.01f;
GetRenderer()->UnProjectFromScreen(aabb.min.x * w / 100, aabb.min.y * h / 100, d, &lstPortVertsSS[i].x, &lstPortVertsSS[i].y, &lstPortVertsSS[i].z);
i++;
GetRenderer()->UnProjectFromScreen(aabb.min.x * w / 100, aabb.max.y * h / 100, d, &lstPortVertsSS[i].x, &lstPortVertsSS[i].y, &lstPortVertsSS[i].z);
i++;
GetRenderer()->UnProjectFromScreen(aabb.max.x * w / 100, aabb.max.y * h / 100, d, &lstPortVertsSS[i].x, &lstPortVertsSS[i].y, &lstPortVertsSS[i].z);
i++;
GetRenderer()->UnProjectFromScreen(aabb.max.x * w / 100, aabb.min.y * h / 100, d, &lstPortVertsSS[i].x, &lstPortVertsSS[i].y, &lstPortVertsSS[i].z);
i++;
CurCamera.m_ScissorInfo.x1 = uint16(CLAMP(aabb.min.x * w / 100, 0, w));
CurCamera.m_ScissorInfo.y1 = uint16(CLAMP(aabb.min.y * h / 100, 0, h));
CurCamera.m_ScissorInfo.x2 = uint16(CLAMP(aabb.max.x * w / 100, 0, w));
CurCamera.m_ScissorInfo.y2 = uint16(CLAMP(aabb.max.y * h / 100, 0, h));
}
if (GetCVars()->e_Portals == 4)
{
for (int i = 0; i < lstPortVertsSS.Count(); i++)
{
float farrColor[4] = { float((nReqursionLevel & 1) > 0), float((nReqursionLevel & 2) > 0), float((nReqursionLevel & 4) > 0), 1};
ColorF c(farrColor[0], farrColor[1], farrColor[2], farrColor[3]);
DrawSphere(lstPortVertsSS[i], 0.002f, c);
GetRenderer()->DrawLabelEx(lstPortVertsSS[i], 0.1f, farrColor, false, true, "%d", i);
}
}
UpdatePortalCameraPlanes(CurCamera, lstPortVertsSS.GetElements(), Upright, passInfo);
bCanSeeThruThisArea =
(CurCamera.m_ScissorInfo.x1 < CurCamera.m_ScissorInfo.x2) &&
(CurCamera.m_ScissorInfo.y1 < CurCamera.m_ScissorInfo.y2);
}
if (m_bUseDeepness && bCanSeeThruThisArea && barrPortVertsOtherSideValid)
{
Vec3 vOtherSideBoxMax = SetMinBB();
Vec3 vOtherSideBoxMin = SetMaxBB();
for (int i = 0; i < 4; i++)
{
vOtherSideBoxMin.CheckMin(arrPortVertsOtherSide[i] - Vec3(0.01f, 0.01f, 0.01f));
vOtherSideBoxMax.CheckMax(arrPortVertsOtherSide[i] + Vec3(0.01f, 0.01f, 0.01f));
}
bCanSeeThruThisArea = CurCamera.IsAABBVisible_E(AABB(vOtherSideBoxMin, vOtherSideBoxMax));
}
if (bCanSeeThruThisArea && pParent && m_lstConnections.Count() == 1)
{ // set this camera for outdoor
if (nReqursionLevel >= 1)
{
if (!m_bSkyOnly)
{
if (plstOutPortCameras)
{
plstOutPortCameras->Add(CurCamera);
plstOutPortCameras->Last().m_pPortal = this;
}
if (pbOutdoorVisible)
{
*pbOutdoorVisible = true;
}
}
else if (pbSkyVisible)
{
*pbSkyVisible = true;
}
}
UpdatePortalBlendInfo();
return;
}
}
// sort portals by distance
if (!m_bThisIsPortal && m_lstConnections.Count())
{
for (int p = 0; p < m_lstConnections.Count(); p++)
{
CVisArea* pNeibVolume = m_lstConnections[p];
pNeibVolume->m_fDistance = CurCamera.GetPosition().GetDistance((pNeibVolume->m_boxArea.min + pNeibVolume->m_boxArea.max) * 0.5f);
}
qsort(&m_lstConnections[0], m_lstConnections.Count(),
sizeof(m_lstConnections[0]), CVisAreaManager__CmpDistToPortal);
}
if (m_bOceanVisible && pbOceanVisible)
{
*pbOceanVisible = true;
}
// recurse to connections
for (int p = 0; p < m_lstConnections.Count(); p++)
{
CVisArea* pNeibVolume = m_lstConnections[p];
if (pNeibVolume != pParent)
{
if (!m_bThisIsPortal)
{ // skip far portals
float fRadius = (pNeibVolume->m_boxArea.max - pNeibVolume->m_boxArea.min).GetLength() * 0.5f * GetFloatCVar(e_ViewDistRatioPortals) / 60.f;
if (pNeibVolume->m_fDistance * passInfo.GetZoomFactor() > fRadius * pNeibVolume->m_fViewDistRatio)
{
continue;
}
Vec3 vPortNorm = (this == pNeibVolume->m_lstConnections[0] || pNeibVolume->m_lstConnections.Count() == 1) ?
pNeibVolume->m_vConnNormals[0] : pNeibVolume->m_vConnNormals[1];
// back face check
Vec3 vPortToCamDir = CurCamera.GetPosition() - pNeibVolume->GetAABBox()->GetCenter();
if (vPortToCamDir.Dot(vPortNorm) < 0)
{
continue;
}
}
if ((bCanSeeThruThisArea || m_lstConnections.Count() == 1) && (m_bThisIsPortal || CurCamera.IsAABBVisible_F(pNeibVolume->m_boxStatics)))
{
pNeibVolume->PreRender(nReqursionLevel - 1, CurCamera, this, pCurPortal, pbOutdoorVisible, plstOutPortCameras, pbSkyVisible, pbOceanVisible, lstVisibleAreas, passInfo);
}
}
}
if (m_bThisIsPortal)
{
UpdatePortalBlendInfo();
}
}
//! return list of visareas connected to specified visarea (can return portals and sectors)
int CVisArea::GetRealConnections(IVisArea** pAreas, int nMaxConnNum, bool bSkipDisabledPortals)
{
int nOut = 0;
for (int nArea = 0; nArea < m_lstConnections.Count(); nArea++)
{
if (nOut < nMaxConnNum)
{
pAreas[nOut] = (IVisArea*)m_lstConnections[nArea];
}
nOut++;
}
return nOut;
}
//! return list of sectors conected to specified sector or portal (returns sectors only)
// todo: change the way it returns data
int CVisArea::GetVisAreaConnections(IVisArea** pAreas, int nMaxConnNum, bool bSkipDisabledPortals)
{
int nOut = 0;
if (IsPortal())
{
/* for(int nArea=0; nArea<m_lstConnections.Count(); nArea++)
{
if(nOut<nMaxConnNum)
pAreas[nOut] = (IVisArea*)m_lstConnections[nArea];
nOut++;
}*/
return min(nMaxConnNum, GetRealConnections(pAreas, nMaxConnNum, bSkipDisabledPortals));
}
else
{
for (int nPort = 0; nPort < m_lstConnections.Count(); nPort++)
{
CVisArea* pPortal = m_lstConnections[nPort];
assert(pPortal->IsPortal());
for (int nArea = 0; nArea < pPortal->m_lstConnections.Count(); nArea++)
{
if (pPortal->m_lstConnections[nArea] != this)
{
if (!bSkipDisabledPortals || pPortal->IsActive())
{
if (nOut < nMaxConnNum)
{
pAreas[nOut] = (IVisArea*)pPortal->m_lstConnections[nArea];
}
nOut++;
break; // take first valid connection
}
}
}
}
}
return min(nMaxConnNum, nOut);
}
bool CVisArea::IsPortalValid()
{
int nCount = m_lstConnections.Count();
if (nCount > 2 || nCount == 0)
{
return false;
}
for (int i = 0; i < nCount; i++)
{
if (m_vConnNormals[i].IsEquivalent(Vec3(0, 0, 0), VEC_EPSILON))
{
return false;
}
}
if (nCount > 1)
{
if (m_vConnNormals[0].Dot(m_vConnNormals[1]) > -0.99f)
{
return false;
}
}
return true;
}
bool CVisArea::IsPortalIntersectAreaInValidWay(CVisArea* pPortal)
{
const Vec3& v1Min = pPortal->m_boxArea.min;
const Vec3& v1Max = pPortal->m_boxArea.max;
const Vec3& v2Min = m_boxArea.min;
const Vec3& v2Max = m_boxArea.max;
if (v1Max.x > v2Min.x && v2Max.x > v1Min.x)
{
if (v1Max.y > v2Min.y && v2Max.y > v1Min.y)
{
if (v1Max.z > v2Min.z && v2Max.z > v1Min.z)
{
// vertical portal
for (int v = 0; v < m_lstShapePoints.Count(); v++)
{
int nIntersNum = 0;
bool arrIntResult[4] = { 0, 0, 0, 0 };
for (int p = 0; p < pPortal->m_lstShapePoints.Count() && p < 4; p++)
{
const Vec3& v0 = m_lstShapePoints[v];
const Vec3& v1 = m_lstShapePoints[(v + 1) % m_lstShapePoints.Count()];
const Vec3& p0 = pPortal->m_lstShapePoints[p];
const Vec3& p1 = pPortal->m_lstShapePoints[(p + 1) % pPortal->m_lstShapePoints.Count()];
if (Is2dLinesIntersect(v0.x, v0.y, v1.x, v1.y, p0.x, p0.y, p1.x, p1.y))
{
nIntersNum++;
arrIntResult[p] = true;
}
}
if (nIntersNum == 2 && arrIntResult[0] == arrIntResult[2] && arrIntResult[1] == arrIntResult[3])
{
return true;
}
}
// horisontal portal
{
int nBottomPoints = 0, nUpPoints = 0;
for (int p = 0; p < pPortal->m_lstShapePoints.Count() && p < 4; p++)
{
if (IsPointInsideVisArea(pPortal->m_lstShapePoints[p]))
{
nBottomPoints++;
}
}
for (int p = 0; p < pPortal->m_lstShapePoints.Count() && p < 4; p++)
{
if (IsPointInsideVisArea(pPortal->m_lstShapePoints[p] + Vec3(0, 0, pPortal->m_fHeight)))
{
nUpPoints++;
}
}
if (nBottomPoints == 0 && nUpPoints == 4)
{
return true;
}
if (nBottomPoints == 4 && nUpPoints == 0)
{
return true;
}
}
}
}
}
return false;
}
/*
void CVisArea::SetTreeId(int nTreeId)
{
if(m_nTreeId == nTreeId)
return;
m_nTreeId = nTreeId;
for(int p=0; p<m_lstConnections.Count(); p++)
m_lstConnections[p]->SetTreeId(nTreeId);
}
*/
bool CVisArea::IsShapeClockwise()
{
float fClockWise =
(m_lstShapePoints[0].x - m_lstShapePoints[1].x) * (m_lstShapePoints[2].y - m_lstShapePoints[1].y) -
(m_lstShapePoints[0].y - m_lstShapePoints[1].y) * (m_lstShapePoints[2].x - m_lstShapePoints[1].x);
return fClockWise > 0;
}
void CVisArea::DrawAreaBoundsIntoCBuffer(CCullBuffer* pCBuffer)
{
assert(!"temprary not supported");
/* if(m_lstShapePoints.Count()!=4)
return;
Vec3 arrVerts[8];
int arrIndices[24];
int v=0;
int i=0;
for(int p=0; p<4 && p<m_lstShapePoints.Count(); p++)
{
arrVerts[v++] = m_lstShapePoints[p];
arrVerts[v++] = m_lstShapePoints[p] + Vec3(0,0,m_fHeight);
arrIndices[i++] = (p*2+0)%8;
arrIndices[i++] = (p*2+1)%8;
arrIndices[i++] = (p*2+2)%8;
arrIndices[i++] = (p*2+3)%8;
arrIndices[i++] = (p*2+2)%8;
arrIndices[i++] = (p*2+1)%8;
}
Matrix34 mat;
mat.SetIdentity();
pCBuffer->AddMesh(arrVerts,8,arrIndices,24,&mat);*/
}
void CVisArea::ClipPortalVerticesByCameraFrustum(PodArray<Vec3>* pPolygon, const CCamera& cam)
{
Plane planes[5] = {
*cam.GetFrustumPlane(FR_PLANE_RIGHT),
*cam.GetFrustumPlane(FR_PLANE_LEFT),
*cam.GetFrustumPlane(FR_PLANE_TOP),
*cam.GetFrustumPlane(FR_PLANE_BOTTOM),
*cam.GetFrustumPlane(FR_PLANE_NEAR)
};
const PodArray<Vec3>& clipped = s_tmpClipContext.Clip(*pPolygon, planes, 4);
pPolygon->Clear();
pPolygon->AddList(clipped);
}
void CVisArea::GetMemoryUsage(ICrySizer* pSizer)
{
// pSizer->AddContainer(m_lstEntities[STATIC_OBJECTS]);
//pSizer->AddContainer(m_lstEntities[DYNAMIC_OBJECTS]);
// TODO: include obects tree
if (m_pObjectsTree)
{
SIZER_COMPONENT_NAME(pSizer, "IndoorObjectsTree");
m_pObjectsTree->GetMemoryUsage(pSizer);
}
// for(int nStatic=0; nStatic<2; nStatic++)
//for(int i=0; i<m_lstEntities[nStatic].Count(); i++)
// nSize += m_lstEntities[nStatic][i].pNode->GetMemoryUsage();
pSizer->AddObject(this, sizeof(*this));
}
void CVisArea::UpdateOcclusionFlagInTerrain()
{
if (m_bAffectedByOutLights && !m_bThisIsPortal)
{
Vec3 vCenter = GetAABBox()->GetCenter();
if (vCenter.z < GetTerrain()->GetBilinearZ(vCenter.x, vCenter.y))
{
AABB box = *GetAABBox();
box.min.z = 0;
box.min -= Vec3(8, 8, 8);
box.max.z = 16000;
box.max += Vec3(8, 8, 8);
PodArray<CTerrainNode*>& lstResult = s_tmpLstTerrainNodeResult;
lstResult.Clear();
GetTerrain()->IntersectWithBox(box, &lstResult);
for (int i = 0; i < lstResult.Count(); i++)
{
if (lstResult[i]->m_nTreeLevel <= 2)
{
lstResult[i]->m_bNoOcclusion = true;
}
}
}
}
}
void CVisArea::AddConnectedAreas(PodArray<CVisArea*>& lstAreas, int nMaxRecursion)
{
if (lstAreas.Find(this) < 0)
{
lstAreas.Add(this);
// add connected areas
if (nMaxRecursion)
{
nMaxRecursion--;
for (int p = 0; p < m_lstConnections.Count(); p++)
{
m_lstConnections[p]->AddConnectedAreas(lstAreas, nMaxRecursion);
}
}
}
}
bool CVisArea::GetDistanceThruVisAreas(AABB vCurBoxIn, IVisArea* pTargetArea, const AABB& targetBox, int nMaxReqursion, float& fResDist)
{
return GetDistanceThruVisAreasReq(vCurBoxIn, 0, pTargetArea, targetBox, nMaxReqursion, fResDist, NULL, s_nGetDistanceThruVisAreasCallCounter++);
}
float DistanceAABB(const AABB& aBox, const AABB& bBox)
{
float result = 0;
for (int i = 0; i < 3; ++i)
{
const float& aMin = aBox.min[i];
const float& aMax = aBox.max[i];
const float& bMin = bBox.min[i];
const float& bMax = bBox.max[i];
if (aMin > bMax)
{
const float delta = bMax - aMin;
result += delta * delta;
}
else if (bMin > aMax)
{
const float delta = aMax - bMin;
result += delta * delta;
}
// else the projection intervals overlap.
}
return sqrt(result);
}
bool CVisArea::GetDistanceThruVisAreasReq(AABB vCurBoxIn, float fCurDistIn, IVisArea* pTargetArea, const AABB& targetBox, int nMaxReqursion, float& fResDist, CVisArea* pPrevArea, int nCallID)
{
if (pTargetArea == this || (pTargetArea == NULL && IsConnectedToOutdoor()))
{ // target area is found
fResDist = min(fResDist, fCurDistIn + DistanceAABB(vCurBoxIn, targetBox));
return true;
}
// if we already visited this area and last time input distance was smaller - makes no sence to continue
if (nCallID == m_nGetDistanceThruVisAreasLastCallID)
{
if (fCurDistIn >= m_fGetDistanceThruVisAreasMinDistance)
{
return false;
}
}
m_nGetDistanceThruVisAreasLastCallID = nCallID;
m_fGetDistanceThruVisAreasMinDistance = fCurDistIn;
fResDist = FLT_MAX;
bool bFound = false;
if (nMaxReqursion > 1)
{
for (int p = 0; p < m_lstConnections.Count(); p++)
{
if ((m_lstConnections[p] != pPrevArea) && m_lstConnections[p]->IsActive())
{
AABB vCurBox = vCurBoxIn;
float fCurDist = fCurDistIn;
float dist = FLT_MAX;
if (IsPortal())
{
vCurBox = vCurBoxIn;
fCurDist = fCurDistIn;
}
else
{
vCurBox = *m_lstConnections[p]->GetAABBox();
fCurDist = fCurDistIn + DistanceAABB(vCurBox, vCurBoxIn);
}
if (m_lstConnections[p]->GetDistanceThruVisAreasReq(vCurBox, fCurDist, pTargetArea, targetBox, nMaxReqursion - 1, dist, this, nCallID))
{
bFound = true;
fResDist = min(fResDist, dist);
}
}
}
}
return bFound;
}
void CVisArea::OffsetPosition(const Vec3& delta)
{
m_boxArea.Move(delta);
m_boxStatics.Move(delta);
for (int i = 0; i < m_lstShapePoints.Count(); i++)
{
m_lstShapePoints[i] += delta;
}
if (m_pObjectsTree)
{
m_pObjectsTree->OffsetObjects(delta);
}
}
| 34.105353 | 205 | 0.565642 | [
"shape",
"3d"
] |
917c74270449f58b2a6e8262637014eb6779e2cd | 11,935 | cc | C++ | include/insnet/operator/matrix.cc | ishine/N3LDG-plus | 7fdfd79b75265487df9240176ca7a2b1adbaadab | [
"Apache-2.0"
] | 27 | 2021-06-07T02:25:33.000Z | 2022-03-16T20:41:14.000Z | include/insnet/operator/matrix.cc | ishine/N3LDG-plus | 7fdfd79b75265487df9240176ca7a2b1adbaadab | [
"Apache-2.0"
] | null | null | null | include/insnet/operator/matrix.cc | ishine/N3LDG-plus | 7fdfd79b75265487df9240176ca7a2b1adbaadab | [
"Apache-2.0"
] | 3 | 2021-07-10T15:11:00.000Z | 2022-03-06T03:10:30.000Z | #include "insnet/operator/matrix.h"
#include "insnet/util/util.h"
using std::array;
using std::vector;
using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::to_string;
using std::make_pair;
using std::pair;
namespace insnet {
class MatrixExecutor : public Executor {
public:
int getRow() const {
return batch.front()->getRow();
}
vector<int> getCols() const {
vector<int> cols;
cols.reserve(batch.size());
for (Node *node : batch) {
cols.push_back(node->getColumn());
}
return cols;
}
};
class MatrixMulMatrixNode : public Node, public Poolable<MatrixMulMatrixNode> {
public:
MatrixMulMatrixNode() : Node("MatrixMulMatrixNode") {}
void setNodeDim(int dim) override {
setDim(dim);
}
void setInputs(const vector<Node *> &ins) override {
int a_size = ins.at(0)->size();
if (a_size % k_ != 0) {
cerr << fmt::format("MatrixMulMatrixNode setInputs a_size:{} k:{}\n", a_size, k_);
abort();
}
Node::setInputs(ins);
}
void connect(Node &a, Node &b) {
setInputs({&a, &b});
afterConnect({&a, &b});
}
void compute() override {
a_row_ = input_dims_.at(0) / k_;
b_col_ = input_dims_.at(1) / k_;
Mat(getVal().v, a_row_, b_col_) = Mat(input_vals_.at(0)->v, a_row_, k_) *
Mat(input_vals_.at(1)->v, k_, b_col_);
}
void backward() override {
Mat(input_grads_.at(0)->v, a_row_, k_) += Mat(getGrad().v, a_row_, b_col_) *
Mat(input_vals_.at(1)->v, k_, b_col_).transpose();
Mat(input_grads_.at(1)->v, k_, b_col_) +=
Mat(input_vals_.at(0)->v, a_row_, k_).transpose() * Mat(getGrad().v, a_row_, b_col_);
}
Executor * generate() override;
string typeSignature() const override {
return Node::getNodeType() + to_string(input_dims_.at(0) / k_);
}
int k_ = 0;
protected:
int forwardOnlyInputValSize() override {
return 0;
}
bool isValForwardOnly() const override {
return true;
}
private:
int a_row_;
int b_col_;
friend class BatchedMatrixMulMatrixNode;
friend class MatrixMulMatrixExecutor;
};
class BatchedMatrixMulMatrixNode : public BatchedNodeImpl<MatrixMulMatrixNode> {
public:
void init(BatchedNode &a, BatchedNode &b, int k) {
int a_row = a.size() / k;
int b_col = b.size() / k;
allocateBatch(a_row * b_col, a.batch().size());
for (Node *node : batch()) {
MatrixMulMatrixNode &m = dynamic_cast<MatrixMulMatrixNode &>(*node);
m.k_ = k;
}
setInputsPerNode({&a, &b});
afterInit({&a, &b});
}
};
#if USE_GPU
class MatrixMulMatrixExecutor : public Executor {
public:
void forward() override {
int count = batch.size();
vector<dtype *> vals;
a_vals_.reserve(count);
b_vals_.reserve(count);
vals.reserve(count);
ks_.reserve(count);
b_cols_.reserve(count);
for (Node *node : batch) {
MatrixMulMatrixNode &m = dynamic_cast<MatrixMulMatrixNode &>(*node);
a_vals_.push_back(m.input_vals_.at(0)->value);
b_vals_.push_back(m.input_vals_.at(1)->value);
vals.push_back(m.getVal().value);
ks_.push_back(m.k_);
b_cols_.push_back(m.input_dims_.at(1) / m.k_);
}
MatrixMulMatrixNode &first = dynamic_cast<MatrixMulMatrixNode &>(*batch.front());
row_ = first.input_dims_.at(0) / first.k_;
#if TEST_CUDA
testForwardInpputs();
#endif
cuda::MatrixMulMatrixForward(a_vals_, b_vals_, count, ks_, b_cols_, row_, vals);
#if TEST_CUDA
testForward();
#endif
}
void backward() override {
int count = batch.size();
vector<dtype *> grads, a_grads, b_grads;
grads.reserve(count);
a_grads.reserve(count);
b_grads.reserve(count);
for (Node *node : batch) {
MatrixMulMatrixNode &m = dynamic_cast<MatrixMulMatrixNode &>(*node);
grads.push_back(m.getGrad().value);
a_grads.push_back(m.input_grads_.at(0)->value);
b_grads.push_back(m.input_grads_.at(1)->value);
}
#if TEST_CUDA
cout << "testing matmul backward input" << endl;
testBeforeBackward();
#endif
cuda::MatrixMulMatrixBackward(grads, a_vals_, b_vals_, count, ks_, b_cols_, row_,
a_grads, b_grads);
#if TEST_CUDA
cout << "testing matmul backward" << endl;
testBackward();
#endif
}
private:
vector<dtype *> a_vals_, b_vals_;
vector<int> ks_, b_cols_;
int row_;
};
#else
class MatrixMulMatrixExecutor : public Executor {
public:
int calculateFLOPs() override {
return 0; // TODO
}
};
#endif
Executor *MatrixMulMatrixNode::generate() {
return new MatrixMulMatrixExecutor;
}
class TranMatrixMulMatrixNode : public Node, public Poolable<TranMatrixMulMatrixNode> {
public:
TranMatrixMulMatrixNode() : Node("TranMatrixMulMatrixNode") {}
void setNodeDim(int dim) override {
setDim(dim);
}
void connect(Node &a, Node &b) {
vector<Node *> inputs = {&a, &b};
setInputs(inputs);
afterConnect(inputs);
}
void compute() override {
a_col_ = input_dims_.at(0) / input_row_;
b_col_ = input_dims_.at(1) / input_row_;
Mat(val().v, a_col_, b_col_) = Mat(input_vals_.at(0)->v, input_row_, a_col_).transpose()
* Mat(input_vals_.at(1)->v, input_row_, b_col_);
if (use_lower_triangular_mask_) {
if (a_col_ != b_col_) {
cerr << fmt::format("a_col_:{} b_col_:{}\n", a_col_, b_col_);
abort();
}
for (int i = 0; i < a_col_; ++i) {
for (int j = i + 1; j < a_col_; ++j) {
val()[i * a_col_ + j] = -INF;
}
}
}
}
void backward() override {
Mat(input_grads_.at(0)->v, input_row_, a_col_) +=
Mat(input_vals_.at(1)->v, input_row_, b_col_) *
Mat(getGrad().v, a_col_, b_col_).transpose();
Mat(input_grads_.at(1)->v, input_row_, b_col_) +=
Mat(input_vals_.at(0)->v, input_row_, a_col_) * Mat(getGrad().v, a_col_, b_col_);
}
Executor * generate() override;
string typeSignature() const override {
return Node::getNodeType() + to_string(input_row_) +
(use_lower_triangular_mask_ ? "-mask" : "-no-mask");
}
int a_col_, b_col_, input_row_;
bool use_lower_triangular_mask_ = false;
protected:
int forwardOnlyInputValSize() override {
return 0;
}
bool isValForwardOnly() const override {
return true;
}
private:
friend class TranMatrixMulMatrixExecutor;
};
class BatchedTranMatrixMulMatrixNode : public BatchedNodeImpl<TranMatrixMulMatrixNode> {
public:
void init(BatchedNode &a, BatchedNode &b, int input_row,
bool use_lower_triangular_mask = false) {
int a_col = a.size() / input_row;
int b_col = b.size() / input_row;
if (use_lower_triangular_mask && a_col != b_col) {
cerr << fmt::format("BatchedTranMatrixMulMatrixNode init a_col:{} b_col:{}\n",
a_col, b_col);
abort();
}
allocateBatch(a_col * b_col, a.batch().size());
setInputsPerNode({&a, &b});
for (Node *node : batch()) {
TranMatrixMulMatrixNode &t = dynamic_cast<TranMatrixMulMatrixNode &>(*node);
t.use_lower_triangular_mask_ = use_lower_triangular_mask;
t.input_row_ = input_row;
}
afterInit({&a, &b});
}
};
#if USE_GPU
class TranMatrixMulMatrixExecutor : public Executor {
public:
void forward() override {
int count = batch.size();
vector<dtype *> vals;
vals.reserve(count);
a_cols_.reserve(count);
b_cols_.reserve(count);
b_cols_.reserve(count);
a_vals_.reserve(count);
b_vals_.reserve(count);
input_row_ = dynamic_cast<TranMatrixMulMatrixNode &>(*batch.front()).input_row_;
use_lower_triangular_mask_ =
dynamic_cast<TranMatrixMulMatrixNode &>(*batch.front()).use_lower_triangular_mask_;
for (Node *node : batch) {
TranMatrixMulMatrixNode &t = dynamic_cast<TranMatrixMulMatrixNode &>(*node);
a_vals_.push_back(t.input_vals_.at(0)->value);
b_vals_.push_back(t.input_vals_.at(1)->value);
vals.push_back(t.getVal().value);
a_cols_.push_back(t.input_dims_.at(0) / input_row_);
b_cols_.push_back(t.input_dims_.at(1) / input_row_);
}
cuda::TranMatrixMulMatrixForward(a_vals_, b_vals_, count, a_cols_, b_cols_, input_row_,
use_lower_triangular_mask_, vals);
#if TEST_CUDA
testForward();
#endif
}
void backward() override {
int count = batch.size();
vector<dtype *> a_grads, b_grads, grads;
a_grads.reserve(count);
b_grads.reserve(count);
for (Node *node : batch) {
TranMatrixMulMatrixNode &t = dynamic_cast<TranMatrixMulMatrixNode &>(*node);
a_grads.push_back(t.input_grads_.at(0)->value);
b_grads.push_back(t.input_grads_.at(1)->value);
grads.push_back(t.getGrad().value);
}
cuda::TranMatrixMulMatrixBackward(grads, a_vals_, b_vals_, count, a_cols_, b_cols_,
input_row_, a_grads, b_grads);
#if TEST_CUDA
testBackward();
#endif
}
private:
vector<dtype *> a_vals_, b_vals_;
vector<int> a_cols_, b_cols_;
int input_row_;
bool use_lower_triangular_mask_;
};
#else
class TranMatrixMulMatrixExecutor : public Executor {
public:
int calculateFLOPs() override {
abort();
}
};
#endif
Executor* TranMatrixMulMatrixNode::generate() {
return new TranMatrixMulMatrixExecutor;
}
BatchedNode *tranMatrixMulMatrix(BatchedNode &a, BatchedNode &b, int input_row,
bool use_lower_triangular_mask) {
BatchedTranMatrixMulMatrixNode *node = new BatchedTranMatrixMulMatrixNode;
node->init(a, b, input_row, use_lower_triangular_mask);
return node;
}
Node *matmul(Node &a, Node &b, int b_row, bool transpose_a, bool use_lower_triangular_mask) {
if (transpose_a) {
int a_col = a.size() / b_row;
if (a_col * b_row != a.size()) {
cerr << fmt::format("a size:{} b_row:{}", a.size(), b_row) << endl;
abort();
}
int b_col = b.size() / b_row;
if (b_col * b_row != b.size()) {
cerr << fmt::format("b size:{} b_row:{}", b.size(), b_row) << endl;
abort();
}
if (use_lower_triangular_mask && a_col != b_col) {
cerr << fmt::format("matmul init a_col:{} b_col:{}\n", a_col, b_col);
abort();
}
TranMatrixMulMatrixNode *result = TranMatrixMulMatrixNode::newNode(a_col * b_col);
result->use_lower_triangular_mask_ = use_lower_triangular_mask;
result->input_row_ = b_row;
result->connect(a, b);
return result;
} else {
if (use_lower_triangular_mask) {
cerr << fmt::format("matmul transpose_a:{} use_lower_triangular_mask:{}", transpose_a,
use_lower_triangular_mask) << endl;
abort();
}
int a_row = a.size() / b_row;
int b_col = b.size() / b_row;
MatrixMulMatrixNode *result = MatrixMulMatrixNode::newNode(a_row * b_col);
result->setColumn(b_col);
result->k_ = b_row;
result->connect(a, b);
return result;
}
}
BatchedNode *matrixMulMatrix(BatchedNode &a, BatchedNode &b, int k) {
BatchedMatrixMulMatrixNode *node = new BatchedMatrixMulMatrixNode;
node->init(a, b, k);
return node;
}
}
| 30.681234 | 98 | 0.600251 | [
"vector"
] |
91839b1e235c45d56c0525a48da9844fa7059376 | 5,115 | cpp | C++ | Gems/MultiplayerCompression/Code/Tests/MultiplayerCompressionTest.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-12T14:13:45.000Z | 2022-03-12T14:13:45.000Z | Gems/MultiplayerCompression/Code/Tests/MultiplayerCompressionTest.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-13T04:29:38.000Z | 2022-03-12T01:05:31.000Z | Gems/MultiplayerCompression/Code/Tests/MultiplayerCompressionTest.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <lz4.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <LZ4Compressor.h>
#include <AzCore/Compression/Compression.h>
#include <AzNetworking/DataStructures/ByteBuffer.h>
#include <AzNetworking/Serialization/NetworkInputSerializer.h>
#include <AzTest/AzTest.h>
class MultiplayerCompressionTest
: public UnitTest::AllocatorsTestFixture
{
protected:
void SetUp() override
{
AllocatorsTestFixture::SetUp();
}
void TearDown() override
{
AllocatorsTestFixture::TearDown();
}
};
TEST_F(MultiplayerCompressionTest, MultiplayerCompression_CompressTest)
{
AzNetworking::UdpPacketEncodingBuffer buffer;
buffer.Resize(buffer.GetCapacity());
// Setup and marshal a highly compressable buffer for LZ4
AZStd::chrono::system_clock::time_point startTime = AZStd::chrono::system_clock::now();
memset(buffer.GetBuffer(), 255, buffer.GetCapacity());
size_t maxCompressedSize = buffer.GetSize() + 32U;
size_t compressedSize = -1;
size_t uncompressedSize = -1;
size_t consumedSize = -1;
char* pCompressedBuffer = new char[maxCompressedSize];
char* pDecompressedBuffer = new char[buffer.GetSize()];
//Run and test compress
MultiplayerCompression::LZ4Compressor lz4Compressor;
startTime = AZStd::chrono::system_clock::now();
AzNetworking::CompressorError compressStatus = lz4Compressor.Compress(buffer.GetBuffer(), buffer.GetSize(), pCompressedBuffer, maxCompressedSize, compressedSize);
const AZ::u64 compressTime = (AZStd::chrono::system_clock::now() - startTime).count();
ASSERT_TRUE(compressStatus == AzNetworking::CompressorError::Ok);
EXPECT_TRUE(compressedSize < maxCompressedSize);
//Run and test decompress
startTime = AZStd::chrono::system_clock::now();
AzNetworking::CompressorError decompressStatus = lz4Compressor.Decompress(pCompressedBuffer, compressedSize, pDecompressedBuffer, buffer.GetSize(), consumedSize, uncompressedSize);
const AZ::u64 decompressTime = (AZStd::chrono::system_clock::now() - startTime).count();
ASSERT_TRUE(decompressStatus == AzNetworking::CompressorError::Ok);
EXPECT_TRUE(uncompressedSize = buffer.GetSize());
EXPECT_TRUE(memcmp(pDecompressedBuffer, buffer.GetBuffer(), uncompressedSize) == 0);
const AZ::u64 unmarshalTime = (AZStd::chrono::system_clock::now() - startTime).count();
delete [] pCompressedBuffer;
delete [] pDecompressedBuffer;
//Expected [Profile]: Uncompressed Size: 2048 B Compressed Size: 21 B
AZ_TracePrintf("Multiplayer Compression Test", "Uncompressed Size:(%llu B) Compressed Size:(%llu B) \n", uncompressedSize, compressedSize);
//Expected [Profile]: Marshal Time : 84 mcs Unmarshal Time : 98 mcs Compress Time : 182 mcs Decompress Time : 7 mcs (times will vary with hardware)
AZ_TracePrintf("Multiplayer Compression Test", "Compress Time:(%llu mcs) Decompress Time:(%llu mcs) \n", compressTime, decompressTime);
}
TEST_F(MultiplayerCompressionTest, MultiplayerCompression_OversizeTest)
{
size_t badInputSize = LZ4_MAX_INPUT_SIZE + 1;
size_t bufferSize = 4;
char* badInput = new char[badInputSize];
char* pBuffer = new char[bufferSize];
size_t compressedSize = 0;
MultiplayerCompression::LZ4Compressor lz4Compressor;
AzNetworking::CompressorError compressStatus = lz4Compressor.Compress(badInput, badInputSize, pBuffer, bufferSize, compressedSize);
EXPECT_TRUE(compressStatus == AzNetworking::CompressorError::InsufficientBuffer);
delete [] badInput;
delete [] pBuffer;
}
TEST_F(MultiplayerCompressionTest, MultiplayerCompressionTest_UndersizeTest)
{
size_t badInputSize = LZ4_MAX_INPUT_SIZE + 1;
size_t bufferSize = 4;
char* badInput = new char[badInputSize];
char* pBuffer = new char[bufferSize];
size_t consumedSize = 0;
size_t uncompressedSize = 0;
MultiplayerCompression::LZ4Compressor lz4Compressor;
AzNetworking::CompressorError decompressStatus = lz4Compressor.Decompress(badInput, badInputSize, pBuffer, bufferSize, consumedSize, uncompressedSize);
EXPECT_TRUE(decompressStatus == AzNetworking::CompressorError::CorruptData);
delete [] badInput;
delete [] pBuffer;
}
TEST_F(MultiplayerCompressionTest, MultiplayerCompressionTest_NullTest)
{
size_t compressedSize = 0;
size_t consumedSize = 0;
size_t uncompressedSize = 0;
MultiplayerCompression::LZ4Compressor lz4Compressor;
AzNetworking::CompressorError compressStatus = lz4Compressor.Compress(nullptr, 4, nullptr, 4, compressedSize);
EXPECT_TRUE(compressStatus == AzNetworking::CompressorError::Uninitialized);
AzNetworking::CompressorError decompressStatus = lz4Compressor.Decompress(nullptr, 4, nullptr, 4, consumedSize, uncompressedSize);
EXPECT_TRUE(decompressStatus == AzNetworking::CompressorError::Uninitialized);
}
AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV);
| 39.045802 | 184 | 0.754643 | [
"3d"
] |
918467ef28ef1dba4558b635ef7cfb26eb296b0e | 13,844 | cpp | C++ | c++/src/objtools/blast/blastdb_format/blastdb_dataextract.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/src/objtools/blast/blastdb_format/blastdb_dataextract.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/src/objtools/blast/blastdb_format/blastdb_dataextract.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | /* $Id: blastdb_dataextract.cpp 389294 2013-02-14 18:43:48Z rafanovi $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Christiam Camacho
*
*/
/** @file blastdb_dataextract.cpp
* Defines classes which extract data from a BLAST database
*/
#ifndef SKIP_DOXYGEN_PROCESSING
static char const rcsid[] = "$Id: blastdb_dataextract.cpp 389294 2013-02-14 18:43:48Z rafanovi $";
#endif /* SKIP_DOXYGEN_PROCESSING */
#include <ncbi_pch.hpp>
#include <objtools/blast/blastdb_format/invalid_data_exception.hpp>
#include <objtools/blast/blastdb_format/blastdb_dataextract.hpp>
#include <objects/seq/Seqdesc.hpp>
#include <objects/seq/Seq_descr.hpp>
#include <objects/seqloc/Seq_id.hpp>
#include <corelib/ncbiutil.hpp>
#include <util/sequtil/sequtil_manip.hpp>
#include <util/checksum.hpp>
BEGIN_NCBI_SCOPE
USING_SCOPE(objects);
#define NOT_AVAILABLE "N/A"
void CBlastDBExtractor::SetSeqId(const CBlastDBSeqId &id, bool get_data) {
m_Defline.Reset();
m_Gi = 0;
m_Oid = -1;
CRef<CSeq_id> seq_id;
int target_gi = 0;
CSeq_id *target_seq_id = NULL;
if (id.IsOID()) {
m_Oid = id.GetOID();
} else if (id.IsGi()) {
m_Gi = id.GetGi();
m_BlastDb.GiToOid(m_Gi, m_Oid);
if (m_TargetOnly || ! get_data) target_gi = m_Gi;
} else if (id.IsPig()) {
m_BlastDb.PigToOid(id.GetPig(), m_Oid);
} else if (id.IsStringId()) {
string acc(id.GetStringId());
NStr::ToUpper(acc);
vector<int> oids;
m_BlastDb.AccessionToOids(acc, oids);
if (!oids.empty()) {
m_Oid = oids[0];
if (m_TargetOnly || ! get_data) {
// TODO check if id is complete
seq_id.Reset(new CSeq_id(acc, CSeq_id::fParse_PartialOK));
target_seq_id = &(*seq_id);
}
}
}
if (m_Oid < 0) {
NCBI_THROW(CSeqDBException, eArgErr,
"Entry not found in BLAST database");
}
TSeqPos length = m_BlastDb.GetSeqLength(m_Oid);
if (length <= 0) {
NCBI_THROW(CSeqDBException, eArgErr,
"Entry found in BLAST database has invalid length");
}
m_SeqRange = m_OrigSeqRange;
if((TSeqPos)length < m_SeqRange.GetTo())
{
m_SeqRange.SetTo(length-1);
}
if(TSeqRange::GetPositionMax() == m_OrigSeqRange.GetTo())
{
if (m_SeqRange.GetTo() < m_SeqRange.GetFrom()) {
NCBI_THROW(CSeqDBException, eArgErr,
"start pos > length of sequence");
}
}
try {
if (get_data) {
m_Bioseq.Reset(m_BlastDb.GetBioseq(m_Oid, target_gi, target_seq_id));
} else {
m_Bioseq.Reset(m_BlastDb.GetBioseqNoData(m_Oid, target_gi, target_seq_id));
}
} catch (const CSeqDBException& e) {
// this happens when CSeqDB detects a GI that doesn't belong to a
// filtered database (e.g.: swissprot as a subset of nr)
if (e.GetMsg().find("oid headers do not contain target gi")) {
NCBI_THROW(CSeqDBException, eArgErr,
"Entry not found in BLAST database");
}
}
}
string CBlastDBExtractor::ExtractOid() {
return NStr::IntToString(m_Oid);
}
string CBlastDBExtractor::ExtractPig() {
int pig;
m_BlastDb.OidToPig(m_Oid, pig);
return NStr::IntToString(pig);
}
string CBlastDBExtractor::ExtractGi() {
x_SetGi();
return (m_Gi ? NStr::IntToString(m_Gi) : NOT_AVAILABLE);
}
void CBlastDBExtractor::x_SetGi() {
if (m_Gi) return;
ITERATE(list<CRef<CSeq_id> >, itr, m_Bioseq->GetId()) {
if ((*itr)->IsGi()) {
m_Gi = (*itr)->GetGi();
return;
}
}
return;
}
void CBlastDBExtractor::x_InitDefline()
{
if (m_Defline.NotEmpty()) {
return;
}
if (m_Bioseq.NotEmpty()) {
m_Defline = CSeqDB::ExtractBlastDefline(*m_Bioseq);
}
if (m_Defline.Empty()) {
m_Defline = m_BlastDb.GetHdr(m_Oid);
}
}
string CBlastDBExtractor::ExtractMembershipInteger()
{
x_InitDefline();
int retval = 0;
if (m_Gi == 0) {
return NStr::IntToString(0);
}
ITERATE(CBlast_def_line_set::Tdata, itr, m_Defline->Get()) {
const CRef<CSeq_id> seqid = FindBestChoice((*itr)->GetSeqid(),
CSeq_id::BestRank);
_ASSERT(seqid.NotEmpty());
if (seqid->IsGi() && (seqid->GetGi() == m_Gi) &&
(*itr)->IsSetMemberships()) {
ITERATE(CBlast_def_line::TMemberships, memb_int,
(*itr)->GetMemberships()) {
retval += *memb_int;
}
break;
}
}
return NStr::IntToString(retval);
}
string CBlastDBExtractor::ExtractAsn1Defline()
{
x_InitDefline();
CNcbiOstrstream oss;
oss << MSerial_AsnText << *m_Defline << endl;
return CNcbiOstrstreamToString(oss);
}
string CBlastDBExtractor::ExtractAsn1Bioseq()
{
_ASSERT(m_Bioseq.NotEmpty());
CNcbiOstrstream oss;
oss << MSerial_AsnText << *m_Bioseq << endl;
return CNcbiOstrstreamToString(oss);
}
string CBlastDBExtractor::ExtractAccession() {
CRef<CSeq_id> theId = FindBestChoice(m_Bioseq->GetId(), CSeq_id::WorstRank);
if (theId->IsGeneral() && theId->GetGeneral().GetDb() == "BL_ORD_ID") {
return "No ID available";
}
string acc;
theId->GetLabel(&acc, CSeq_id::eContent);
return acc;
}
string CBlastDBExtractor::ExtractSeqId() {
CRef<CSeq_id> theId = FindBestChoice(m_Bioseq->GetId(), CSeq_id::WorstRank);
if (theId->IsGeneral() && theId->GetGeneral().GetDb() == "BL_ORD_ID") {
return "No ID available";
}
return theId->AsFastaString();
}
string CBlastDBExtractor::ExtractTitle() {
ITERATE(list <CRef <CSeqdesc> >, itr, m_Bioseq->GetDescr().Get()) {
if ((*itr)->IsTitle()) {
return (*itr)->GetTitle();
}
}
return NOT_AVAILABLE;
}
string CBlastDBExtractor::ExtractTaxId() {
return NStr::IntToString(x_ExtractTaxId());
}
string CBlastDBExtractor::ExtractCommonTaxonomicName() {
const int kTaxID = x_ExtractTaxId();
SSeqDBTaxInfo tax_info;
string retval(NOT_AVAILABLE);
try {
m_BlastDb.GetTaxInfo(kTaxID, tax_info);
_ASSERT(kTaxID == tax_info.taxid);
retval = tax_info.common_name;
} catch (...) {}
return retval;
}
string CBlastDBExtractor::ExtractScientificName() {
const int kTaxID = x_ExtractTaxId();
SSeqDBTaxInfo tax_info;
string retval(NOT_AVAILABLE);
try {
m_BlastDb.GetTaxInfo(kTaxID, tax_info);
_ASSERT(kTaxID == tax_info.taxid);
retval = tax_info.scientific_name;
} catch (...) {}
return retval;
}
string CBlastDBExtractor::ExtractMaskingData() {
static const string kNoMasksFound("none");
#if ((defined(NCBI_COMPILER_WORKSHOP) && (NCBI_COMPILER_VERSION <= 550)) || \
defined(NCBI_COMPILER_MIPSPRO))
return kNoMasksFound;
#else
CSeqDB::TSequenceRanges masked_ranges;
x_ExtractMaskingData(masked_ranges, m_FmtAlgoId);
if (masked_ranges.empty()) return kNoMasksFound;
CNcbiOstrstream out;
ITERATE(CSeqDB::TSequenceRanges, range, masked_ranges) {
out << range->first << "-" << range->second << ";";
}
return CNcbiOstrstreamToString(out);
#endif
}
string CBlastDBExtractor::ExtractSeqData() {
string seq;
try {
m_BlastDb.GetSequenceAsString(m_Oid, seq, m_SeqRange);
CSeqDB::TSequenceRanges masked_ranges;
x_ExtractMaskingData(masked_ranges, m_FiltAlgoId);
ITERATE(CSeqDB::TSequenceRanges, mask, masked_ranges) {
transform(&seq[mask->first], &seq[mask->second],
&seq[mask->first], (int (*)(int))tolower);
}
if (m_Strand == eNa_strand_minus) {
CSeqManip::ReverseComplement(seq, CSeqUtil::e_Iupacna,
0, seq.size());
}
} catch (CSeqDBException& e) {
//FIXME: change the enumeration when it's availble
if (e.GetErrCode() == CSeqDBException::eArgErr ||
e.GetErrCode() == CSeqDBException::eFileErr/*eOutOfRange*/) {
NCBI_THROW(CInvalidDataException, eInvalidRange, e.GetMsg());
}
throw;
}
return seq;
}
string CBlastDBExtractor::ExtractSeqLen() {
return NStr::IntToString(m_BlastDb.GetSeqLength(m_Oid));
}
// Calculates hash for a buffer in IUPACna (NCBIeaa for proteins) format.
// NOTE: if sequence is in a different format, the function below can be modified to convert
// each byte into IUPACna encoding on the fly.
static int s_GetHash(const char* buffer, int length)
{
CChecksum crc(CChecksum::eCRC32ZIP);
for(int ii = 0; ii < length; ii++) {
if (buffer[ii] != '\n')
crc.AddChars(buffer+ii,1);
}
return (crc.GetChecksum() ^ (0xFFFFFFFFL));
}
string CBlastDBExtractor::ExtractHash() {
string seq;
m_BlastDb.GetSequenceAsString(m_Oid, seq);
return NStr::IntToString(s_GetHash(seq.c_str(), seq.size()));
}
static void s_ReplaceCtrlAsInTitle(CRef<CBioseq> bioseq)
{
static const string kTarget(" >gi|");
static const string kCtrlA = string(1, '\001') + string("gi|");
NON_CONST_ITERATE(CSeq_descr::Tdata, desc, bioseq->SetDescr().Set()) {
if ((*desc)->Which() == CSeqdesc::e_Title) {
NStr::ReplaceInPlace((*desc)->SetTitle(), kTarget, kCtrlA);
break;
}
}
}
string CBlastDBExtractor::ExtractFasta(const CBlastDBSeqId &id) {
stringstream out("");
CFastaOstream fasta(out);
fasta.SetWidth(m_LineWidth);
fasta.SetAllFlags(CFastaOstream::fKeepGTSigns);
SetSeqId(id, true);
if (m_UseCtrlA) {
s_ReplaceCtrlAsInTitle(m_Bioseq);
}
CRef<CSeq_id> seqid = FindBestChoice(m_Bioseq->GetId(), CSeq_id::BestRank);
// Handle the case when a sequence range is provided
CRef<CSeq_loc> range;
if (m_SeqRange.NotEmpty() || m_Strand != eNa_strand_other) {
if (m_SeqRange.NotEmpty()) {
range.Reset(new CSeq_loc(*seqid, m_SeqRange.GetFrom(),
m_SeqRange.GetTo(), m_Strand));
fasta.ResetFlag(CFastaOstream::fSuppressRange);
} else {
TSeqPos length = m_Bioseq->GetLength();
range.Reset(new CSeq_loc(*seqid, 0, length-1, m_Strand));
fasta.SetFlag(CFastaOstream::fSuppressRange);
}
}
// Handle any requests for masked FASTA
static const CFastaOstream::EMaskType kMaskType = CFastaOstream::eSoftMask;
CSeqDB::TSequenceRanges masked_ranges;
x_ExtractMaskingData(masked_ranges, m_FiltAlgoId);
if (!masked_ranges.empty()) {
CRef<CSeq_loc> masks(new CSeq_loc);
ITERATE(CSeqDB::TSequenceRanges, itr, masked_ranges) {
CRef<CSeq_loc> mask(new CSeq_loc(*seqid, itr->first, itr->second -1));
masks->SetMix().Set().push_back(mask);
}
fasta.SetMask(kMaskType, masks);
}
try { fasta.Write(*m_Bioseq, range); }
catch (const CObjmgrUtilException& e) {
if (e.GetErrCode() == CObjmgrUtilException::eBadLocation) {
NCBI_THROW(CInvalidDataException, eInvalidRange,
"Invalid sequence range");
}
}
return out.str();
}
int CBlastDBExtractor::x_ExtractTaxId()
{
x_SetGi();
#if 0
if (m_Bioseq.NotEmpty()) {
// try to use the defline first to avoid re-reading it from the database
x_InitDefline();
ITERATE(CBlast_def_line_set::Tdata, bd, m_Defline->Get()) {
ITERATE(CBlast_def_line::TSeqid, id, ((*bd)->GetSeqid())) {
if ((*id)->IsGi()) {
if ((*id)->GetGi() == m_Gi) {
return (*bd)->GetTaxid();
} else {
break;
}
}
}
}
}
#endif
if (m_Gi) {
map <int, int> gi2taxid;
m_BlastDb.GetTaxIDs(m_Oid, gi2taxid);
return gi2taxid[m_Gi];
}
// for database without Gi:
vector <int> taxid;
m_BlastDb.GetTaxIDs(m_Oid, taxid);
return taxid.size() ? taxid[0] : 0;
}
void
CBlastDBExtractor::x_ExtractMaskingData(CSeqDB::TSequenceRanges &ranges,
int algo_id)
{
ranges.clear();
if (algo_id != -1) {
m_BlastDb.GetMaskData(m_Oid, algo_id, ranges);
}
}
void CBlastDBExtractor::SetConfig(TSeqRange range, objects::ENa_strand strand,
int filt_algo_id)
{
m_OrigSeqRange = range;
m_Strand = strand;
m_FiltAlgoId = filt_algo_id;
}
END_NCBI_SCOPE
| 31.040359 | 98 | 0.616729 | [
"vector",
"transform"
] |
918557964070dae69dd51ac8f9c51f1fcb652751 | 1,343 | cpp | C++ | src/render/materials.cpp | hydrocarborane/polyscope | bee34c22cd7ac1b1e01686b55b7b8ceeee20d2fe | [
"MIT"
] | 930 | 2018-02-19T16:38:29.000Z | 2022-03-30T22:16:01.000Z | src/render/materials.cpp | hydrocarborane/polyscope | bee34c22cd7ac1b1e01686b55b7b8ceeee20d2fe | [
"MIT"
] | 142 | 2018-02-19T16:14:28.000Z | 2022-03-25T13:51:08.000Z | src/render/materials.cpp | hydrocarborane/polyscope | bee34c22cd7ac1b1e01686b55b7b8ceeee20d2fe | [
"MIT"
] | 92 | 2018-05-13T01:41:04.000Z | 2022-03-28T03:26:44.000Z | // Copyright 2017-2019, Nicholas Sharp and the Polyscope contributors. http://polyscope.run.
#include "polyscope/render/materials.h"
#include "polyscope/messages.h"
#include "polyscope/render/engine.h"
#include "polyscope/render/material_defs.h"
#include "imgui.h"
#include "stb_image.h"
namespace polyscope {
namespace render {
bool buildMaterialOptionsGui(std::string& mat) {
if (ImGui::BeginMenu("Material")) {
for (const std::unique_ptr<Material>& o : render::engine->materials) {
bool selected = (o->name == mat);
std::string fancyName = o->name;
if(o->supportsRGB) {
fancyName += " (rgb)";
}
if (ImGui::MenuItem(fancyName.c_str(), NULL, selected)) {
mat = o->name;
ImGui::EndMenu();
return true;
}
}
ImGui::EndMenu();
}
return false;
}
} // namespace render
void loadBlendableMaterial(std::string matName, std::array<std::string, 4> filenames) {
render::engine->loadBlendableMaterial(matName, filenames);
}
void loadBlendableMaterial(std::string matName, std::string filenameBase, std::string filenameExt) {
render::engine->loadBlendableMaterial(matName, filenameBase, filenameExt);
}
void loadStaticMaterial(std::string matName, std::string filename) {
render::engine->loadStaticMaterial(matName, filename);
}
} // namespace polyscope
| 27.979167 | 100 | 0.69248 | [
"render"
] |
918a5a398d5dadef1b2e7d779c7b2b8d5516f9fb | 2,617 | cpp | C++ | Tests/MeshLib/TestElementStatus.cpp | garibay-j/ogs | 33340f22e9dbe0b7ccc60f0c828c2a528737c81e | [
"BSD-3-Clause"
] | null | null | null | Tests/MeshLib/TestElementStatus.cpp | garibay-j/ogs | 33340f22e9dbe0b7ccc60f0c828c2a528737c81e | [
"BSD-3-Clause"
] | null | null | null | Tests/MeshLib/TestElementStatus.cpp | garibay-j/ogs | 33340f22e9dbe0b7ccc60f0c828c2a528737c81e | [
"BSD-3-Clause"
] | null | null | null | /**
* \file
* \author Karsten Rink
* \date 2013-03-14
* \brief Tests for ElementStatus class
*
* \copyright
* Copyright (c) 2012-2022, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*/
#include <gtest/gtest.h>
#include <memory>
#include "MeshLib/ElementStatus.h"
#include "MeshLib/Elements/Element.h"
#include "MeshLib/Mesh.h"
#include "MeshLib/MeshGenerators/MeshGenerator.h"
#include "MeshLib/Node.h"
TEST(MeshLib, ElementStatus)
{
const unsigned width(100);
const unsigned elements_per_side(20);
auto const mesh = std::unique_ptr<MeshLib::Mesh>{
MeshLib::MeshGenerator::generateRegularQuadMesh(width,
elements_per_side)};
auto* const material_id_properties =
mesh->getProperties().createNewPropertyVector<int>(
"MaterialIDs", MeshLib::MeshItemType::Cell);
ASSERT_NE(nullptr, material_id_properties);
material_id_properties->resize(mesh->getNumberOfElements());
const std::vector<MeshLib::Element*> elements(mesh->getElements());
for (unsigned i = 0; i < elements_per_side; ++i)
{
for (unsigned j = 0; j < elements_per_side; ++j)
{
(*material_id_properties)[elements[i * elements_per_side + j]
->getID()] = i;
}
}
{
// all elements and nodes active
MeshLib::ElementStatus status(mesh.get());
ASSERT_EQ(elements.size(), status.getNumberOfActiveElements());
ASSERT_EQ(mesh->getNumberOfNodes(), status.getNumberOfActiveNodes());
}
{
// set material 1 to false
std::vector<int> inactiveMat{1};
MeshLib::ElementStatus status(mesh.get(), inactiveMat);
ASSERT_EQ(elements.size() - elements_per_side,
status.getNumberOfActiveElements());
}
{
// set material 0 and 1 to false
std::vector<int> inactiveMat{0, 1};
MeshLib::ElementStatus status(mesh.get(), inactiveMat);
ASSERT_EQ(elements.size() - (2 * elements_per_side),
status.getNumberOfActiveElements());
// active elements
auto& active_elements(status.getActiveElements());
ASSERT_EQ(active_elements.size(), status.getNumberOfActiveElements());
// active nodes
auto& active_nodes(status.getActiveNodes());
ASSERT_EQ(active_nodes.size(), status.getNumberOfActiveNodes());
}
}
| 32.7125 | 78 | 0.628582 | [
"mesh",
"vector"
] |
918c22e7aba173714f76ccfbc66cdf00cd833528 | 1,095 | cpp | C++ | LeetCode/HouseRobber.cpp | Anvesh-Chennupati/DsAlgo | fd8ddd264e14f89f86e339c684e1f7a553507a35 | [
"MIT"
] | null | null | null | LeetCode/HouseRobber.cpp | Anvesh-Chennupati/DsAlgo | fd8ddd264e14f89f86e339c684e1f7a553507a35 | [
"MIT"
] | null | null | null | LeetCode/HouseRobber.cpp | Anvesh-Chennupati/DsAlgo | fd8ddd264e14f89f86e339c684e1f7a553507a35 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
int maxProfitR(vector<int> houses)
{
vector<int> tempsol(houses.size(), 0);
for (int i = 0; i < houses.size(); i++)
{
int tempprofit = houses[i];
for (int j = i + 2; j < houses.size(); j += 2)
{
tempprofit += houses[j];
}
tempsol[i] = tempprofit;
}
return *max_element(tempsol.begin(), tempsol.end());
}
int maxProfitDP(vector<int> nums)
{
int include = 0;
int exclude = 0;
for (int j = 0; j < nums.size(); j++)
{
int temp = include;
include = nums[j] + exclude;
exclude = max(exclude, temp);
}
return max(include, exclude);
}
};
int main(int argc, char const *argv[])
{
vector<int> houses = {2, 7, 9, 3, 1};
Solution s1;
cout << "\nMax profitR: " << s1.maxProfitR(houses);
cout << "\nMax profitDP: " << s1.maxProfitDP(houses);
return 0;
} | 22.346939 | 60 | 0.499543 | [
"vector"
] |
9261be996bd662d98067112d662e7927e55eec51 | 2,789 | cpp | C++ | Alignment/MuonAlignment/test/TestAlign.cpp | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | Alignment/MuonAlignment/test/TestAlign.cpp | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | Alignment/MuonAlignment/test/TestAlign.cpp | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | // -*- C++ -*-
//
// Package: TestAlign
// Class: TestAlign
//
//
// Description: Module to test the Alignment software
//
//
// system include files
#include <string>
// user include files
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "Alignment/MuonAlignment/interface/MuonAlignment.h"
#include "Alignment/MuonAlignment/interface/AlignableMuon.h"
#include "DataFormats/GeometrySurface/interface/Surface.h"
#include <vector>
//
//
// class declaration
//
class TestAlign : public edm::EDAnalyzer {
public:
explicit TestAlign(const edm::ParameterSet&);
virtual ~TestAlign();
virtual void analyze(const edm::Event&, const edm::EventSetup&);
private:
//typedef Surface::RotationType RotationType;
//typedef Surface::PositionType PositionType;
};
//
// constructors and destructor
//
TestAlign::TestAlign(const edm::ParameterSet& iConfig) { edm::LogInfo("MuonAlignment") << "Starting!"; }
TestAlign::~TestAlign() { edm::LogInfo("MuonAlignment") << "Ending!"; }
void TestAlign::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
// Instantiate the helper class
MuonAlignment align(iSetup);
// Get the AlignableMuon pointer
AlignableMuon* theAlignableMuon = align.getAlignableMuon();
// Apply alignment
std::vector<double> displacement;
displacement.push_back(1.0);
displacement.push_back(0.0);
displacement.push_back(0.0);
std::vector<double> rotation;
rotation.push_back(0.0);
rotation.push_back(0.0);
rotation.push_back(1.64);
// Loop over DT chamber to apply alignment corrections
for (const auto& iter : theAlignableMuon->DTChambers()) {
// Print inital position/orientation
align::GlobalPoint pos_i = iter->globalPosition();
align::RotationType dir_i = iter->globalRotation();
std::cout << "Initial pos: x=" << pos_i.x() << ", y=" << pos_i.y() << ", z=" << pos_i.z() << std::endl;
std::cout << "Initial ori: x=" << dir_i.xx() << ", y=" << dir_i.yy() << ", z=" << dir_i.zz() << std::endl;
// Move DT chamber
DetId detid = iter->geomDetId();
align.moveAlignableGlobalCoord(detid, displacement, rotation);
// Print final position/orientation
align::GlobalPoint pos_f = iter->globalPosition();
align::RotationType dir_f = iter->globalRotation();
std::cout << "Final pos: x=" << pos_f.x() << ", y=" << pos_f.y() << ", z=" << pos_f.z() << std::endl;
std::cout << "Final ori: x=" << dir_f.xx() << ", y=" << dir_f.yy() << ", z=" << dir_f.zz() << std::endl;
std::cout << "------------------------" << std::endl;
}
// Saves to DB
// align.saveToDB();
}
//define this as a plug-in
DEFINE_FWK_MODULE(TestAlign);
| 29.052083 | 112 | 0.661527 | [
"vector"
] |
9261c970769320f8c17fa0606d3a12d03d76f974 | 397 | cpp | C++ | code/remove-duplicates-from-sorted-array-ii/remove_duplicates_from_sorted_array_ii.cpp | shenhuaze/leetcode-cpp | 2a70f33697fbc562207e1ed3bbe8d038512628be | [
"MIT"
] | 1 | 2019-06-17T04:37:39.000Z | 2019-06-17T04:37:39.000Z | code/remove-duplicates-from-sorted-array-ii/remove_duplicates_from_sorted_array_ii.cpp | shenhuaze/leetcode-cpp | 2a70f33697fbc562207e1ed3bbe8d038512628be | [
"MIT"
] | null | null | null | code/remove-duplicates-from-sorted-array-ii/remove_duplicates_from_sorted_array_ii.cpp | shenhuaze/leetcode-cpp | 2a70f33697fbc562207e1ed3bbe8d038512628be | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int RemoveDuplicates(vector<int>& nums) {
int index = 0;
for (int num: nums) {
if (index < 2 || num > nums[index - 2]) {
nums[index] = num;
index += 1;
}
}
return index;
}
int main() {
vector<int> nums = {1, 1, 1, 2, 2, 3};
cout << RemoveDuplicates(nums);
return 0;
} | 18.904762 | 49 | 0.518892 | [
"vector"
] |
92662aa5f03714e401e3340c61ad28a4010ba017 | 9,628 | cc | C++ | lite/backends/nnadapter/nnadapter/driver/imagination_nna/converter/converter.cc | chiaitian/Paddle-Lite | 07bfd0705b8351f0e6c9d95bcee71e4ac011fa62 | [
"Apache-2.0"
] | 3 | 2021-06-17T11:00:13.000Z | 2021-08-10T10:28:59.000Z | lite/backends/nnadapter/nnadapter/driver/imagination_nna/converter/converter.cc | chiaitian/Paddle-Lite | 07bfd0705b8351f0e6c9d95bcee71e4ac011fa62 | [
"Apache-2.0"
] | 1 | 2021-05-26T05:19:38.000Z | 2021-05-26T05:19:38.000Z | lite/backends/nnadapter/nnadapter/driver/imagination_nna/converter/converter.cc | yingshengBD/Paddle-Lite | eea59b66f61bb2acad471010c9526eeec43a15ca | [
"Apache-2.0"
] | 1 | 2021-12-03T10:07:54.000Z | 2021-12-03T10:07:54.000Z | // Copyright (c) 2019 PaddlePaddle 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 "driver/imagination_nna/converter/converter.h"
#include <unistd.h>
#include <algorithm>
#include <limits>
#include "utility/debug.h"
#include "utility/logging.h"
#include "utility/modeling.h"
#include "utility/string.h"
#include "utility/utility.h"
namespace nnadapter {
namespace imagination_nna {
#define REGISTER_CONVERTER(__op_type__, __func_name__) \
extern int __func_name__(Converter* converter, hal::Operation* operation);
#include "driver/imagination_nna/converter/all.h" // NOLINT
#undef __NNADAPTER_DRIVER_IMAGINATION_NNA_CONVERTER_ALL_H__
#undef REGISTER_CONVERTER
int Converter::Apply(hal::Model* model) {
// Convert the NNAdapter operations to the imgdnn operators
std::vector<hal::Operation*> operations =
SortOperationsInTopologicalOrder(model);
for (auto operation : operations) {
NNADAPTER_VLOG(5) << "Converting " << OperationTypeToString(operation->type)
<< " ...";
switch (operation->type) {
#define REGISTER_CONVERTER(__op_type__, __func_name__) \
case NNADAPTER_##__op_type__: \
__func_name__(this, operation); \
break;
#include "driver/imagination_nna/converter/all.h" // NOLINT
#undef __NNADAPTER_DRIVER_IMAGINATION_NNA_CONVERTER_ALL_H__
#undef REGISTER_CONVERTER
default:
NNADAPTER_LOG(FATAL) << "Unsupported operation("
<< OperationTypeToString(operation->type)
<< ") is found.";
break;
}
}
return NNADAPTER_NO_ERROR;
}
imgdnn_tensor Converter::GetMappedTensor(hal::Operand* operand) {
auto it = tensors_->find(operand);
if (it != tensors_->end()) {
return it->second.back();
}
return nullptr;
}
imgdnn_tensor Converter::UpdateTensorMap(hal::Operand* operand,
imgdnn_tensor tensor) {
auto it = tensors_->find(operand);
if (it == tensors_->end()) {
auto result =
tensors_->insert(std::make_pair(operand, std::vector<imgdnn_tensor>()));
NNADAPTER_CHECK(result.second);
it = result.first;
}
it->second.push_back(tensor);
return tensor;
}
imgdnn_tensor Converter::AddTensor(int32_t* dimensions_data,
uint32_t dimensions_count,
imgdnn_type type,
const float* quant_scales,
const int32_t* zero_point,
uint32_t quant_scale_count,
uint32_t quant_channel_dim,
void* buffer) {
imgdnn_tensor tensor = nullptr;
imgdnn_tensor_descriptor desc;
desc.type = type;
NNADAPTER_CHECK(dimensions_data);
NNADAPTER_CHECK_GT(dimensions_count, 0);
ConvertToImgdnnDimensions(
dimensions_data, dimensions_count, desc.size, &desc.dimensions);
if (quant_scales && quant_scale_count > 0) {
// Quantization types
if (quant_scale_count > 1) {
// Symmetric and asymmetric per-channel quantization
if (zero_point) {
// Asymmetric per-channel quantization
NNADAPTER_CHECK_EQ(type, IMGDNN_TYPE_QPA_U8);
} else {
// Symmetric per-channel quantization
NNADAPTER_CHECK_EQ(type, IMGDNN_TYPE_QPA_I8);
}
desc.quant_param.per_axis = imgdnnCreatePerAxisQuantParam(
quant_channel_dim, quant_scale_count, quant_scales, zero_point);
NNADAPTER_CHECK(desc.quant_param.per_axis != nullptr);
tensor = buffer ? imgdnn_mgr_->CreateFixedInputTensor(&desc, buffer, true)
: imgdnn_mgr_->CreateInputTensor(&desc);
imgdnnDestroyPerAxisQuantParam(desc.quant_param.per_axis);
} else {
desc.quant_param.scale = quant_scales[0];
if (zero_point) {
// Asymmetric per-layer quantization
NNADAPTER_CHECK_EQ(type, IMGDNN_TYPE_Q_U8);
desc.quant_param.zero_point = zero_point[0];
} else {
// Symmetric per-layer quantization
NNADAPTER_CHECK_EQ(type, IMGDNN_TYPE_Q_I8);
// zeroPoint = 0
}
tensor = buffer ? imgdnn_mgr_->CreateFixedInputTensor(&desc, buffer, true)
: imgdnn_mgr_->CreateInputTensor(&desc);
}
} else {
// TODO(hong19860320) Supports the normal types, such as float, int32 etc.
NNADAPTER_CHECK_EQ(type, IMGDNN_TYPE_I32);
NNADAPTER_CHECK(buffer);
tensor = imgdnn_mgr_->CreateFixedInputTensor(&desc, buffer, true);
}
return tensor;
}
imgdnn_tensor Converter::AddTensor(const NNAdapterOperandType* type,
void* buffer,
std::vector<int32_t> dimensions) {
if (dimensions.empty()) {
for (uint32_t i = 0; i < type->dimensions.count; i++) {
dimensions.push_back(type->dimensions.data[i]);
}
}
NNADAPTER_CHECK_EQ(type->layout, NNADAPTER_NCHW);
const float* quant_scales = nullptr;
const int32_t* zero_point = nullptr;
uint32_t quant_scale_count = 0;
uint32_t quant_channel_dim = 0;
switch (type->precision) {
case NNADAPTER_QUANT_UINT8_ASYMM_PER_LAYER:
quant_scales = &type->asymm_per_layer_params.scale;
zero_point = &type->asymm_per_layer_params.zero_point;
quant_scale_count = 1;
break;
case NNADAPTER_QUANT_INT8_SYMM_PER_CHANNEL:
quant_scales = type->symm_per_channel_params.scales;
quant_scale_count = type->symm_per_channel_params.scale_count;
quant_channel_dim = type->symm_per_channel_params.channel_dim;
break;
case NNADAPTER_QUANT_INT32_SYMM_PER_LAYER:
case NNADAPTER_QUANT_INT32_SYMM_PER_CHANNEL:
// Only for bias
NNADAPTER_CHECK(type->lifetime == NNADAPTER_CONSTANT_COPY ||
type->lifetime == NNADAPTER_CONSTANT_REFERENCE);
break;
default:
NNADAPTER_LOG(FATAL) << "Can not add a imgdnn_tensor with precision="
<< OperandPrecisionCodeToString(type->precision)
<< " !";
break;
}
return AddTensor(dimensions.data(),
dimensions.size(),
ConvertToImgdnnPrecision(type->precision),
quant_scales,
zero_point,
quant_scale_count,
quant_channel_dim,
buffer);
}
imgdnn_tensor Converter::AddQuant8ConstantTensor(uint8_t* values,
int32_t* dimensions_data,
uint32_t dimensions_count,
float quant_scale,
int32_t zero_point) {
return AddTensor(dimensions_data,
dimensions_count,
IMGDNN_TYPE_Q_U8,
&quant_scale,
&zero_point,
1,
0,
values);
}
imgdnn_tensor Converter::AddQuant8ConstantTensor(int8_t* values,
int32_t* dimensions_data,
uint32_t dimensions_count,
float* quant_scales,
uint32_t quant_scale_count,
uint32_t quant_channel_dim) {
return AddTensor(dimensions_data,
dimensions_count,
IMGDNN_TYPE_Q_I8,
quant_scales,
nullptr,
quant_scale_count,
quant_channel_dim,
values);
}
imgdnn_tensor Converter::AddQuant32ConstantTensor(int32_t* values,
int32_t* dimensions_data,
uint32_t dimensions_count,
float quant_scale) {
return AddTensor(dimensions_data,
dimensions_count,
IMGDNN_TYPE_I32,
&quant_scale,
nullptr,
1,
0,
values);
}
imgdnn_tensor Converter::ConvertOperand(hal::Operand* operand,
std::vector<int32_t> dimensions) {
if (IsConstantOperand(operand)) {
auto constant_tensor =
AddTensor(&operand->type, operand->buffer, dimensions);
UpdateTensorMap(operand, constant_tensor);
return constant_tensor;
} else if (IsModelInputOperand(operand)) {
auto input_tensor = AddTensor(&operand->type, nullptr, dimensions);
UpdateTensorMap(operand, input_tensor);
return input_tensor;
} else {
NNADAPTER_LOG(FATAL) << "Only constant and model input operands can be "
"converted to imgdnn_tensor!"
<< OperandToString(operand);
}
return nullptr;
}
} // namespace imagination_nna
} // namespace nnadapter
| 38.979757 | 80 | 0.602098 | [
"vector",
"model"
] |
9279ae2b9a77663321b2c5bf3f947ad102c8a4d9 | 3,476 | cpp | C++ | Tests/test_chm_mpm_mix1.cpp | MingAtUWA/SimpleMPM | 46a0e48028b7d6258f452f9cbee6195bb7f6aa41 | [
"MIT"
] | null | null | null | Tests/test_chm_mpm_mix1.cpp | MingAtUWA/SimpleMPM | 46a0e48028b7d6258f452f9cbee6195bb7f6aa41 | [
"MIT"
] | null | null | null | Tests/test_chm_mpm_mix1.cpp | MingAtUWA/SimpleMPM | 46a0e48028b7d6258f452f9cbee6195bb7f6aa41 | [
"MIT"
] | null | null | null | #include "Test_pcp.h"
#include "Model_S2D_CHM_MPM_s_Mix.h"
#include "Step_S2D_CHM_MPM_s_Mix.h"
#include "TimeHistory_Particle_S2D_CHM_Mix_AllPcl.h"
#include "TimeHistory_ConsoleProgressBar.h"
#include "ResultFile_Text.h"
#include "test_sim_core.h"
// 1 by 1 element
void test_chm_mpm_mix1(void)
{
Model_S2D_CHM_MPM_s_Mix model;
size_t elem_x_num = 1;
size_t elem_y_num = 1;
double elem_len = 1.0 / double(elem_y_num);
model.init_mesh(elem_len, elem_x_num, elem_y_num);
double pcl_vol = elem_len * elem_len * 0.5 * 0.5;
model.init_pcl(elem_x_num * elem_y_num * 4,
0.3, pcl_vol * (1.0 - 0.3) * 2650.0, 2650.0, 1000.0,
1.0e3, 0.3, 50.0e3, 1.0e-4, 1.0);
size_t k = 0;
for (size_t j = 0; j < elem_y_num * 2; ++j)
for (size_t i = 0; i < elem_x_num * 2; ++i)
{
Particle_S2D_CHM_Mix &pcl = model.pcls[k];
pcl.x = (0.25 + double(i) * 0.5) * elem_len;
pcl.y = (0.25 + double(j) * 0.5) * elem_len;
++k;
}
model.ty_num = elem_x_num * 2;
model.tys = new TractionBC_MPM[model.ty_num];
for (size_t i = 0; i < model.ty_num; ++i)
{
model.tys[i].pcl_id = (elem_y_num * 2 - 1) * elem_x_num * 2 + i;
model.tys[i].t = -10.0 * 0.5 * elem_len;
}
model.vsx_num = model.node_y_num * 2;
model.vsxs = new VelocityBC[model.vsx_num];
for (size_t i = 0; i < model.node_y_num; i++)
{
model.vsxs[i].node_id = i * model.node_x_num;
model.vsxs[i].v = 0.0;
model.vsxs[i + model.node_y_num].node_id = (i + 1) * model.node_x_num - 1;
model.vsxs[i + model.node_y_num].v = 0.0;
}
model.vsy_num = model.node_x_num;
model.vsys = new VelocityBC[model.vsy_num];
for (size_t i = 0; i < model.vsy_num; i++)
{
model.vsys[i].node_id = i;
model.vsys[i].v = 0.0;
}
model.vfx_num = model.node_y_num * 2;
model.vfxs = new VelocityBC[model.vfx_num];
for (size_t i = 0; i < model.node_y_num; i++)
{
model.vfxs[i].node_id = i * model.node_x_num;
model.vfxs[i].v = 0.0;
model.vfxs[i + model.node_y_num].node_id = (i + 1) * model.node_x_num - 1;
model.vfxs[i + model.node_y_num].v = 0.0;
}
model.vfy_num = model.node_x_num * 2;
model.vfys = new VelocityBC[model.vfy_num];
for (size_t i = 0; i < model.node_x_num; i++)
{
model.vfys[i].node_id = i;
model.vfys[i].v = 0.0;
model.vfys[i+model.node_x_num].node_id = model.node_x_num * (model.node_y_num - 1) + i;
model.vfys[i+model.node_x_num].v = 0.0;
}
ResultFile_Text res_file;
res_file.set_filename("res_file");
res_file.output_model_state(model);
TimeHistory_Particle_S2D_CHM_Mix_AllPcl th1;
th1.set_name("test_out1");
th1.set_interval_num(5);
th1.set_if_output_initial_state(true);
Particle_Field_2D_CHM fld1[4] = {
Particle_Field_2D_CHM::x,
Particle_Field_2D_CHM::y,
Particle_Field_2D_CHM::vol,
Particle_Field_2D_CHM::p,
};
for (size_t i = 0; i < sizeof(fld1) / sizeof(fld1[0]); ++i)
th1.add_field(fld1[i]);
TimeHistory_ConsoleProgressBar th2;
// step1
Step_S2D_CHM_MPM_s_Mix step1;
step1.set_name("initial_step");
step1.set_model(&model);
step1.set_result_file(&res_file);
step1.set_step_time(5.0e-4);
step1.set_dt(1.0e-4);
step1.add_output(&th1);
//step1.add_output(&th2);
step1.solve();
//// step2
//Step_S2D_CHM_MPM_s_GIMP step2;
//step2.set_name("consolidation_step");
//step2.set_prev_step(&step1);
//step2.set_step_time(30.0); // total_time
//step2.set_dt(1.0e-4);
//// free drainage bcs
//model.afy_num = model.node_x_num;
//th1.set_interval_num(30);
//step2.add_output(&th1);
//step2.add_output(&th2);
//step2.solve();
} | 27.15625 | 89 | 0.678078 | [
"model"
] |
927f4db42ebb9bf6d246c8236998dbe82f029be5 | 5,112 | cpp | C++ | QuantMate/ChessFigure.cpp | IKholopov/QuantMate | 89eb0f9a51e051d349e88bbcecc15b06cb114269 | [
"Apache-2.0"
] | null | null | null | QuantMate/ChessFigure.cpp | IKholopov/QuantMate | 89eb0f9a51e051d349e88bbcecc15b06cb114269 | [
"Apache-2.0"
] | null | null | null | QuantMate/ChessFigure.cpp | IKholopov/QuantMate | 89eb0f9a51e051d349e88bbcecc15b06cb114269 | [
"Apache-2.0"
] | null | null | null | #include "ChessFigure.h"
#include <assert.h>
#include "BitmapResource.h"
CChessFigure::CChessFigure(Figure figure, FigureColor color, Coordinates position,
float probability, float velocity): quantObject(new CQuantObject())
{
this->figure = figure;
this->color = color;
assert(position.X >= 0 && position.X < 8);
assert(position.Y >= 0 && position.Y < 8);
this->boardPosition = position;
this->probability = probability;
this->velocity = velocity;
this->scale = 1.0f;
quantObject->AddState(this);
}
CChessFigure::CChessFigure(Figure figure, FigureColor color, Coordinates position,
std::shared_ptr<CQuantObject> quantObject, float probability, float velocity): quantObject(quantObject)
{
this->figure = figure;
this->color = color;
assert(position.X >= 0 && position.X < 8);
assert(position.Y >= 0 && position.Y < 8);
this->boardPosition = position;
this->probability = probability;
this->velocity = velocity;
this->scale = 1.0f;
this->quantObject->AddState(this);
}
CChessFigure::~CChessFigure()
{
}
void CChessFigure::SetBoardPosition(Coordinates position)
{
oldBoardPosition = boardPosition;
boardPosition = position;
}
void CChessFigure::SetSpritePosition(Coordinates position)
{
newSpritePosition.X = position.X;
newSpritePosition.Y = position.Y;
}
void CChessFigure::SetSelected()
{
sprite->SetScale(1.2f);
}
void CChessFigure::SetUnselected()
{
sprite->SetScale(1.0f);
}
void CChessFigure::ResetProbability()
{
this->probability = 1.0f;
}
Coordinates CChessFigure::GetBoardPosition()
{
return boardPosition;
}
Coordinates CChessFigure::GetOldBoardPosition()
{
return oldBoardPosition;
}
CChessFigure::FigureColor CChessFigure::GetColor()
{
return color;
}
CChessFigure::Figure CChessFigure::GetFigure()
{
return figure;
}
CQuantObject* CChessFigure::GetQuantObject()
{
return quantObject.get();
}
void CChessFigure::Render(HDC hdc)
{
auto graphics = Gdiplus::Graphics::FromHDC(hdc);
Gdiplus::RectF rect;
sprite->GetBounds(rect);
Gdiplus::GraphicsPath pathRed;
Gdiplus::GraphicsPath pathBlue;
pathBlue.AddArc(rect, -90, 360);
pathRed.AddArc(rect, -90, 360 * probability);
Gdiplus::Pen penRed(Gdiplus::Color::Red, FIGURE_CHART_THICKNESS);
Gdiplus::Pen penBlue(Gdiplus::Color::Blue, FIGURE_CHART_THICKNESS);
graphics->DrawPath(&penBlue, &pathBlue);
graphics->DrawPath(&penRed, &pathRed);
delete graphics;
sprite->Draw(hdc);
}
bool CChessFigure::OnTimerTick()
{
if( newSpritePosition.X != sprite->GetX() || newSpritePosition.Y != sprite->GetY() ){
int deltaX = int((newSpritePosition.X - sprite->GetX()) / std::sqrt(
std::pow(newSpritePosition.X - sprite->GetX(), 2) +
std::pow(newSpritePosition.Y - sprite->GetY(), 2)) * velocity);
int deltaY = int((newSpritePosition.Y - sprite->GetY()) / std::sqrt(
std::pow(newSpritePosition.X - sprite->GetX(), 2) +
std::pow(newSpritePosition.Y - sprite->GetY(), 2)) * velocity);
bool useDelta = std::abs(deltaX) < std::abs(newSpritePosition.X - sprite->GetX()) ||
std::abs(deltaY) < std::abs(newSpritePosition.Y - sprite->GetY());
sprite->SetX(useDelta ? sprite->GetX() + deltaX : newSpritePosition.X);
sprite->SetY(useDelta ? sprite->GetY() + deltaY : newSpritePosition.Y);
return true;
}
return false;
}
void CChessFigure::FetchResources(CResourceManager & manager)
{
IResource* resource;
switch( this->figure ) {
case PAWN:
if( color == WHITE ) {
resource = manager.GetResource(CQuantMateResources::PAWN_WHITE);
} else {
resource = manager.GetResource(CQuantMateResources::PAWN_BLACK);
}
break;
case ROOK:
if( color == WHITE ) {
resource = manager.GetResource(CQuantMateResources::ROOK_WHITE);
} else {
resource = manager.GetResource(CQuantMateResources::ROOK_BLACK);
}
break;
case BISHOP:
if( color == WHITE ) {
resource = manager.GetResource(CQuantMateResources::BISHOP_WHITE);
} else {
resource = manager.GetResource(CQuantMateResources::BISHOP_BLACK);
}
break;
case KNIGHT:
if( color == WHITE ) {
resource = manager.GetResource(CQuantMateResources::KNIGHT_WHITE);
} else {
resource = manager.GetResource(CQuantMateResources::KNIGHT_BLACK);
}
break;
case QUEEN:
if( color == WHITE ) {
resource = manager.GetResource(CQuantMateResources::QUEEN_WHITE);
} else {
resource = manager.GetResource(CQuantMateResources::QUEEN_BLACK);
}
break;
case KING:
if( color == WHITE ) {
resource = manager.GetResource(CQuantMateResources::KING_WHITE);
} else {
resource = manager.GetResource(CQuantMateResources::KING_BLACK);
}
break;
default:
throw std::logic_error("Invalid figure\n");
return;
}
sprite = std::unique_ptr<CSprite>(new CSprite(static_cast<CBitmapResource*>(resource)->GetBitmap()));
}
float CChessFigure::GetProbability()
{
return probability;
}
IQuantState* CChessFigure::Split()
{
this->probability /= 2.0f;
auto newState = new CChessFigure(this->figure, this->color, this->boardPosition, this->quantObject, this->probability, this->velocity);
newState->sprite = std::unique_ptr<CSprite>(new CSprite(*(this->sprite)));
return newState;
}
| 26.764398 | 136 | 0.717919 | [
"render"
] |
927f660e9e97b0507b9b8888efef7a2bde80b578 | 433 | cpp | C++ | leetcode_archived_cpp/LeetCode_89.cpp | Sean10/Algorithm_code | 46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb | [
"BSD-3-Clause"
] | null | null | null | leetcode_archived_cpp/LeetCode_89.cpp | Sean10/Algorithm_code | 46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb | [
"BSD-3-Clause"
] | 7 | 2021-03-19T04:41:21.000Z | 2021-10-19T15:46:36.000Z | leetcode_archived_cpp/LeetCode_89.cpp | Sean10/Algorithm_code | 46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb | [
"BSD-3-Clause"
] | null | null | null | class Solution {
public:
vector<int> grayCode(int n) {
vector<int> ans;
bitset<32> temp;
helper(temp ,ans, n);
return ans;
}
void helper(bitset<32>& temp, vector<int>& ans, int n)
{
if(n == 0)
{
ans.push_back(temp.to_ulong());
return ;
}
helper(temp, ans, n-1);
temp.flip(n-1);
helper(temp, ans, n-1);
}
};
| 18.826087 | 58 | 0.459584 | [
"vector"
] |
9284f4488622503da6a63bfee134c7e9664fb332 | 13,098 | hpp | C++ | 3rdparty/GPSTk/core/lib/GNSSCore/MOPSTropModel.hpp | mfkiwl/ICE | e660d031bb1bcea664db1de4946fd8781be5b627 | [
"MIT"
] | 50 | 2019-10-12T01:22:20.000Z | 2022-02-15T23:28:26.000Z | 3rdparty/GPSTk/core/lib/GNSSCore/MOPSTropModel.hpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | null | null | null | 3rdparty/GPSTk/core/lib/GNSSCore/MOPSTropModel.hpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | 14 | 2019-11-05T01:50:29.000Z | 2021-08-06T06:23:44.000Z | //============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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 3.0 of the License, or
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#ifndef MOPS_TROP_MODEL_HPP
#define MOPS_TROP_MODEL_HPP
#include "GCATTropModel.hpp"
namespace gpstk
{
/** Tropospheric model implemented in the RTCA "Minimum Operational
* Performance Standards" (MOPS), version C.
*
* This model is described in the RTCA "Minimum Operational Performance
* Standards" (MOPS), version C (RTCA/DO-229C), in Appendix A.4.2.4.
* Although originally developed for SBAS systems (EGNOS, WAAS), it may
* be suitable for other uses as well.
*
* This model needs the day of year, satellite elevation (degrees),
* receiver height over mean sea level (meters) and receiver latitude in
* order to start computing.
*
* On the other hand, the outputs are the tropospheric correction (in
* meters) and the sigma-squared of tropospheric delay residual error
* (meters^2).
*
* A typical way to use this model follows:
*
* @code
* MOPSTropModel mopsTM;
* mopsTM.setReceiverLatitude(lat);
* mopsTM.setReceiverHeight(height);
* mopsTM.setDayOfYear(doy);
* @endcode
*
* Once all the basic model parameters are set (latitude, height and day
* of year), then we are able to compute the tropospheric correction as
* a function of elevation:
*
* @code
* trop = mopsTM.correction(elevation);
* @endcode
*
*/
class MOPSTropModel : public GCATTropModel
{
public:
/// Empty constructor
MOPSTropModel(void);
/** Constructor to create a MOPS trop model providing just the height
* of the receiver above mean sea level. The other parameters must be
* set with the appropriate set methods before calling correction
* methods.
*
* @param ht Height of the receiver above mean sea level, in meters.
*/
MOPSTropModel(const double& ht)
{ setReceiverHeight(ht); };
/** Constructor to create a MOPS trop model providing the height of
* the receiver above mean sea level (as defined by ellipsoid model),
* its latitude and the day of year.
*
* @param ht Height of the receiver above mean sea level, in meters.
* @param lat Latitude of receiver, in degrees.
* @param doy Day of year.
*/
MOPSTropModel(const double& ht, const double& lat, const int& doy);
/** Constructor to create a MOPS trop model providing the position of
* the receiver and current time.
*
* @param RX Receiver position.
* @param time Time.
*/
MOPSTropModel(const Position& RX, const CommonTime& time);
/// Return the name of the model
virtual std::string name(void)
{ return std::string("MOPS"); }
/** Compute and return the full tropospheric delay. The receiver
* height, latitude and Day oy Year must has been set before using
* the appropriate constructor or the provided methods.
*
* @param elevation Elevation of satellite as seen at receiver, in
* degrees.
*/
virtual double correction(double elevation) const
throw(InvalidTropModel);
/** Compute and return the full tropospheric delay, given the
* positions of receiver and satellite.
*
* This version is most useful within positioning algorithms, where
* the receiver position may vary; it computes the elevation (and
* other receiver location information as height and latitude) and
* passes them to appropriate methods. You must set time using method
* setReceiverDOY() before calling this method.
*
* @param RX Receiver position.
* @param SV Satellite position.
*/
virtual double correction( const Position& RX,
const Position& SV )
throw(InvalidTropModel);
/** Compute and return the full tropospheric delay, given the
* positions of receiver and satellite and the time tag.
*
* This version is most useful within positioning algorithms, where
* the receiver position may vary; it computes the elevation (and
* other receiver location information as height and latitude) and
* passes them to appropriate methods.
*
* @param RX Receiver position.
* @param SV Satellite position.
* @param tt Time (CommonTime object).
*/
virtual double correction( const Position& RX,
const Position& SV,
const CommonTime& tt )
throw(InvalidTropModel);
/** Compute and return the full tropospheric delay, given the
* positions of receiver and satellite and the day of the year.
*
* This version is most useful within positioning algorithms, where
* the receiver position may vary; it computes the elevation (and
* other receiver location information as height and latitude) and
* passes them to appropriate methods.
*
* @param RX Receiver position.
* @param SV Satellite position.
* @param doy Day of year.
*/
virtual double correction( const Position& RX,
const Position& SV,
const int& doy )
throw(InvalidTropModel);
/** \deprecated
* Compute and return the full tropospheric delay, given the positions
* of receiver and satellite. . You must set time using method
* setReceiverDOY() before calling this method.
*
* @param RX Receiver position in ECEF cartesian coordinates
* (meters).
* @param SV Satellite position in ECEF cartesian coordinates
* (meters).
*/
virtual double correction( const Xvt& RX,
const Xvt& SV )
throw(InvalidTropModel);
/** \deprecated
* Compute and return the full tropospheric delay, given the positions
* of receiver and satellite and the time tag. This version is most
* useful within positioning algorithms, where the receiver position
* may vary; it computes the elevation (and other receiver location
* information as height and latitude) and passes them to appropriate
* methods.
*
* @param RX Receiver position in ECEF cartesian coordinates
* (meters)
* @param SV Satellite position in ECEF cartesian coordinates
* (meters)
* @param tt Time (CommonTime object).
*/
virtual double correction( const Xvt& RX,
const Xvt& SV,
const CommonTime& tt )
throw(InvalidTropModel);
/** \deprecated
* Compute and return the full tropospheric delay, given the positions
* of receiver and satellite and the day of the year. This version is
* most useful within positioning algorithms, where the receiver
* position may vary; it computes the elevation (and other receiver
* location information as height and latitude) and passes them to
* appropriate methods.
*
* @param RX Receiver position in ECEF cartesian coordinates
* (meters)
* @param SV Satellite position in ECEF cartesian coordinates
* (meters)
* @param doy Day of year.
*/
virtual double correction( const Xvt& RX,
const Xvt& SV,
const int& doy )
throw(InvalidTropModel);
/// Compute and return the zenith delay for dry component of the
/// troposphere.
virtual double dry_zenith_delay(void) const
throw(InvalidTropModel);
/// Compute and return the zenith delay for wet component of the
/// troposphere.
virtual double wet_zenith_delay(void) const
throw(InvalidTropModel);
/** This method configure the model to estimate the weather using
* height, latitude and day of year (DOY). It is called automatically
* when setting those parameters.
*/
void setWeather()
throw(InvalidTropModel);
/// In MOPS tropospheric model, this is a dummy method kept here just
/// for consistency.
virtual void setWeather( const double& T,
const double& P,
const double& H )
throw(InvalidParameter) {};
/// In MOPS tropospheric model, this is a dummy method kept here just
/// for consistency.
virtual void setWeather(const WxObservation& wx)
throw(InvalidParameter) {};
/** Define the receiver height; this is required before calling
* correction() or any of the zenith_delay routines.
*
* @param ht Height of the receiver above mean sea level, in meters.
*/
virtual void setReceiverHeight(const double& ht);
/** Define the receiver latitude; this is required before calling
* correction() or any of the zenith_delay routines.
*
* @param lat Latitude of receiver, in degrees.
*/
virtual void setReceiverLatitude(const double& lat);
/** Set the time when tropospheric correction will be computed for, in
* days of the year.
*
* @param doy Day of the year.
*/
virtual void setDayOfYear(const int& doy);
/** Set the time when tropospheric correction will be computed for, in
* days of the year.
*
* @param time Time object.
*/
virtual void setDayOfYear(const CommonTime& time);
/** Convenient method to set all model parameters in one pass.
*
* @param time Time object.
* @param rxPos Receiver position object.
*/
virtual void setAllParameters( const CommonTime& time,
const Position& rxPos );
/** Compute and return the sigma-squared value of tropospheric delay
* residual error (meters^2).
*
* @param elevation Elevation of satellite as seen at receiver,
* in degrees
*/
double MOPSsigma2(double elevation)
throw(InvalidTropModel);
private:
double MOPSHeight;
double MOPSLat;
int MOPSTime;
bool validHeight;
bool validLat;
bool validTime;
Matrix<double> avr;
Matrix<double> svr;
Vector<double> fi0;
Vector<double> MOPSParameters;
// The MOPS tropospheric model needs to compute several extra
// parameters
virtual void prepareParameters(void) throw(InvalidTropModel);
// The MOPS tropospheric model uses several predefined data tables
virtual void prepareTables(void);
};
}
#endif
| 37.422857 | 79 | 0.584746 | [
"object",
"vector",
"model"
] |
928cef41633704cad2aa62c8921754455109b55f | 13,153 | cc | C++ | omaha/internal/chrome_recovery_improved/command_line.cc | r3yn0ld4/omaha | 05eeb606c433b7d0622dc95a10afd0c8d7af11b6 | [
"Apache-2.0"
] | 1,975 | 2015-07-03T07:00:50.000Z | 2022-03-31T20:04:04.000Z | omaha/internal/chrome_recovery_improved/command_line.cc | r3yn0ld4/omaha | 05eeb606c433b7d0622dc95a10afd0c8d7af11b6 | [
"Apache-2.0"
] | 277 | 2015-07-18T00:13:30.000Z | 2022-03-31T22:18:39.000Z | omaha/internal/chrome_recovery_improved/command_line.cc | r3yn0ld4/omaha | 05eeb606c433b7d0622dc95a10afd0c8d7af11b6 | [
"Apache-2.0"
] | 685 | 2015-07-18T11:24:49.000Z | 2022-03-30T20:50:12.000Z | // Copyright 2017 Google 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.
// ========================================================================
// 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 "omaha/internal/chrome_recovery_improved/command_line.h"
#include <windows.h>
#include <shellapi.h>
#include <algorithm>
#include "base/basictypes.h"
#include "base/string.h"
#include "omaha/base/debug.h"
namespace omaha {
namespace {
#define WHITESPACE_UNICODE \
0x0009, /* CHARACTER TABULATION */ \
0x000A, /* LINE FEED (LF) */ \
0x000B, /* LINE TABULATION */ \
0x000C, /* FORM FEED (FF) */ \
0x000D, /* CARRIAGE RETURN (CR) */ \
0x0020, /* SPACE */ \
0x0085, /* NEXT LINE (NEL) */ \
0x00A0, /* NO-BREAK SPACE */ \
0x1680, /* OGHAM SPACE MARK */ \
0x2000, /* EN QUAD */ \
0x2001, /* EM QUAD */ \
0x2002, /* EN SPACE */ \
0x2003, /* EM SPACE */ \
0x2004, /* THREE-PER-EM SPACE */ \
0x2005, /* FOUR-PER-EM SPACE */ \
0x2006, /* SIX-PER-EM SPACE */ \
0x2007, /* FIGURE SPACE */ \
0x2008, /* PUNCTUATION SPACE */ \
0x2009, /* THIN SPACE */ \
0x200A, /* HAIR SPACE */ \
0x2028, /* LINE SEPARATOR */ \
0x2029, /* PARAGRAPH SEPARATOR */ \
0x202F, /* NARROW NO-BREAK SPACE */ \
0x205F, /* MEDIUM MATHEMATICAL SPACE */ \
0x3000, /* IDEOGRAPHIC SPACE */ \
0
const wchar_t kWhitespaceWide[] = {
WHITESPACE_UNICODE
};
const wchar_t kSwitchTerminator[] = L"--";
const wchar_t kSwitchValueSeparator[] = L"=";
// Since we use a lazy match, make sure that longer versions (like "--") are
// listed before shorter versions (like "-") of similar prefixes.
// By putting slash last, we can control whether it is treaded as a switch
// value by changing the value of switch_prefix_count to be one less than
// the array size.
const wchar_t* const kSwitchPrefixes[] = {L"--", L"-", L"/"};
const size_t switch_prefix_count = arraysize(kSwitchPrefixes);
size_t GetSwitchPrefixLength(const std::wstring& s) {
for (size_t i = 0; i < switch_prefix_count; ++i) {
const std::wstring prefix(kSwitchPrefixes[i]);
if (s.compare(0, prefix.length(), prefix) == 0)
return prefix.length();
}
return 0;
}
// Fills in |switch_string| and |switch_value| if |string| is a switch.
// This will preserve the input switch prefix in the output |switch_string|.
bool IsSwitch(const std::wstring& string,
std::wstring* switch_string,
std::wstring* switch_value) {
switch_string->clear();
switch_value->clear();
const size_t prefix_length = GetSwitchPrefixLength(string);
if (prefix_length == 0 || prefix_length == string.length())
return false;
const size_t equals_position = string.find(kSwitchValueSeparator);
*switch_string = string.substr(0, equals_position);
if (equals_position != std::wstring::npos)
*switch_value = string.substr(equals_position + 1);
return true;
}
bool TrimWhitespace(const std::wstring& input, std::wstring* output) {
if (input.empty()) {
output->clear();
return false;
}
const std::wstring::size_type left = input.find_first_not_of(kWhitespaceWide);
const std::wstring::size_type right = input.find_last_not_of(kWhitespaceWide);
if (left == std::wstring::npos || right == std::wstring::npos) {
output->clear();
return true;
}
*output = input.substr(left, right - left + 1);
return true;
}
// Append switches and arguments, keeping switches before arguments.
void AppendSwitchesAndArguments(CommandLine* command_line,
const CommandLine::StringVector& argv) {
bool parse_switches = true;
for (size_t i = 1; i < argv.size(); ++i) {
std::wstring arg = argv[i];
TrimWhitespace(arg, &arg);
std::wstring switch_string;
std::wstring switch_value;
parse_switches &= (arg != kSwitchTerminator);
if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
command_line->AppendSwitch(switch_string, switch_value);
} else {
command_line->AppendArg(arg);
}
}
}
// Quote a string as necessary for CommandLineToArgvW compatiblity *on Windows*.
std::wstring QuoteForCommandLineToArgvW(const std::wstring& arg,
bool quote_placeholders) {
// We follow the quoting rules of CommandLineToArgvW.
// http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
std::wstring quotable_chars(L" \\\"");
// We may also be required to quote '%', which is commonly used in a command
// line as a placeholder. (It may be substituted for a string with spaces.)
if (quote_placeholders)
quotable_chars.push_back(L'%');
if (arg.find_first_of(quotable_chars) == std::wstring::npos) {
// No quoting necessary.
return arg;
}
std::wstring out;
out.push_back(L'"');
for (size_t i = 0; i < arg.size(); ++i) {
if (arg[i] == '\\') {
// Find the extent of this run of backslashes.
size_t start = i, end = start + 1;
for (; end < arg.size() && arg[end] == '\\'; ++end) {}
size_t backslash_count = end - start;
// Backslashes are escapes only if the run is followed by a double quote.
// Since we also will end the string with a double quote, we escape for
// either a double quote or the end of the string.
if (end == arg.size() || arg[end] == '"') {
// To quote, we need to output 2x as many backslashes.
backslash_count *= 2;
}
for (size_t j = 0; j < backslash_count; ++j)
out.push_back('\\');
// Advance i to one before the end to balance i++ in loop.
i = end - 1;
} else if (arg[i] == '"') {
out.push_back('\\');
out.push_back('"');
} else {
out.push_back(arg[i]);
}
}
out.push_back('"');
return out;
}
} // namespace
CommandLine* CommandLine::current_process_commandline_ = NULL;
CommandLine::CommandLine(NoProgram /*no_program*/)
: argv_(1),
begin_args_(1) {
}
CommandLine::CommandLine(const std::wstring& program)
: argv_(1),
begin_args_(1) {
SetProgram(program);
}
CommandLine::CommandLine(int argc, const wchar_t* const* argv)
: argv_(1),
begin_args_(1) {
InitFromArgv(argc, argv);
}
CommandLine::CommandLine(const StringVector& argv)
: argv_(1),
begin_args_(1) {
InitFromArgv(argv);
}
CommandLine::~CommandLine() {
}
bool CommandLine::Init(int /*argc*/, const wchar_t* const* /*argv*/) {
if (current_process_commandline_) {
// If this is intentional, Reset() must be called first. If we are using
// the shared build mode, we have to share a single object across multiple
// shared libraries.
return false;
}
current_process_commandline_ = new CommandLine(NO_PROGRAM);
current_process_commandline_->ParseFromString(::GetCommandLineW());
return true;
}
void CommandLine::Reset() {
ASSERT1(current_process_commandline_);
delete current_process_commandline_;
current_process_commandline_ = NULL;
}
CommandLine* CommandLine::ForCurrentProcess() {
ASSERT1(current_process_commandline_);
return current_process_commandline_;
}
bool CommandLine::InitializedForCurrentProcess() {
return !!current_process_commandline_;
}
CommandLine CommandLine::FromString(const std::wstring& command_line) {
CommandLine cmd(NO_PROGRAM);
cmd.ParseFromString(command_line);
return cmd;
}
void CommandLine::InitFromArgv(int argc,
const wchar_t* const* argv) {
StringVector new_argv;
for (int i = 0; i < argc; ++i)
new_argv.push_back(argv[i]);
InitFromArgv(new_argv);
}
void CommandLine::InitFromArgv(const StringVector& argv) {
argv_ = StringVector(1);
switches_.clear();
begin_args_ = 1;
SetProgram(argv.empty() ? std::wstring() : std::wstring(argv[0]));
AppendSwitchesAndArguments(this, argv);
}
std::wstring CommandLine::GetProgram() const {
return std::wstring(argv_[0]);
}
void CommandLine::SetProgram(const std::wstring& program) {
TrimWhitespace(program, &argv_[0]);
}
bool CommandLine::HasSwitch(const std::wstring& switch_string) const {
return switches_.find(switch_string) != switches_.end();
}
bool CommandLine::HasSwitch(const wchar_t switch_constant[]) const {
return HasSwitch(std::wstring(switch_constant));
}
std::wstring CommandLine::GetSwitchValue(
const std::wstring& switch_string) const {
SwitchMap::const_iterator it = switches_.find(switch_string);
return it != switches_.end() ? it->second : std::wstring();
}
void CommandLine::AppendSwitch(const std::wstring& switch_string) {
AppendSwitch(switch_string, std::wstring());
}
void CommandLine::AppendSwitch(const std::wstring& switch_string,
const std::wstring& value) {
std::wstring switch_key = std::wstring(
CString(switch_string.c_str()).MakeLower());
std::wstring combined_switch_string(switch_key);
size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
std::pair<SwitchMap::iterator, bool> insertion =
switches_.insert(make_pair(switch_key.substr(prefix_length), value));
if (!insertion.second)
insertion.first->second = value;
// Preserve existing switch prefixes in |argv_|; only append one if necessary.
if (prefix_length == 0)
combined_switch_string = kSwitchPrefixes[0] + combined_switch_string;
if (!value.empty())
combined_switch_string += kSwitchValueSeparator + value;
// Append the switch and update the switches/arguments divider |begin_args_|.
argv_.insert(argv_.begin() + begin_args_++, combined_switch_string);
}
void CommandLine::CopySwitchesFrom(const CommandLine& source,
const wchar_t* const switches[],
size_t count) {
for (size_t i = 0; i < count; ++i) {
if (source.HasSwitch(switches[i]))
AppendSwitch(switches[i], source.GetSwitchValue(switches[i]));
}
}
CommandLine::StringVector CommandLine::GetArgs() const {
// Gather all arguments after the last switch (may include kSwitchTerminator).
StringVector args(argv_.begin() + begin_args_, argv_.end());
// Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
StringVector::iterator switch_terminator =
std::find(args.begin(), args.end(), kSwitchTerminator);
if (switch_terminator != args.end())
args.erase(switch_terminator);
return args;
}
void CommandLine::AppendArg(const std::wstring& value) {
argv_.push_back(value);
}
void CommandLine::AppendArguments(const CommandLine& other,
bool include_program) {
if (include_program)
SetProgram(other.GetProgram());
AppendSwitchesAndArguments(this, other.argv());
}
void CommandLine::ParseFromString(const std::wstring& command_line) {
std::wstring command_line_string;
TrimWhitespace(command_line, &command_line_string);
if (command_line_string.empty())
return;
int num_args = 0;
wchar_t** args = NULL;
args = ::CommandLineToArgvW(command_line_string.c_str(), &num_args);
InitFromArgv(num_args, args);
::LocalFree(args);
}
std::wstring CommandLine::GetCommandLineStringInternal(
bool quote_placeholders) const {
std::wstring string(argv_[0]);
string = QuoteForCommandLineToArgvW(string, quote_placeholders);
std::wstring params(GetArgumentsStringInternal(quote_placeholders));
if (!params.empty()) {
string.append(L" ");
string.append(params);
}
return string;
}
std::wstring CommandLine::GetArgumentsStringInternal(
bool quote_placeholders) const {
std::wstring params;
// Append switches and arguments.
bool parse_switches = true;
for (size_t i = 1; i < argv_.size(); ++i) {
std::wstring arg = argv_[i];
std::wstring switch_string;
std::wstring switch_value;
parse_switches &= arg != kSwitchTerminator;
if (i > 1)
params.append(L" ");
if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
params.append(switch_string);
if (!switch_value.empty()) {
switch_value =
QuoteForCommandLineToArgvW(switch_value, quote_placeholders);
params.append(kSwitchValueSeparator + switch_value);
}
} else {
arg = QuoteForCommandLineToArgvW(arg, quote_placeholders);
params.append(arg);
}
}
return params;
}
} // namespace omaha
| 32.476543 | 80 | 0.662054 | [
"object"
] |
9295ec8ee15407d1839bac31fb3199a4faa07b05 | 11,233 | cc | C++ | app/geant-exporter/geant-exporter-cat.cc | vrpascuzzi/celeritas | 6a8ffc5e6551371fab7cdb5bbb55c60e65f0439f | [
"Apache-2.0",
"MIT"
] | null | null | null | app/geant-exporter/geant-exporter-cat.cc | vrpascuzzi/celeritas | 6a8ffc5e6551371fab7cdb5bbb55c60e65f0439f | [
"Apache-2.0",
"MIT"
] | null | null | null | app/geant-exporter/geant-exporter-cat.cc | vrpascuzzi/celeritas | 6a8ffc5e6551371fab7cdb5bbb55c60e65f0439f | [
"Apache-2.0",
"MIT"
] | null | null | null | //----------------------------------*-C++-*----------------------------------//
// Copyright 2020 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file geant-exporter-cat.cc
//---------------------------------------------------------------------------//
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include "base/Join.hh"
#include "base/Range.hh"
#include "comm/Communicator.hh"
#include "comm/Logger.hh"
#include "comm/ScopedMpiInit.hh"
#include "physics/base/ParticleInterface.hh"
#include "io/RootImporter.hh"
#include "io/GdmlGeometryMap.hh"
using namespace celeritas;
using std::cout;
using std::endl;
using std::setprecision;
using std::setw;
//---------------------------------------------------------------------------//
/*!
* Print particle properties.
*/
void print_particles(const ParticleParams& particles)
{
CELER_LOG(info) << "Loaded " << particles.size() << " particles";
cout << R"gfm(# Particles
| Name | PDG Code | Mass [MeV] | Charge [e] | Decay [1/s] |
| ----------------- | ----------- | ---------- | ---------- | ----------- |
)gfm";
for (auto particle_id : range(ParticleId{particles.size()}))
{
const auto& p = particles.get(particle_id);
// clang-format off
cout << "| "
<< setw(17) << std::left << particles.id_to_label(particle_id) << " | "
<< setw(11) << particles.id_to_pdg(particle_id).get() << " | "
<< setw(10) << setprecision(6) << p.mass().value() << " | "
<< setw(10) << setprecision(3) << p.charge().value() << " | "
<< setw(11) << setprecision(3) << p.decay_constant()
<< " |\n";
// clang-format on
}
cout << endl;
}
//---------------------------------------------------------------------------//
/*!
* Print physics properties.
*/
void print_process(const ImportProcess& proc, const ParticleParams& particles)
{
if (proc.process_type != ImportProcessType::electromagnetic)
{
CELER_LOG(warning) << "Skipping non-EM process "
<< to_cstring(proc.process_class)
<< " for particle " << proc.particle_pdg;
}
cout << "## "
<< particles.id_to_label(particles.find(PDGNumber{proc.particle_pdg}))
<< " " << to_cstring(proc.process_class) << "\n\n";
cout << "Models: "
<< join(proc.models.begin(),
proc.models.end(),
", ",
[](ImportModelClass im) { return to_cstring(im); })
<< "\n";
for (const auto& table : proc.tables)
{
cout << "\n------\n\n" << to_cstring(table.table_type) << ":\n\n";
cout << "| Type | Size | Endpoints ("
<< to_cstring(table.x_units) << ", " << to_cstring(table.y_units)
<< ") |\n"
<< "| ------------- | ----- | "
"------------------------------------------------------------ "
"|\n";
for (const auto& physvec : table.physics_vectors)
{
cout << "| " << setw(13) << std::left
<< to_cstring(physvec.vector_type) << " | " << setw(5)
<< physvec.x.size() << " | (" << setprecision(3) << setw(12)
<< physvec.x.front() << ", " << setprecision(3) << setw(12)
<< physvec.y.front() << ") -> (" << setprecision(3)
<< setw(12) << physvec.x.back() << ", " << setprecision(3)
<< setw(12) << physvec.y.back() << ") |\n";
}
}
cout << endl;
}
//---------------------------------------------------------------------------//
/*!
* Print physics properties.
*/
void print_processes(const std::vector<ImportProcess>& processes,
const ParticleParams& particles)
{
CELER_LOG(info) << "Loaded " << processes.size() << " processes";
// Print summary
cout << "# Processes\n"
<< R"gfm(
| Process | Particle | Models | Tables |
| -------------- | ------------- | ------------------------- | ------------------------ |
)gfm";
for (const ImportProcess& proc : processes)
{
auto pdef_id = particles.find(PDGNumber{proc.particle_pdg});
CELER_ASSERT(pdef_id);
cout << "| " << setw(14) << to_cstring(proc.process_class) << " | "
<< setw(13) << particles.id_to_label(pdef_id) << " | " << setw(25)
<< to_string(
join(proc.models.begin(),
proc.models.end(),
", ",
[](ImportModelClass im) { return to_cstring(im); }))
<< " | " << setw(24)
<< to_string(join(proc.tables.begin(),
proc.tables.end(),
", ",
[](const ImportPhysicsTable& tab) {
return to_cstring(tab.table_type);
}))
<< " |\n";
}
cout << "|\n\n";
// Print details
for (const ImportProcess& proc : processes)
{
print_process(proc, particles);
}
}
//---------------------------------------------------------------------------//
/*!
* Print GDML properties.
*
* TODO: add a print_materials to use material params directly.
*/
void print_geometry(const GdmlGeometryMap& geometry,
const ParticleParams& particles)
{
//// PRINT ELEMENT LIST ////
const auto& element_map = geometry.elemid_to_element_map();
CELER_LOG(info) << "Loaded " << element_map.size() << " elements";
cout << R"gfm(# GDML properties
## Elements
| Element ID | Name | Atomic number | Mass (AMU) |
| ---------- | ---- | ------------- | ---------- |
)gfm";
for (const auto& el_key : element_map)
{
const auto& element = geometry.get_element(el_key.first);
// clang-format off
cout << "| "
<< setw(10) << std::left << el_key.first << " | "
<< setw(4) << element.name << " | "
<< setw(13) << element.atomic_number << " | "
<< setw(10) << element.atomic_mass << " |\n";
// clang-format on
}
cout << endl;
//// PRINT MATERIAL LIST ///
const auto& material_map = geometry.matid_to_material_map();
CELER_LOG(info) << "Loaded " << material_map.size() << " materials";
cout << R"gfm(
## Materials
| Material ID | Name | Composition |
| ----------- | ------------------------------- | ------------------------------- |
)gfm";
for (const auto& mat_key : material_map)
{
const auto& material = geometry.get_material(mat_key.first);
cout << "| " << setw(11) << mat_key.first << " | " << setw(31)
<< material.name << " | " << setw(31)
<< to_string(join(material.elements_fractions.begin(),
material.elements_fractions.end(),
", ",
[&geometry](const auto& key) {
return geometry.get_element(key.first).name;
}))
<< " |\n";
}
cout << endl;
//// PRINT CUTOFF LIST ///
cout << R"gfm(
## Cutoffs per material
| Material ID | Name | Cutoffs [MeV, cm] |
| ----------- | ------------------------------- | ------------------------------- |
)gfm";
std::map<int, std::string> pdg_label;
for (auto particle_id : range(ParticleId{particles.size()}))
{
const int pdg = particles.id_to_pdg(particle_id).get();
const auto& label = particles.id_to_label(particle_id);
pdg_label.insert({pdg, label});
}
for (const auto& mat_key : material_map)
{
const auto& material = geometry.get_material(mat_key.first);
bool is_first_line = true;
for (const auto& cutoff_key : mat_key.second.pdg_cutoff)
{
const std::string label = pdg_label.find(cutoff_key.first)->second;
const std::string str_cuts
= label + ": " + std::to_string(cutoff_key.second.energy)
+ ", " + std::to_string(cutoff_key.second.range);
if (is_first_line)
{
cout << "| " << setw(11) << mat_key.first << " | " << setw(31)
<< material.name << " | " << setw(31) << str_cuts
<< " |\n";
is_first_line = false;
}
else
{
cout << "| | | "
<< setw(31) << str_cuts << " |\n";
}
}
}
cout << endl;
//// PRINT VOLUME AND MATERIAL LIST ////
const auto& volume_material_map = geometry.volid_to_matid_map();
CELER_LOG(info) << "Loaded " << volume_material_map.size() << " volumes";
cout << R"gfm(
## Volumes
| Volume ID | Material ID | Solid Name | Material Name |
| --------- | ----------- | ------------------------------------ | --------------------------- |
)gfm";
for (const auto& key_value : volume_material_map)
{
auto volid = key_value.first;
auto matid = key_value.second;
auto volume = geometry.get_volume(volid);
auto material = geometry.get_material(matid);
// clang-format off
cout << "| "
<< setw(9) << std::left << volid << " | "
<< setw(11) << matid << " | "
<< setw(36) << volume.solid_name << " | "
<< setw(27) << material.name << " |\n";
// clang-format on
}
cout << endl;
}
//---------------------------------------------------------------------------//
/*!
* Dump the contents of a ROOT file writen by geant-exporter.
*/
int main(int argc, char* argv[])
{
ScopedMpiInit scoped_mpi(&argc, &argv);
if (ScopedMpiInit::status() == ScopedMpiInit::Status::initialized
&& Communicator::comm_world().size() > 1)
{
CELER_LOG(critical) << "This app cannot run in parallel";
return EXIT_FAILURE;
}
if (argc != 2)
{
// If number of arguments is incorrect, print help
cout << "Usage: " << argv[0] << " output.root" << endl;
return 2;
}
RootImporter::result_type data;
try
{
RootImporter import(argv[1]);
data = import();
}
catch (const DebugError& e)
{
CELER_LOG(critical) << "Exception while reading ROOT file '" << argv[1]
<< "': " << e.what();
return EXIT_FAILURE;
}
CELER_LOG(info) << "Successfully loaded ROOT file '" << argv[1] << "'";
print_particles(*data.particle_params);
print_processes(data.processes, *data.particle_params);
print_geometry(*data.geometry, *data.particle_params);
return EXIT_SUCCESS;
}
| 34.039394 | 96 | 0.449301 | [
"geometry",
"vector",
"solid"
] |
92995b5f37058b039e11fd0e2eb6e40e21bbcfd7 | 18,186 | cpp | C++ | ui/viewmodel/settings_view.cpp | iambeam/beam | 6dc302a96339463a85cf0f2f15aaf4d4b5d00edb | [
"Apache-2.0"
] | 1 | 2019-09-24T11:33:23.000Z | 2019-09-24T11:33:23.000Z | ui/viewmodel/settings_view.cpp | iambeam/beam | 6dc302a96339463a85cf0f2f15aaf4d4b5d00edb | [
"Apache-2.0"
] | null | null | null | ui/viewmodel/settings_view.cpp | iambeam/beam | 6dc302a96339463a85cf0f2f15aaf4d4b5d00edb | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 The Beam Team
//
// 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 "settings_view.h"
#include "version.h"
#include <QtQuick>
#include <QApplication>
#include <QClipboard>
#include "model/app_model.h"
#include "model/helpers.h"
#include <thread>
#include "wallet/secstring.h"
#include "qml_globals.h"
#include <algorithm>
#include "wallet/litecoin/settings.h"
#include "wallet/qtum/settings.h"
using namespace beam;
using namespace ECC;
using namespace std;
namespace
{
QString AddressToQstring(const io::Address& address) {
if (!address.empty())
{
return str2qstr(address.str());
}
return {};
}
}
SettingsViewModel::SettingsViewModel()
: m_settings{AppModel::getInstance().getSettings()}
, m_isValidNodeAddress{true}
, m_isNeedToCheckAddress(false)
, m_isNeedToApplyChanges(false)
, m_supportedLanguages(WalletSettings::getSupportedLanguages())
{
undoChanges();
connect(&AppModel::getInstance().getNode(), SIGNAL(startedNode()), SLOT(onNodeStarted()));
connect(&AppModel::getInstance().getNode(), SIGNAL(stoppedNode()), SLOT(onNodeStopped()));
connect(AppModel::getInstance().getWallet().get(), SIGNAL(addressChecked(const QString&, bool)), SLOT(onAddressChecked(const QString&, bool)));
LoadBitcoinSettings();
LoadLitecoinSettings();
LoadQtumSettings();
m_timerId = startTimer(CHECK_INTERVAL);
}
void SettingsViewModel::onNodeStarted()
{
emit localNodeRunningChanged();
}
void SettingsViewModel::onNodeStopped()
{
emit localNodeRunningChanged();
}
void SettingsViewModel::onAddressChecked(const QString& addr, bool isValid)
{
if (m_nodeAddress == addr && m_isValidNodeAddress != isValid)
{
m_isValidNodeAddress = isValid;
emit validNodeAddressChanged();
if (m_isNeedToApplyChanges)
{
if (m_isValidNodeAddress)
applyChanges();
m_isNeedToApplyChanges = false;
}
}
}
QString SettingsViewModel::getBtcUser() const
{
return m_bitcoinUser;
}
void SettingsViewModel::setBtcUser(const QString& value)
{
LOG_INFO() << "SetBtcUser " << value.toStdString();
if (value != m_bitcoinUser)
{
m_bitcoinUser = value;
emit btcUserChanged();
emit propertiesChanged();
}
}
QString SettingsViewModel::getBtcPass() const
{
return m_bitcoinPass;
}
void SettingsViewModel::setBtcPass(const QString& value)
{
LOG_INFO() << "setBtcPass ****";
if (value != m_bitcoinPass)
{
m_bitcoinPass = value;
emit btcPassChanged();
emit propertiesChanged();
}
}
QString SettingsViewModel::getBtcNodeAddress() const
{
return m_bitcoinNodeAddress;
}
void SettingsViewModel::setBtcNodeAddress(const QString& value)
{
const auto val = value == "0.0.0.0" ? "" : value;
LOG_INFO() << "setBtcNodeAddress " << val.toStdString();
if (val != m_bitcoinNodeAddress)
{
m_bitcoinNodeAddress = val;
emit btcNodeAddressChanged();
emit propertiesChanged();
}
}
int SettingsViewModel::getBtcFeeRate() const
{
return m_bitcoinFeeRate;
}
void SettingsViewModel::setBtcFeeRate(int value)
{
LOG_INFO() << "setBtcFeeRate " << value;
if (value != m_bitcoinFeeRate)
{
m_bitcoinFeeRate = value;
emit btcFeeRateChanged();
emit propertiesChanged();
}
}
void SettingsViewModel::btcOff()
{
setBtcFeeRate(QMLGlobals::defFeeRateBtc());
setBtcNodeAddress("");
setBtcPass("");
setBtcUser("");
AppModel::getInstance().getBitcoinClient()->GetAsync()->ResetSettings();
}
void SettingsViewModel::applyBtcSettings()
{
bitcoin::BitcoinCoreSettings connectionSettings;
connectionSettings.m_pass = m_bitcoinPass.toStdString();
connectionSettings.m_userName = m_bitcoinUser.toStdString();
if (!m_bitcoinNodeAddress.isEmpty())
{
const std::string address = m_bitcoinNodeAddress.toStdString();
connectionSettings.m_address.resolve(address.c_str());
}
m_bitcoinSettings->SetConnectionOptions(connectionSettings);
m_bitcoinSettings->SetFeeRate(m_bitcoinFeeRate);
AppModel::getInstance().getBitcoinClient()->SetSettings(*m_bitcoinSettings);
}
QString SettingsViewModel::getLtcUser() const
{
return m_litecoinUser;
}
void SettingsViewModel::setLtcUser(const QString& value)
{
if (value != m_litecoinUser)
{
m_litecoinUser = value;
emit ltcUserChanged();
emit propertiesChanged();
}
}
QString SettingsViewModel::getLtcPass() const
{
return m_litecoinPass;
}
void SettingsViewModel::setLtcPass(const QString& value)
{
if (value != m_litecoinPass)
{
m_litecoinPass = value;
emit ltcPassChanged();
emit propertiesChanged();
}
}
QString SettingsViewModel::getLtcNodeAddress() const
{
return m_litecoinNodeAddress;
}
void SettingsViewModel::setLtcNodeAddress(const QString& value)
{
if (value != m_litecoinNodeAddress)
{
m_litecoinNodeAddress = value;
emit ltcNodeAddressChanged();
emit propertiesChanged();
}
}
int SettingsViewModel::getLtcFeeRate() const
{
return m_litecoinFeeRate;
}
void SettingsViewModel::setLtcFeeRate(int value)
{
if (value != m_litecoinFeeRate)
{
m_litecoinFeeRate = value;
emit ltcFeeRateChanged();
emit propertiesChanged();
}
}
void SettingsViewModel::applyLtcSettings()
{
litecoin::LitecoinCoreSettings connectionSettings;
connectionSettings.m_pass = m_litecoinPass.toStdString();
connectionSettings.m_userName = m_litecoinUser.toStdString();
if (!m_litecoinNodeAddress.isEmpty())
{
const std::string address = m_litecoinNodeAddress.toStdString();
connectionSettings.m_address.resolve(address.c_str());
}
m_litecoinSettings->SetConnectionOptions(connectionSettings);
m_litecoinSettings->SetFeeRate(m_litecoinFeeRate);
AppModel::getInstance().getLitecoinClient()->SetSettings(*m_litecoinSettings);
}
void SettingsViewModel::ltcOff()
{
setLtcFeeRate(QMLGlobals::defFeeRateLtc());
setLtcNodeAddress("");
setLtcPass("");
setLtcUser("");
AppModel::getInstance().getLitecoinClient()->GetAsync()->ResetSettings();
}
QString SettingsViewModel::getQtumUser() const
{
return m_qtumUser;
}
void SettingsViewModel::setQtumUser(const QString& value)
{
if (value != m_qtumUser)
{
m_qtumUser = value;
emit qtumUserChanged();
emit propertiesChanged();
}
}
QString SettingsViewModel::getQtumPass() const
{
return m_qtumPass;
}
void SettingsViewModel::setQtumPass(const QString& value)
{
if (value != m_qtumPass)
{
m_qtumPass = value;
emit qtumPassChanged();
emit propertiesChanged();
}
}
QString SettingsViewModel::getQtumNodeAddress() const
{
return m_qtumNodeAddress;
}
void SettingsViewModel::setQtumNodeAddress(const QString& value)
{
if (value != m_qtumNodeAddress)
{
m_qtumNodeAddress = value;
emit qtumNodeAddressChanged();
emit propertiesChanged();
}
}
int SettingsViewModel::getQtumFeeRate() const
{
return m_qtumFeeRate;
}
void SettingsViewModel::setQtumFeeRate(int value)
{
if (value != m_qtumFeeRate)
{
m_qtumFeeRate = value;
emit qtumFeeRateChanged();
emit propertiesChanged();
}
}
void SettingsViewModel::applyQtumSettings()
{
qtum::QtumCoreSettings connectionSettings;
connectionSettings.m_pass = m_qtumPass.toStdString();
connectionSettings.m_userName = m_qtumUser.toStdString();
if (!m_qtumNodeAddress.isEmpty())
{
const std::string address = m_qtumNodeAddress.toStdString();
connectionSettings.m_address.resolve(address.c_str());
}
m_qtumSettings->SetConnectionOptions(connectionSettings);
m_qtumSettings->SetFeeRate(m_qtumFeeRate);
AppModel::getInstance().getQtumClient()->SetSettings(*m_qtumSettings);
}
void SettingsViewModel::qtumOff()
{
setQtumFeeRate(QMLGlobals::defFeeRateQtum());
setQtumNodeAddress("");
setQtumPass("");
setQtumUser("");
AppModel::getInstance().getQtumClient()->GetAsync()->ResetSettings();
}
QString SettingsViewModel::getBtcSeedEL() const
{
return "";
}
void SettingsViewModel::setBtcSeedEL(const QString& value)
{
}
QString SettingsViewModel::getBtcNodeAddressEL() const
{
return "";
}
void SettingsViewModel::setBtcNodeAddressEL(const QString& value)
{
}
int SettingsViewModel::getBtcFeeRateEL() const
{
return 90000;
}
void SettingsViewModel::setBtcFeeRateEL(int value)
{
}
void SettingsViewModel::applyBtcSettingsEL()
{
LOG_INFO() << "apply btc settings EL";
}
void SettingsViewModel::btcOffEL()
{
LOG_INFO() << "btcOffEL";
}
QString SettingsViewModel::getLtcSeedEL() const
{
return "";
}
void SettingsViewModel::setLtcSeedEL(const QString& value)
{
}
QString SettingsViewModel::getLtcNodeAddressEL() const
{
return "";
}
void SettingsViewModel::setLtcNodeAddressEL(const QString& value)
{
}
int SettingsViewModel::getLtcFeeRateEL() const
{
return 90000;
}
void SettingsViewModel::setLtcFeeRateEL(int value)
{
}
void SettingsViewModel::SettingsViewModel::applyLtcSettingsEL()
{
}
void SettingsViewModel::ltcOffEL()
{
}
void SettingsViewModel::SettingsViewModel::applyQtumSettingsEL()
{
}
QString SettingsViewModel::getQtumSeedEL() const
{
return "";
}
void SettingsViewModel::setQtumSeedEL(const QString& value)
{
}
QString SettingsViewModel::getQtumNodeAddressEL() const
{
return "";
}
void SettingsViewModel::setQtumNodeAddressEL(const QString& value)
{
}
int SettingsViewModel::getQtumFeeRateEL() const
{
return 90000;
}
void SettingsViewModel::setQtumFeeRateEL(int value)
{
}
void SettingsViewModel::qtumOffEL()
{
}
void SettingsViewModel::btcNewSeedEL()
{
}
void SettingsViewModel::ltcNewSeedEL()
{
}
void SettingsViewModel::qtumNewSeedEL()
{
}
bool SettingsViewModel::isLocalNodeRunning() const
{
return AppModel::getInstance().getNode().isNodeRunning();
}
bool SettingsViewModel::isValidNodeAddress() const
{
return m_isValidNodeAddress;
}
QString SettingsViewModel::getNodeAddress() const
{
return m_nodeAddress;
}
void SettingsViewModel::setNodeAddress(const QString& value)
{
if (value != m_nodeAddress)
{
m_nodeAddress = value;
if (!m_isNeedToCheckAddress)
{
m_isNeedToCheckAddress = true;
m_timerId = startTimer(CHECK_INTERVAL);
}
emit nodeAddressChanged();
emit propertiesChanged();
}
}
QString SettingsViewModel::getVersion() const
{
return QString::fromStdString(PROJECT_VERSION);
}
bool SettingsViewModel::getLocalNodeRun() const
{
return m_localNodeRun;
}
void SettingsViewModel::setLocalNodeRun(bool value)
{
if (value != m_localNodeRun)
{
m_localNodeRun = value;
if (!m_localNodeRun && !m_isNeedToCheckAddress)
{
m_isNeedToCheckAddress = true;
m_timerId = startTimer(CHECK_INTERVAL);
}
emit localNodeRunChanged();
emit propertiesChanged();
}
}
uint SettingsViewModel::getLocalNodePort() const
{
return m_localNodePort;
}
void SettingsViewModel::setLocalNodePort(uint value)
{
if (value != m_localNodePort)
{
m_localNodePort = value;
emit localNodePortChanged();
emit propertiesChanged();
}
}
int SettingsViewModel::getLockTimeout() const
{
return m_lockTimeout;
}
void SettingsViewModel::setLockTimeout(int value)
{
if (value != m_lockTimeout)
{
m_lockTimeout = value;
m_settings.setLockTimeout(m_lockTimeout);
emit lockTimeoutChanged();
}
}
bool SettingsViewModel::isPasswordReqiredToSpendMoney() const
{
return m_isPasswordReqiredToSpendMoney;
}
void SettingsViewModel::setPasswordReqiredToSpendMoney(bool value)
{
if (value != m_isPasswordReqiredToSpendMoney)
{
m_isPasswordReqiredToSpendMoney = value;
m_settings.setPasswordReqiredToSpendMoney(m_isPasswordReqiredToSpendMoney);
emit passwordReqiredToSpendMoneyChanged();
}
}
bool SettingsViewModel::isAllowedBeamMWLinks() const
{
return m_isAllowedBeamMWLinks;
}
void SettingsViewModel::allowBeamMWLinks(bool value)
{
if (value != m_isAllowedBeamMWLinks)
{
m_isAllowedBeamMWLinks = value;
m_settings.setAllowedBeamMWLinks(m_isAllowedBeamMWLinks);
emit beamMWLinksAllowed();
}
}
QStringList SettingsViewModel::getSupportedLanguages() const
{
return m_supportedLanguages;
}
int SettingsViewModel::getCurrentLanguageIndex() const
{
return m_currentLanguageIndex;
}
void SettingsViewModel::setCurrentLanguageIndex(int value)
{
m_currentLanguageIndex = value;
m_settings.setLocaleByLanguageName(
m_supportedLanguages[m_currentLanguageIndex]);
emit currentLanguageIndexChanged();
}
QString SettingsViewModel::getCurrentLanguage() const
{
return m_supportedLanguages[m_currentLanguageIndex];
}
void SettingsViewModel::setCurrentLanguage(QString value)
{
auto index = m_supportedLanguages.indexOf(value);
if (index != -1 )
{
setCurrentLanguageIndex(index);
}
}
uint SettingsViewModel::coreAmount() const
{
return std::thread::hardware_concurrency();
}
void SettingsViewModel::addLocalNodePeer(const QString& localNodePeer)
{
m_localNodePeers.push_back(localNodePeer);
emit localNodePeersChanged();
emit propertiesChanged();
}
void SettingsViewModel::deleteLocalNodePeer(int index)
{
m_localNodePeers.removeAt(index);
emit localNodePeersChanged();
emit propertiesChanged();
}
void SettingsViewModel::openUrl(const QString& url)
{
QDesktopServices::openUrl(QUrl(url));
}
void SettingsViewModel::refreshWallet()
{
AppModel::getInstance().getWallet()->getAsync()->refresh();
}
void SettingsViewModel::openFolder(const QString& path)
{
WalletSettings::openFolder(path);
}
bool SettingsViewModel::checkWalletPassword(const QString& oldPass) const
{
SecString secretPass = oldPass.toStdString();
return AppModel::getInstance().checkWalletPassword(secretPass);
}
bool SettingsViewModel::isChanged() const
{
return m_nodeAddress != m_settings.getNodeAddress()
|| m_localNodeRun != m_settings.getRunLocalNode()
|| m_localNodePort != m_settings.getLocalNodePort()
|| m_localNodePeers != m_settings.getLocalNodePeers();
}
void SettingsViewModel::applyChanges()
{
if (!m_localNodeRun && m_isNeedToCheckAddress)
{
m_isNeedToApplyChanges = true;
return;
}
m_settings.setNodeAddress(m_nodeAddress);
m_settings.setRunLocalNode(m_localNodeRun);
m_settings.setLocalNodePort(m_localNodePort);
m_settings.setLocalNodePeers(m_localNodePeers);
m_settings.applyChanges();
emit propertiesChanged();
}
QStringList SettingsViewModel::getLocalNodePeers() const
{
return m_localNodePeers;
}
void SettingsViewModel::setLocalNodePeers(const QStringList& localNodePeers)
{
m_localNodePeers = localNodePeers;
emit localNodePeersChanged();
emit propertiesChanged();
}
QString SettingsViewModel::getWalletLocation() const
{
return QString::fromStdString(m_settings.getAppDataPath());
}
void SettingsViewModel::undoChanges()
{
setNodeAddress(m_settings.getNodeAddress());
setLocalNodeRun(m_settings.getRunLocalNode());
setLocalNodePort(m_settings.getLocalNodePort());
setLockTimeout(m_settings.getLockTimeout());
setLocalNodePeers(m_settings.getLocalNodePeers());
setPasswordReqiredToSpendMoney(m_settings.isPasswordReqiredToSpendMoney());
allowBeamMWLinks(m_settings.isAllowedBeamMWLinks());
setCurrentLanguageIndex(m_supportedLanguages.indexOf(m_settings.getLanguageName()));
}
void SettingsViewModel::reportProblem()
{
m_settings.reportProblem();
}
void SettingsViewModel::changeWalletPassword(const QString& pass)
{
AppModel::getInstance().changeWalletPassword(pass.toStdString());
}
void SettingsViewModel::timerEvent(QTimerEvent *event)
{
if (m_isNeedToCheckAddress && !m_localNodeRun)
{
m_isNeedToCheckAddress = false;
AppModel::getInstance().getWallet()->getAsync()->checkAddress(m_nodeAddress.toStdString());
killTimer(m_timerId);
}
}
void SettingsViewModel::LoadBitcoinSettings()
{
m_bitcoinSettings = AppModel::getInstance().getBitcoinClient()->GetSettings();
setBtcUser(str2qstr(m_bitcoinSettings->GetConnectionOptions().m_userName));
setBtcPass(str2qstr(m_bitcoinSettings->GetConnectionOptions().m_pass));
setBtcNodeAddress(AddressToQstring(m_bitcoinSettings->GetConnectionOptions().m_address));
setBtcFeeRate(m_bitcoinSettings->GetFeeRate());
}
void SettingsViewModel::LoadLitecoinSettings()
{
m_litecoinSettings = AppModel::getInstance().getLitecoinClient()->GetSettings();
setLtcUser(str2qstr(m_litecoinSettings->GetConnectionOptions().m_userName));
setLtcPass(str2qstr(m_litecoinSettings->GetConnectionOptions().m_pass));
setLtcNodeAddress(AddressToQstring(m_litecoinSettings->GetConnectionOptions().m_address));
setLtcFeeRate(m_litecoinSettings->GetFeeRate());
}
void SettingsViewModel::LoadQtumSettings()
{
m_qtumSettings = AppModel::getInstance().getQtumClient()->GetSettings();
setQtumUser(str2qstr(m_qtumSettings->GetConnectionOptions().m_userName));
setQtumPass(str2qstr(m_qtumSettings->GetConnectionOptions().m_pass));
setQtumNodeAddress(AddressToQstring(m_qtumSettings->GetConnectionOptions().m_address));
setQtumFeeRate(m_qtumSettings->GetFeeRate());
} | 23.679688 | 147 | 0.720279 | [
"model"
] |
929c3186ad055aacb63a3792296dc4ac774dbd60 | 9,160 | cpp | C++ | source/rotating_body.cpp | timbeaudet/racecar | 3695be16a92c7be6d10c2a9c6fc93a9ad7324aea | [
"MIT"
] | 7 | 2017-08-19T08:34:10.000Z | 2020-05-31T18:38:53.000Z | source/rotating_body.cpp | timbeaudet/racecar | 3695be16a92c7be6d10c2a9c6fc93a9ad7324aea | [
"MIT"
] | 1 | 2017-10-15T17:11:54.000Z | 2017-10-15T17:11:54.000Z | source/rotating_body.cpp | timbeaudet/racecar | 3695be16a92c7be6d10c2a9c6fc93a9ad7324aea | [
"MIT"
] | null | null | null | ///
/// @file
/// @details A simple base class for each of the components of the drive-train that have rotating bodies.
///
/// <!-- This file is made available under the terms of the MIT license(see LICENSE.md) -->
/// <!-- Copyright (c) 2017 Contributers: Tim Beaudet, -->
///-----------------------------------------------------------------------------------------------------------------///
#include "rotating_body.h"
#include <algorithm>
//-------------------------------------------------------------------------------------------------------------------//
//-------------------------------------------------------------------------------------------------------------------//
//-------------------------------------------------------------------------------------------------------------------//
Racecar::Real Racecar::kGravityConstant(10.0); //10m/s/s
static const Racecar::Real kPi(3.14159265358979323846);
static const Racecar::Real kTwoPi(kPi * 2.0);
Racecar::Real Racecar::RevolutionsMinuteToRadiansSecond(const Real& revolutionsMinute)
{
return revolutionsMinute / 60.0 * kTwoPi;
}
//-------------------------------------------------------------------------------------------------------------------//
Racecar::Real Racecar::RadiansSecondToRevolutionsMinute(const Real& radiansSecond)
{
return radiansSecond * 60.0 / kTwoPi;
}
//-------------------------------------------------------------------------------------------------------------------//
//-------------------------------------------------------------------------------------------------------------------//
//-------------------------------------------------------------------------------------------------------------------//
Racecar::RotatingBody::RotatingBody(const Real& momentOfInertia) :
mInputSource(nullptr),
mOutputSources(),
mInertia(momentOfInertia),
mAngularVelocity(0)
{
}
//-------------------------------------------------------------------------------------------------------------------//
Racecar::RotatingBody::~RotatingBody(void)
{
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::SetInputSource(RotatingBody* input)
{
error_if(nullptr != mInputSource, "Already has an input, attempting to change is illegal.");
mInputSource = input;
}
//-------------------------------------------------------------------------------------------------------------------//
const Racecar::RotatingBody& Racecar::RotatingBody::GetExpectedInputSource(void) const
{
error_if(nullptr == mInputSource, "RotatingBody was expecting to have an input source for use.");
return *mInputSource;
}
//-------------------------------------------------------------------------------------------------------------------//
Racecar::RotatingBody& Racecar::RotatingBody::GetExpectedInputSource(void)
{
error_if(nullptr == mInputSource, "RotatingBody was expecting to have an input source for use.");
return *mInputSource;
}
//-------------------------------------------------------------------------------------------------------------------//
bool Racecar::RotatingBody::IsOutputSource(const RotatingBody& source) const
{
return (mOutputSources.end() != std::find(mOutputSources.begin(), mOutputSources.end(), &source));
}
//-------------------------------------------------------------------------------------------------------------------//
size_t Racecar::RotatingBody::GetNumberOfOutputSources(void) const
{
return mOutputSources.size();
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::AddOutputSource(RotatingBody* output)
{
error_if(mOutputSources.end() != std::find(mOutputSources.begin(), mOutputSources.end(), output), "Already connected to this output.");
error_if(nullptr == output, "Cannot connect to a null output.");
mOutputSources.push_back(output);
}
//-------------------------------------------------------------------------------------------------------------------//
const Racecar::RotatingBody& Racecar::RotatingBody::GetExpectedOutputSource(const size_t& sourceIndex) const
{
error_if(sourceIndex >= mOutputSources.size(), "RotatingBody was expecting to have an output source for use of index: %d.", sourceIndex);
return *(mOutputSources[sourceIndex]);
}
//-------------------------------------------------------------------------------------------------------------------//
Racecar::RotatingBody& Racecar::RotatingBody::GetExpectedOutputSource(const size_t& sourceIndex)
{
error_if(sourceIndex >= mOutputSources.size(), "RotatingBody was expecting to have an output source for use of index: %d.", sourceIndex);
return *(mOutputSources[sourceIndex]);
}
//-------------------------------------------------------------------------------------------------------------------//
const std::vector<Racecar::RotatingBody*>& Racecar::RotatingBody::GetOutputSources(void) const
{
return mOutputSources;
}
//-------------------------------------------------------------------------------------------------------------------//
std::vector<Racecar::RotatingBody*>& Racecar::RotatingBody::GetOutputSources(void)
{
return mOutputSources;
}
//-------------------------------------------------------------------------------------------------------------------//
Racecar::Real Racecar::RotatingBody::ComputeDownstreamInertia(void) const
{
Real downstreamInertia(GetInertia());
for (RotatingBody* output : mOutputSources)
{
downstreamInertia += output->ComputeDownstreamInertia();
}
return downstreamInertia;
}
//-------------------------------------------------------------------------------------------------------------------//
Racecar::Real Racecar::RotatingBody::ComputeUpstreamInertia(void) const
{
Real upstreamInertia(GetInertia());
if (nullptr != mInputSource)
{
upstreamInertia += mInputSource->ComputeUpstreamInertia();
}
return upstreamInertia;
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::ControllerChange(const RacecarControllerInterface& racecarController)
{
OnControllerChange(racecarController);
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::OnControllerChange(const RacecarControllerInterface& racecarController)
{
((void)racecarController);
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::Simulate(const Real& fixedTime)
{
OnSimulate(fixedTime);
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::OnSimulate(const Real& fixedTime)
{
((void)fixedTime);
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::ApplyDownstreamAngularImpulse(const Real& angularImpulse)
{
const Real totalInertia(ComputeDownstreamInertia());
OnDownstreamAngularVelocityChange(angularImpulse / totalInertia);
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::ApplyUpstreamAngularImpulse(const Real& angularImpulse)
{
const Real totalInertia(ComputeUpstreamInertia());
OnUpstreamAngularVelocityChange(angularImpulse / totalInertia);
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::OnDownstreamAngularVelocityChange(const Real& changeInAngularVelocity)
{
mAngularVelocity += changeInAngularVelocity;
for (RotatingBody* output : mOutputSources)
{
output->OnDownstreamAngularVelocityChange(changeInAngularVelocity);
}
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::OnUpstreamAngularVelocityChange(const Real& changeInAngularVelocity)
{
mAngularVelocity += changeInAngularVelocity;
if (nullptr != mInputSource)
{
mInputSource->OnUpstreamAngularVelocityChange(changeInAngularVelocity);
}
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::SetInertia(const Real& inertia)
{
mInertia = inertia;
}
//-------------------------------------------------------------------------------------------------------------------//
void Racecar::RotatingBody::SetAngularVelocity(const Real& angularVelocity)
{
mAngularVelocity = angularVelocity;
}
//-------------------------------------------------------------------------------------------------------------------//
| 39.145299 | 139 | 0.432424 | [
"vector"
] |
929c345e91b8f369cc10409bc519979e1c128561 | 427 | cc | C++ | Leetcode/0201_to_0250/0240_search_2D_matrix_2/cc/search_2D_matrix_2.cc | z-yin/Leetcode-learning | e84c2fb067b767ed5f24d8736274c7ebce5dc00e | [
"MIT"
] | 1 | 2019-07-31T08:44:45.000Z | 2019-07-31T08:44:45.000Z | Leetcode/0201_to_0250/0240_search_2D_matrix_2/cc/search_2D_matrix_2.cc | z-yin/Leetcode-learning | e84c2fb067b767ed5f24d8736274c7ebce5dc00e | [
"MIT"
] | null | null | null | Leetcode/0201_to_0250/0240_search_2D_matrix_2/cc/search_2D_matrix_2.cc | z-yin/Leetcode-learning | e84c2fb067b767ed5f24d8736274c7ebce5dc00e | [
"MIT"
] | null | null | null | #include <vector>
using namespace std;
// 60 ms, 12 MB.
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty() || matrix[0].empty()) return false;
int r = matrix.size() - 1;
int c = 0;
while (r >= 0 && c < matrix[0].size()) {
if (matrix[r][c] == target) return true;
if (matrix[r][c] < target) ++c;
else --r;
}
return false;
}
}; | 23.722222 | 62 | 0.555035 | [
"vector"
] |
929c4f9441603d39f4f73a4732d0823bc7da0136 | 1,987 | cpp | C++ | genresp/genrespmle.cpp | sjhaberman/irtlib | a1c08f77b508e1880a5351fa44631f3f5c846650 | [
"Apache-2.0"
] | 2 | 2019-09-25T09:16:58.000Z | 2020-01-14T03:47:48.000Z | genresp/genrespmle.cpp | sjhaberman/irtlib | a1c08f77b508e1880a5351fa44631f3f5c846650 | [
"Apache-2.0"
] | null | null | null | genresp/genrespmle.cpp | sjhaberman/irtlib | a1c08f77b508e1880a5351fa44631f3f5c846650 | [
"Apache-2.0"
] | null | null | null | //Find maximum likelihood estimates for response model.
//See genresplik.cpp and nrv.cpp for definitions of structs
//used.
//Newton-Raphson approach is used if algorithm is N.
//Louis approach is used if algorithm is L.
//Conjugate gradient method is used if algorithm is C.
//Gradient ascent is used if algorithm is G.
#include<armadillo>
using namespace arma;
using namespace std::placeholders;
struct f2v
{
double value;
vec grad;
mat hess;
};
struct maxf2v
{
vec locmax;
double max;
vec grad;
mat hess;
};
struct params
{
int maxit;
int maxits;
double eta;
double gamma1;
double gamma2;
double kappa;
double tol;
};
struct model
{
char type;
char transform;
};
struct resp
{
ivec iresp;
vec dresp;
};
struct xsel
{
bool all;
uvec list;
};
struct dat
{
model choice;
double weight;
resp dep;
vec offset;
mat indep;
xsel xselect;
};
maxf2v conjgrad(const int &, const params & , const vec & ,
const std::function<f2v(const int & , const vec & )> f);
maxf2v gradascent(const int &, const params & , const vec & ,
const std::function<f2v(const int & , const vec & )> f);
maxf2v nrv(const int &, const params & , const vec & ,
const std::function<f2v(const int & , const vec & )> f);
f2v genresplik(const int & , const std::vector<dat> & , const vec &);
maxf2v genrespmle(const int & order, const params & mparams,
const char & algorithm, const std::vector<dat> & data, const vec & start)
{
maxf2v results;
int p;
p=start.n_elem;
results.locmax.set_size(p);
results.grad.set_size(p);
if(algorithm=='N'||algorithm=='L')results.hess.set_size(p,p);
auto f=std::bind(genresplik, _1, data, _2);
if(algorithm=='N'||algorithm=='L')results=nrv(order, mparams, start, f);
if(algorithm=='C')results=conjgrad(order, mparams, start, f);
if(algorithm=='G')results=gradascent(order, mparams, start, f);
return results;
}
| 24.530864 | 77 | 0.651736 | [
"vector",
"model",
"transform"
] |
92a247e2df71119c7e14b0c6ece8d697f54b3a25 | 2,168 | hpp | C++ | liblava/frame/driver.hpp | TheLavaBlock/LavaBlock | fc2eadb75dfa58622a1941911f20fe31f8780f30 | [
"MIT"
] | 11 | 2018-10-26T02:15:53.000Z | 2019-05-25T16:08:17.000Z | liblava/frame/driver.hpp | TheLavaBlock/LavaBlock | fc2eadb75dfa58622a1941911f20fe31f8780f30 | [
"MIT"
] | null | null | null | liblava/frame/driver.hpp | TheLavaBlock/LavaBlock | fc2eadb75dfa58622a1941911f20fe31f8780f30 | [
"MIT"
] | null | null | null | /**
* @file liblava/frame/driver.hpp
* @brief Stage driver
* @authors Lava Block OÜ and contributors
* @copyright Copyright (c) 2018-present, MIT License
*/
#pragma once
#include <liblava/frame/argh.hpp>
namespace lava {
/**
* @brief Stage
*/
struct stage {
/// Map of stages
using map = std::map<index, stage*>;
/// Stage function
using func = std::function<i32(argh::parser)>;
/**
* @brief Construct a new stage
*
* @param id Stage id
* @param descr Stage description
* @param func Stage function
*/
explicit stage(ui32 id,
name descr,
func func);
/// Stage id
index id = 0;
/// Stage description
string descr;
/// Called on stage run
func on_func;
};
/**
* @brief Stage driver
*/
struct driver {
/**
* @brief Get driver singleton
*
* @return driver& Stage driver
*/
static driver& instance() {
static driver singleton;
return singleton;
}
/**
* @brief Add a stage
*
* @param stage Stage to add
*/
void add_stage(stage* stage) {
stages.emplace(stage->id, stage);
}
/**
* @brief Get all stages
*
* @return stage::map const& Map of stages
*/
stage::map const& get_stages() const {
return stages;
}
/**
* @brief Run the driver
*
* @param cmd_line Command line arguments
*
* @return i32 Result code
*/
i32 run(argh::parser cmd_line = {});
private:
/**
* @brief Construct a new driver
*/
driver() = default;
/// Map of stages
stage::map stages;
};
} // namespace lava
/// Stage object
#define STAGE_OBJ stage_
/// Stage function
#define STAGE_FUNC _stage
/// String concatenation
#define STR_(n, m) n##m
/// String concatenation
#define STR(n, m) STR_(n, m)
/// Lava stage macro
#define LAVA_STAGE(ID, NAME) \
i32 STR(STAGE_FUNC, ID)(argh::parser argh); \
lava::stage STR(STAGE_OBJ, ID)(ID, NAME, ::STR(STAGE_FUNC, ID)); \
i32 STR(STAGE_FUNC, ID)(argh::parser argh)
| 18.852174 | 70 | 0.557657 | [
"object"
] |
92a31e42714364808224afa6d050d264c89e5c3e | 5,534 | cpp | C++ | components/LedDrivers/Strip_ws2812.cpp | afugs98/SmartHome | ffe5926b8eb632a84a6f57c072d67eb6b3ceb9af | [
"MIT"
] | null | null | null | components/LedDrivers/Strip_ws2812.cpp | afugs98/SmartHome | ffe5926b8eb632a84a6f57c072d67eb6b3ceb9af | [
"MIT"
] | 2 | 2019-06-22T02:39:36.000Z | 2019-06-22T05:22:42.000Z | components/LedDrivers/Strip_ws2812.cpp | afugs98/SmartHome | ffe5926b8eb632a84a6f57c072d67eb6b3ceb9af | [
"MIT"
] | null | null | null | #include "Strip_ws2812.h"
#include <stdio.h>
#include <stdlib.h>
#include <espressif/esp_wifi.h>
#include <espressif/esp_sta.h>
#include <esp/uart.h>
#include <esp8266.h>
#include <FreeRTOS.h>
#include <task.h>
#include <math.h>
#define LED_ON 0 // this is the value to write to GPIO for led on (0 = GPIO low)
#define LED_INBUILT_GPIO 2 // this is the onboard LED used to show on/off only
#define LED_COUNT 16 // this is the number of WS2812B leds on the strip
#define LED_RGB_SCALE 255 // this is the scaling factor used for color conversion
// Global variables
static float led_hue = 0; // hue is scaled 0 to 360
static float led_saturation = 59; // saturation is scaled 0 to 100
static float led_brightness = 100; // brightness is scaled 0 to 100
static bool led_on = false; // on is boolean on or off
ws2812_pixel_t pixels[LED_COUNT];
//http://blog.saikoled.com/post/44677718712/how-to-convert-from-hsi-to-rgb-white
static void hsi2rgb(float h, float s, float i, ws2812_pixel_t* rgb)
{
int r, g, b;
while(h < 0)
{
h += 360.0F;
}; // cycle h around to 0-360 degrees
while(h >= 360)
{
h -= 360.0F;
};
h = 3.14159F * h / 180.0F; // convert to radians.
s /= 100.0F; // from percentage to ratio
i /= 100.0F; // from percentage to ratio
s = s > 0 ? (s < 1 ? s : 1) : 0; // clamp s and i to interval [0,1]
i = i > 0 ? (i < 1 ? i : 1) : 0; // clamp s and i to interval [0,1]
i = i * sqrt(i); // shape intensity to have finer granularity near 0
if(h < 2.09439)
{
r = LED_RGB_SCALE * i / 3 * (1 + s * cos(h) / cos(1.047196667 - h));
g = LED_RGB_SCALE * i / 3 * (1 + s * (1 - cos(h) / cos(1.047196667 - h)));
b = LED_RGB_SCALE * i / 3 * (1 - s);
}
else if(h < 4.188787)
{
h = h - 2.09439;
g = LED_RGB_SCALE * i / 3 * (1 + s * cos(h) / cos(1.047196667 - h));
b = LED_RGB_SCALE * i / 3 * (1 + s * (1 - cos(h) / cos(1.047196667 - h)));
r = LED_RGB_SCALE * i / 3 * (1 - s);
}
else
{
h = h - 4.188787;
b = LED_RGB_SCALE * i / 3 * (1 + s * cos(h) / cos(1.047196667 - h));
r = LED_RGB_SCALE * i / 3 * (1 + s * (1 - cos(h) / cos(1.047196667 - h)));
g = LED_RGB_SCALE * i / 3 * (1 - s);
}
rgb->red = (uint8_t)r;
rgb->green = (uint8_t)g;
rgb->blue = (uint8_t)b;
rgb->white = (uint8_t)0; // white channel is not used
}
void led_string_fill(ws2812_pixel_t rgb)
{
// write out the new color to each pixel
for(int i = 0; i < LED_COUNT; i++)
{
pixels[i] = rgb;
}
ws2812_i2s_update(pixels, PIXEL_RGB);
}
void led_string_set(void)
{
ws2812_pixel_t rgb =
{
{ 0, 0, 0, 0 } };
if(led_on)
{
// convert HSI to RGBW
hsi2rgb(led_hue, led_saturation, led_brightness, &rgb);
//printf("h=%d,s=%d,b=%d => ", (int)led_hue, (int)led_saturation, (int)led_brightness);
//printf("r=%d,g=%d,b=%d,w=%d\n", rgbw.red, rgbw.green, rgbw.blue, rgbw.white);
// set the inbuilt led
gpio_write(LED_INBUILT_GPIO, LED_ON);
}
else
{
// printf("off\n");
gpio_write(LED_INBUILT_GPIO, 1 - LED_ON);
}
// write out the new color
led_string_fill(rgb);
}
void LedInit()
{
// initialise the onboard led as a secondary indicator (handy for testing)
gpio_enable(LED_INBUILT_GPIO, GPIO_OUTPUT);
// initialise the LED strip
ws2812_i2s_init(LED_COUNT, PIXEL_RGB);
// set the initial state
led_string_set();
}
void led_identify_task(void *_args)
{
const ws2812_pixel_t COLOR_PINK =
{
{ 255, 0, 127, 0 } };
const ws2812_pixel_t COLOR_BLACK =
{
{ 0, 0, 0, 0 } };
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
gpio_write(LED_INBUILT_GPIO, LED_ON);
led_string_fill(COLOR_PINK);
vTaskDelay(100 / portTICK_PERIOD_MS);
gpio_write(LED_INBUILT_GPIO, 1 - LED_ON);
led_string_fill(COLOR_BLACK);
vTaskDelay(100 / portTICK_PERIOD_MS);
}
vTaskDelay(250 / portTICK_PERIOD_MS);
}
led_string_set();
vTaskDelete (NULL);
}
void LedIdentify(homekit_value_t _value)
{
// printf("LED identify\n");
xTaskCreate(led_identify_task, "LED identify", 128, NULL, 2, NULL);
}
homekit_value_t LedGetSate()
{
return HOMEKIT_BOOL(led_on);
}
void LedSetState(homekit_value_t value)
{
if(value.format != homekit_format_bool)
{
// printf("Invalid on-value format: %d\n", value.format);
return;
}
led_on = value.bool_value;
led_string_set();
}
homekit_value_t LedGetBrightness()
{
return HOMEKIT_INT(led_brightness);
}
void LedSetBrightness(homekit_value_t value)
{
if(value.format != homekit_format_int)
{
// printf("Invalid brightness-value format: %d\n", value.format);
return;
}
led_brightness = value.int_value;
led_string_set();
}
homekit_value_t LedHueGet()
{
return HOMEKIT_FLOAT(led_hue);
}
void LedHueSet(homekit_value_t value)
{
if(value.format != homekit_format_float)
{
// printf("Invalid hue-value format: %d\n", value.format);
return;
}
led_hue = value.float_value;
led_string_set();
}
homekit_value_t LedGetSaturation()
{
return HOMEKIT_FLOAT(led_saturation);
}
void LedSetSaturation(homekit_value_t value)
{
if(value.format != homekit_format_float)
{
// printf("Invalid sat-value format: %d\n", value.format);
return;
}
led_saturation = value.float_value;
led_string_set();
}
| 25.385321 | 95 | 0.610047 | [
"shape"
] |
92a99dafc0bd2179ce74b882f31acc1b51417bf0 | 610 | hpp | C++ | src/engine/render/imgui/ImGuiContextWrapper.hpp | Henauxg/ExperimEngine | e031700128239b3fe3901cb0704699c06257b8e9 | [
"MIT"
] | 3 | 2020-01-08T19:17:02.000Z | 2021-11-29T18:52:22.000Z | src/engine/render/imgui/ImGuiContextWrapper.hpp | Henauxg/ExperimEngine | e031700128239b3fe3901cb0704699c06257b8e9 | [
"MIT"
] | null | null | null | src/engine/render/imgui/ImGuiContextWrapper.hpp | Henauxg/ExperimEngine | e031700128239b3fe3901cb0704699c06257b8e9 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <engine/log/ExpengineLog.hpp>
#include <engine/render/imgui/lib/imgui.h>
/* RAII wrapper for an ImGui context */
namespace experim {
/** Custom back-end */
class ImGuiContextWrapper {
public:
inline ImGuiContextWrapper() { ctx_ = ImGui::CreateContext(); };
/* Also destroy all ImGui viewports from this context */
inline ~ImGuiContextWrapper()
{
SPDLOG_DEBUG("ImGuiContext destruction");
ImGui::DestroyContext(ctx_);
};
inline ImGuiContext* get() { return ctx_; };
private:
ImGuiContext* ctx_;
};
} // namespace experim
| 21.785714 | 68 | 0.683607 | [
"render"
] |
92aa912590d0d9ff983a20e8f046e399364bb106 | 850 | cc | C++ | C_C++_Tricks.cc | Computational-Camera/OPENCV_Tricks | e79957306ce8f267cc725f869769ffda92f47e7c | [
"MIT"
] | 1 | 2019-10-30T06:07:52.000Z | 2019-10-30T06:07:52.000Z | C_C++_Tricks.cc | Computational-Camera/OPENCV_Tricks | e79957306ce8f267cc725f869769ffda92f47e7c | [
"MIT"
] | null | null | null | C_C++_Tricks.cc | Computational-Camera/OPENCV_Tricks | e79957306ce8f267cc725f869769ffda92f47e7c | [
"MIT"
] | 1 | 2019-11-19T05:56:19.000Z | 2019-11-19T05:56:19.000Z | //====Number to String====
char str[8];//enough large
sprintf(str, "%d", t);
//====Variable File Name====
ostringstream fn;
fn<<"./output/xxx_"<<k<<".JPG";
(fn.str()).c_str()
//=====Time Performance=====
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
//------------------
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
uint64_t delta_us = (end.tv_nsec - start.tv_nsec) / 1000;
//======Random Number========
#include <time.h>
srand((unsigned)time(NULL));
float jitter = float(rand()%100)/100 -0.5 ; //RAND_MAX is a constant defined in <cstdlib>. -0.5 to 0.5
//=====3D array declearation
//====new array with zeros
new float[10]();
//====output to console or file
ostringstream file_name;
freopen((file_name.str()).c_str(), "a", stderr);//a: append, w: new and write
fprintf(stdout, "hello\n");
fprintf(stderr, "hello\n");
| 25.757576 | 102 | 0.64 | [
"3d"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.