hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 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 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | 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 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6dc4aef7f7b2ee6ba5efc22d2683853ade1ebc0b | 3,411 | hpp | C++ | include/utils/for_each.hpp | fengwang/ceras | 15d10e8909ded656f45201aecc45b8eefe961b2d | [
"BSD-3-Clause"
] | 65 | 2020-12-07T01:15:41.000Z | 2022-03-28T01:17:33.000Z | include/utils/for_each.hpp | fengwang/ceras | 15d10e8909ded656f45201aecc45b8eefe961b2d | [
"BSD-3-Clause"
] | 1 | 2021-04-08T13:20:39.000Z | 2021-04-09T00:37:02.000Z | include/utils/for_each.hpp | fengwang/ceras | 15d10e8909ded656f45201aecc45b8eefe961b2d | [
"BSD-3-Clause"
] | 7 | 2021-01-07T08:52:39.000Z | 2022-03-08T13:04:37.000Z | #ifndef FOR_EACH_HPP_INCLUDED_DSPOJSADLK111111111111111111111983UY4KAJSLFLKJFDIF
#define FOR_EACH_HPP_INCLUDED_DSPOJSADLK111111111111111111111983UY4KAJSLFLKJFDIF
#include "../includes.hpp"
#include "./range.hpp"
#include "./parallel.hpp"
namespace ceras
{
namespace// anonymous namespace
{
template < std::size_t Index, typename Type, typename... Types >
struct extract_type_forward
{
typedef typename extract_type_forward < Index - 1, Types... >::result_type result_type;
};
template < typename Type, typename... Types >
struct extract_type_forward< 1, Type, Types... >
{
typedef Type result_type;
};
template < typename Type, typename... Types >
struct extract_type_forward< 0, Type, Types... >
{
struct index_parameter_for_extract_type_forwrod_should_not_be_0;
typedef index_parameter_for_extract_type_forwrod_should_not_be_0 result_type;
};
template < std::size_t Index, typename... Types >
struct extract_type_backward
{
typedef typename extract_type_forward <sizeof...( Types ) - Index + 1, Types...>::result_type result_type;
};
template < std::size_t Index, typename... Types >
struct extract_type
{
typedef typename extract_type_forward< Index, Types... >::result_type result_type;
};
template < typename Function, typename InputIterator1, typename... InputIteratorn >
constexpr Function _for_each_n( Function f, std::size_t n, InputIterator1 begin1, InputIteratorn... beginn )
{
//for ( auto idx : range( n ) ) f( *(begin1+idx), *(beginn+idx)... );
auto const& func = [&]( std::uint_least64_t idx )
{
f( *(begin1+idx), *(beginn+idx)... );
};
parallel( func, 0UL, n );
return f;
}
template < typename Function, typename InputIterator1, typename... InputIteratorn >
constexpr Function _for_each( Function f, InputIterator1 begin1, InputIterator1 end1, InputIteratorn... beginn )
{
return _for_each_n( f, std::distance( begin1, end1 ), begin1, beginn... );
}
struct dummy { };
template < typename... Types_N >
struct for_each_impl_with_dummy
{
typedef typename extract_type_backward< 1, Types_N... >::result_type return_type;
template < typename Predict, typename... Types >
constexpr Predict impl( Predict p, dummy, Types... types ) const
{
return _for_each( p, types... );
}
template < typename S, typename... Types >
constexpr return_type impl( S s, Types... types ) const
{
return impl( types..., s );
}
};
}//anonymous namespace
template < typename... Types >
constexpr typename extract_type_backward< 1, Types... >::result_type for_each( Types... types ) // Types are simple enough to pass by value
{
static_assert( sizeof...( types ) > 2, "f::for_each requires at least 3 arguments" );
return for_each_impl_with_dummy< Types... >().impl( types..., dummy{} );
}
}//namespace ceras
#endif//FOR_EACH_HPP_INCLUDED_DSPOJSADLK111111111111111111111983UY4KAJSLFLKJFDIF
| 36.677419 | 143 | 0.61243 | fengwang |
6dc5b8583cf7a282574ac4c5797c9933b8ca818d | 261 | hpp | C++ | core/Exception.hpp | longzuo/SimpleKeyValueDb | ac5ba1184f3ce273ba9a0b1160c091de9902c0f6 | [
"MIT"
] | 1 | 2019-05-25T11:17:21.000Z | 2019-05-25T11:17:21.000Z | core/Exception.hpp | longzuo/SimpleKeyValueDb | ac5ba1184f3ce273ba9a0b1160c091de9902c0f6 | [
"MIT"
] | null | null | null | core/Exception.hpp | longzuo/SimpleKeyValueDb | ac5ba1184f3ce273ba9a0b1160c091de9902c0f6 | [
"MIT"
] | null | null | null | #ifndef SDB_EXCEPTIONS_HPP
#define SDB_EXCEPTIONS_HPP
#include <stdexcept>
namespace SDB {
class SdbException : public std::runtime_error {
public:
explicit SdbException(const std::string& msg) : std::runtime_error(msg) {}
};
} // namespace SDB
#endif | 21.75 | 78 | 0.743295 | longzuo |
6dcb24e72c474a1f85ff67f1563500db6cb00701 | 2,225 | cpp | C++ | core/warp_solver/RigidSolver.cpp | mihaibujanca/surfelwarp | 3b424f912b2a90412ad781940b071520825c3030 | [
"BSD-3-Clause"
] | null | null | null | core/warp_solver/RigidSolver.cpp | mihaibujanca/surfelwarp | 3b424f912b2a90412ad781940b071520825c3030 | [
"BSD-3-Clause"
] | null | null | null | core/warp_solver/RigidSolver.cpp | mihaibujanca/surfelwarp | 3b424f912b2a90412ad781940b071520825c3030 | [
"BSD-3-Clause"
] | 1 | 2020-07-15T05:54:31.000Z | 2020-07-15T05:54:31.000Z | //
// Created by wei on 5/22/18.
//
#include "common/ConfigParser.h"
#include "core/warp_solver/RigidSolver.h"
#include <Eigen/Eigen>
surfelwarp::RigidSolver::RigidSolver() {
//Init the intrisic for projection
const auto& config = ConfigParser::Instance();
m_project_intrinsic = config.rgb_intrinsic_clip();
m_image_rows = config.clip_image_rows();
m_image_cols = config.clip_image_cols();
//Init the world2camera
m_curr_world2camera = mat34::identity();
//Allocate the buffer
allocateReduceBuffer();
}
surfelwarp::RigidSolver::~RigidSolver() {
}
void surfelwarp::RigidSolver::SetInputMaps(
const surfelwarp::Renderer::SolverMaps &solver_maps,
const surfelwarp::CameraObservation &observation,
const mat34& init_world2camera
) {
m_solver_maps.live_vertex_map = solver_maps.warp_vertex_map;
m_solver_maps.live_normal_map = solver_maps.warp_normal_map;
m_observation.vertex_map = observation.vertex_config_map;
m_observation.normal_map = observation.normal_radius_map;
m_curr_world2camera = init_world2camera;
}
surfelwarp::mat34 surfelwarp::RigidSolver::Solve(int max_iters, cudaStream_t stream) {
//The solver iteration
for(int i = 0; i < max_iters; i++) {
rigidSolveDeviceIteration(stream);
rigidSolveHostIterationSync(stream);
}
//The updated world2camera
return m_curr_world2camera;
}
void surfelwarp::RigidSolver::rigidSolveHostIterationSync(cudaStream_t stream) {
//Sync before using the data
cudaSafeCall(cudaStreamSynchronize(stream));
//Load the hsot array
const auto& host_array = m_reduced_matrix_vector.HostArray();
//Load the data into Eigen
auto shift = 0;
#pragma unroll
for (int i = 0; i < 6; i++) {
for (int j = i; j < 6; j++) {
const float value = host_array[shift++];
JtJ_(i, j) = value;
JtJ_(j, i) = value;
}
}
for (int i = 0; i < 6; i++) {
const float value = host_array[shift++];
JtErr_[i] = value;
}
//Solve it
Eigen::Matrix<float, 6, 1> x = JtJ_.llt().solve(JtErr_).cast<float>();
//Update the se3
const float3 twist_rot = make_float3(x(0), x(1), x(2));
const float3 twist_trans = make_float3(x(3), x(4), x(5));
const mat34 se3_update(twist_rot, twist_trans);
m_curr_world2camera = se3_update * m_curr_world2camera;
} | 26.807229 | 86 | 0.733483 | mihaibujanca |
6dcf9957d8485f31f9bdd11b7d3b47c283043e7d | 1,574 | hpp | C++ | include/pique/data/grid.hpp | daboyuka/PIQUE | d0e2ba4cc47aaeaf364b3c76339306e1795adb5e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/pique/data/grid.hpp | daboyuka/PIQUE | d0e2ba4cc47aaeaf364b3c76339306e1795adb5e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/pique/data/grid.hpp | daboyuka/PIQUE | d0e2ba4cc47aaeaf364b3c76339306e1795adb5e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 David A. Boyuka II
*
* 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.
*/
/*
* grid.hpp
*
* Created on: Jan 24, 2014
* Author: David A. Boyuka II
*/
#ifndef GRID_HPP_
#define GRID_HPP_
#include <boost/smart_ptr.hpp>
class Grid : public std::vector< uint64_t > {
public:
enum class Linearization { ROW_MAJOR_ORDER, Z_ORDER, MORTON_ORDER = Z_ORDER /* alias */, };
public:
using ParentType = std::vector< uint64_t >;
Grid(Linearization lin = Linearization::ROW_MAJOR_ORDER) : ParentType(), lin(lin) {}
Grid(std::vector< uint64_t > &&dims, Linearization lin = Linearization::ROW_MAJOR_ORDER) : ParentType(std::move(dims)), lin(lin) {}
Grid(std::initializer_list< uint64_t > &&dims) : ParentType(std::move(dims)), lin(Linearization::ROW_MAJOR_ORDER) {}
Linearization get_linearization() const { return lin; }
uint64_t get_npoints() const {
uint64_t count = 1;
for (uint64_t dim : *this)
count *= dim;
return count;
}
private:
Linearization lin;
};
#endif /* GRID_HPP_ */
| 29.698113 | 135 | 0.691868 | daboyuka |
6dd12f37c7e32ea04ee35dd4e712e20a5e481085 | 3,554 | hpp | C++ | src/Generator/Polar/Generator_polar.hpp | aff3ct/polar_decoder_gen | 7d02025aa62bbef58b88f8fca65f5ee9ed86727e | [
"MIT"
] | 8 | 2018-03-14T22:17:16.000Z | 2021-05-31T23:29:03.000Z | src/Generator/Polar/Generator_polar.hpp | aff3ct/polar_decoder_gen | 7d02025aa62bbef58b88f8fca65f5ee9ed86727e | [
"MIT"
] | 1 | 2017-09-30T01:02:23.000Z | 2018-03-16T09:01:33.000Z | src/Generator/Polar/Generator_polar.hpp | aff3ct/polar_decoder_gen | 7d02025aa62bbef58b88f8fca65f5ee9ed86727e | [
"MIT"
] | 2 | 2019-09-16T08:30:13.000Z | 2019-12-17T02:15:34.000Z | #ifndef GENERATOR_POLAR_SYS_
#define GENERATOR_POLAR_SYS_
#include <map>
#include <vector>
#include <mipp.h>
#include <aff3ct.hpp>
#include "../Generator.hpp"
namespace aff3ct
{
namespace generator
{
class Generator_polar : public Generator
{
protected:
const int K; // k bits input
const int N; // n bits input
const int m; // graph depth
const float snr;
const std::vector<bool>& frozen_bits;
const std::vector<tools::Pattern_polar_i*> &patterns;
const tools::Pattern_polar_i &pattern_rate0;
const tools::Pattern_polar_i &pattern_rate1;
tools::Pattern_polar_parser parser;
std::string mother_class_name;
std::string MOTHER_CLASS_NAME;
std::string fbits_name;
std::ostream &dec_stream;
std::ostream &short_dec_stream;
std::ostream &graph_stream;
std::ostream &short_graph_stream;
std::string tab;
const int inlining_level;
std::vector<std::vector<int>> stats;
std::map<std::string, int> subtree_occurences;
std::map<std::string, int> subtree_occurences_cpy;
std::map<std::string, std::string> subtree_nodes;
unsigned n_nodes_before_compression;
unsigned n_nodes_after_compression;
const bool enable_short_decoder;
public:
Generator_polar(const int& K,
const int& N,
const float& snr,
const std::vector<bool>& frozen_bits,
const std::vector<tools::Pattern_polar_i*> &patterns,
const int idx_r0,
const int idx_r1,
std::string mother_class_name,
std::string MOTHER_CLASS_NAME,
std::ostream &dec_stream = std::cout,
std::ostream &short_dec_stream = std::cout,
std::ostream &graph_stream = std::cout,
std::ostream &short_graph_stream = std::cout,
const bool enable_short_decoder = true);
virtual ~Generator_polar();
void generate();
std::string get_class_name();
unsigned long get_n_generated_nodes ( int graph_depth = -1) const;
unsigned long get_n_generated_nodes_by_pattern(std::size_t pattern_hash, int graph_depth = -1) const;
protected:
virtual void generate_header(const std::string mother_class_name,
const std::vector<bool> &frozen_bits,
const std::string fbits_name,
std::ostream &stream) = 0;
virtual void generate_class_header(const std::string class_name,
const std::string fbits_name,
std::ostream &stream1,
std::ostream &stream2) = 0;
virtual void generate_class_footer( std::ostream &stream) = 0;
virtual void generate_footer ( std::ostream &stream) = 0;
virtual void recursive_generate_decoder (const tools::Binary_node<tools::Pattern_polar_i>* node_curr, std::ostream &stream) = 0;
virtual void recursive_generate_short_decoder(const tools::Binary_node<tools::Pattern_polar_i>* node_curr, std::ostream &stream) = 0;
private:
void recursive_generate_short_decoder_funcs(const tools::Binary_node<tools::Pattern_polar_i>* node_curr, std::ostream &stream);
void recursive_generate_graph (const tools::Binary_node<tools::Pattern_polar_i>* node_curr, std::ostream &stream);
void recursive_generate_short_graph (const tools::Binary_node<tools::Pattern_polar_i>* node_curr, std::ostream &stream);
};
}
}
#endif /* GENERATOR_POLAR_SYS_ */
| 35.188119 | 134 | 0.655318 | aff3ct |
6dd25a7eb3167e6380786d56bfe0fe1389550fa3 | 33,982 | cpp | C++ | cuda/cudamd/Host.cpp | vakuras/moleculardynamics | f9c6b03db7df8e429f72fa17b5ccfd98d08ee272 | [
"MIT"
] | null | null | null | cuda/cudamd/Host.cpp | vakuras/moleculardynamics | f9c6b03db7df8e429f72fa17b5ccfd98d08ee272 | [
"MIT"
] | null | null | null | cuda/cudamd/Host.cpp | vakuras/moleculardynamics | f9c6b03db7df8e429f72fa17b5ccfd98d08ee272 | [
"MIT"
] | null | null | null | ///
/// Host Implementation
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by Vadim Kuras. 2009-2010.
///
#include "Host.h"
///
/// Simulation main host function
///
int hostMain(CUdevice device, char * module_path, configuration * config)
{
real4 * posArray; //positions (host)
real3 * velocityArray; //velocity (host)
bool * flag; //box hit flag (host)
int * ljList = NULL; //lennard jones neigbor list pointer
int * mbList = NULL; //many body neigbor list pointer
listSettings lj; //lennard jones neigbor list settings
listSettings mb; //many body neigbor list settings
float highestVelocity; //heighest velocity
int timesteps; //timestep counter
int ljNextBuild; //on which timestep to call the build of the lennard jones list
int mbNextBuild; //on which timestep to call the build of the many body list
float boxSize=pow((float)(config->LennardJonesParticles + config->ManyBodyParticles),1.0f/3.0f)*52.8f; //box size
float boxSizeList; //box size for the neighbor lists
int buckets; //bucket count for the neighbor list
bool fallbackmb = false; //fallback from tpp to bpp for many body
bool fallbacklj = false; //fallback from tpp to bpp for lennard jones
vector<results> resultVec; //results vector
vector<float*> posVec; //position vector for animation
vector<float*> velVec; //velocity vector for animation
#ifdef USECUDADEBUG
float * informationMemory; //information memory pointer
CUdeviceptr devInformation; //information memory pointer for cuda
//vibLJ, vibMB, kinetic, temperature, centerOfMass, momentum
const int informationSize = sizeof(float)+sizeof(float)+sizeof(float)+sizeof(float)+sizeof(float3)+sizeof(real3);
#endif
//device variables
CUdeviceptr devPosArray; //positions cuda pointer
CUdeviceptr devVelocityArray; //velocity cuda pointer
CUdeviceptr devAAccArray; //acceleration cuda pointer
CUdeviceptr devForceArray; //force cuda pointer
CUdeviceptr devBAccArray; //b-acc cuda pointer
CUdeviceptr devCAccArray; //c-acc cuda pointer
CUdeviceptr devMemAlloc; //device block-shared memory pointer
CUdeviceptr devFlag; //device box-hit-flag
CUcontext context; //device context
CUmodule module; //cude module (.ptx file)
//function pointers from module:
#ifdef USECUDADEBUG
CUfunction performCalculations;
CUfunction calculatePotentional;
#endif
CUfunction correct;
CUfunction predict;
CUfunction lennardJonesForces;
CUfunction lennardJonesForcesBPP;
CUfunction manyBodyForces1;
CUfunction manyBodyForces2;
CUfunction manyBodyForcesBPP1;
CUfunction manyBodyForcesBPP2;
CUfunction calculateAccelerations;
//textures for neighbor lists
CUarray devLjList = NULL;
CUarray devMbList = NULL;
CUtexref devLjTexRef = NULL;
CUtexref devMbTexRef = NULL;
//function build helpers - for use by consts defined in Host.h (CUDA_DEF_SET, CUDA_RESET_OFFSET... and so)
void * ptr;
int offset;
unsigned int val;
float fval;
int nlsoffset; //neighbor list 'largest list size' byte offset in the byte array of the force calculation functions
//block configuration
int BlocksPerGrid = config->CudaBlocks;
int ThreadsPerBlocks = (config->LennardJonesParticles + config->ManyBodyParticles)/BlocksPerGrid + ((config->LennardJonesParticles + config->ManyBodyParticles)%BlocksPerGrid == 0 ? 0:1);
int mbThreadsPerBlocks = config->ManyBodyParticles/BlocksPerGrid + (config->ManyBodyParticles%BlocksPerGrid == 0 ? 0:1);
//time-measure events
CUevent start;
CUevent stop;
float elapsedTime;
config->energyLoss = sqrt(config->energyLoss); //fix energy loss
//create context
CU_SAFE_CALL(cuCtxCreate(&context, 0, device));
//load module
CU_SAFE_CALL(cuModuleLoad(&module, module_path));
//get functions
#ifdef USECUDADEBUG
CU_SAFE_CALL(cuModuleGetFunction(&performCalculations, module, "performCalculations"));
CU_SAFE_CALL(cuModuleGetFunction(&calculatePotentional, module, "calculatePotentional"));
#endif
CU_SAFE_CALL(cuModuleGetFunction(&predict, module, "predict"));
CU_SAFE_CALL(cuModuleGetFunction(&correct, module, "correct"));
CU_SAFE_CALL(cuModuleGetFunction(&calculateAccelerations, module, "calculateAccelerations"));
if (config->useLennardJones) //if using lennard jones
{
CU_SAFE_CALL(cuModuleGetFunction(&lennardJonesForcesBPP, module, "lennardJonesForcesBPP"));
CU_SAFE_CALL(cuModuleGetFunction(&lennardJonesForces, module, "lennardJonesForces"));
}
if (config->useManyBody) //if using many body
{
CU_SAFE_CALL(cuModuleGetFunction(&manyBodyForcesBPP1, module, "manyBodyForcesBPP1"));
CU_SAFE_CALL(cuModuleGetFunction(&manyBodyForcesBPP2, module, "manyBodyForcesBPP2"));
CU_SAFE_CALL(cuModuleGetFunction(&manyBodyForces1, module, "manyBodyForces1"));
CU_SAFE_CALL(cuModuleGetFunction(&manyBodyForces2, module, "manyBodyForces2"));
CU_SAFE_CALL(cuMemAlloc(&devMemAlloc,sizeof(float2) * config->ManyBodyParticles * config->ManyBodyParticles)); //allocate memory used by many body
}
//set events
CU_SAFE_CALL(cuEventCreate(&start, CU_EVENT_DEFAULT));
CU_SAFE_CALL(cuEventCreate(&stop, CU_EVENT_DEFAULT));
//allocate memory for data on host (for future device mapping)
CU_SAFE_CALL(cuMemAllocHost((void**)&posArray, (config->LennardJonesParticles + config->ManyBodyParticles) * sizeof(real4)));
CU_SAFE_CALL(cuMemAllocHost((void**)&velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles) * sizeof(real3)));
#ifdef USECUDADEBUG
CU_SAFE_CALL(cuMemAllocHost((void**)&informationMemory, informationSize));
#endif
CU_SAFE_CALL(cuMemAllocHost((void**)&flag, sizeof(bool)));
//allocate memory for data on device
CU_SAFE_CALL(cuMemAlloc(&devPosArray,sizeof(real4) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemAlloc(&devVelocityArray,sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemAlloc(&devAAccArray,sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemAlloc(&devForceArray,sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemAlloc(&devBAccArray,sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemAlloc(&devCAccArray,sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
#ifdef USECUDADEBUG
CU_SAFE_CALL(cuMemAlloc(&devInformation,informationSize));
#endif
CU_SAFE_CALL(cuMemAlloc(&devFlag,sizeof(bool)));
//number of buckets for list hashs
buckets = (config->LennardJonesParticles + config->ManyBodyParticles) * 3;
mb.nlargestsize = lj.nlargestsize = 0;
if (config->useLennardJones) //set lennard jones list settings
{
lj.maxnlmove = ((config->LennardJonesRS) - (config->LennardJonesRCUT)) * 0.5f;
lj.maxnlmovesq = pow(lj.maxnlmove, 2);
lj.rcutsq = pow(config->LennardJonesRCUT,2);
lj.rcut = config->LennardJonesRCUT;
lj.rs = config->LennardJonesRS;
}
if (config->useManyBody) //set many body list settings
{
mb.maxnlmove = ((config->ManyBodyRS) - (config->ManyBodyRCUT)) * 0.5f;
mb.maxnlmovesq = pow(mb.maxnlmove, 2);
mb.rcutsq = pow(config->ManyBodyRCUT,2);
mb.rcut = config->ManyBodyRCUT;
mb.rs = config->ManyBodyRS;
}
#ifdef USECUDADEBUG
//parameter setup for performCalculations
CUDA_RESET_OFFSET; //reset offset to zero
CUDA_POINTER_ALLOC(performCalculations, devPosArray); //allocate pointer in the byte array of the function
CUDA_POINTER_ALLOC(performCalculations, devVelocityArray);
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(performCalculations, val); //allocate unsigned int in the byte array of the function
CUDA_POINTER_ALLOC(performCalculations, devInformation);
CU_SAFE_CALL(cuParamSetSize( performCalculations, offset )); //set byte array size
CU_SAFE_CALL(cuFuncSetBlockShape( performCalculations, 1, 1, 1 )); //set block grid
//parameter setup for calculatePotentional
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(calculatePotentional, devPosArray);
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(calculatePotentional, val);
CUDA_POINTER_ALLOC(calculatePotentional, devInformation);
CU_SAFE_CALL(cuParamSetSize( calculatePotentional, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( calculatePotentional, ThreadsPerBlocks, 1, 1 ));
#endif
//parameter setup for predict
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(predict, devPosArray);
CUDA_POINTER_ALLOC(predict, devVelocityArray);
CUDA_POINTER_ALLOC(predict, devAAccArray);
CUDA_POINTER_ALLOC(predict, devBAccArray);
CUDA_POINTER_ALLOC(predict, devCAccArray);
fval = config->DT;
CUDA_FLOAT_ALLOC(predict, fval); //allocate float in the byte array of the function
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(predict, val);
CU_SAFE_CALL(cuParamSetSize( predict, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( predict, ThreadsPerBlocks, 1, 1 ));
//parameter setup for correct
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(correct, devPosArray);
CUDA_POINTER_ALLOC(correct, devVelocityArray);
CUDA_POINTER_ALLOC(correct, devForceArray);
CUDA_POINTER_ALLOC(correct, devAAccArray);
CUDA_POINTER_ALLOC(correct, devBAccArray);
CUDA_POINTER_ALLOC(correct, devCAccArray);
fval = config->DT;
CUDA_FLOAT_ALLOC(correct, fval);
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(correct, val);
fval = boxSize;
CUDA_FLOAT_ALLOC(correct, fval);
CUDA_POINTER_ALLOC(correct, devFlag);
fval = config->energyLoss;
CUDA_FLOAT_ALLOC(correct, fval);
CU_SAFE_CALL(cuParamSetSize( correct, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( correct, ThreadsPerBlocks, 1, 1 ));
//parameter setup for calculateAccelerations
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(calculateAccelerations, devPosArray);
CUDA_POINTER_ALLOC(calculateAccelerations, devForceArray);
CUDA_POINTER_ALLOC(calculateAccelerations, devAAccArray);
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(calculateAccelerations, val);
CU_SAFE_CALL(cuParamSetSize( calculateAccelerations, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( calculateAccelerations, ThreadsPerBlocks, 1, 1 ));
if (config->useLennardJones)
{
//parameter setup for lennardJonesForcesBPP
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(lennardJonesForcesBPP, devPosArray);
CUDA_POINTER_ALLOC(lennardJonesForcesBPP, devForceArray);
fval = lj.rcutsq;
CUDA_FLOAT_ALLOC(lennardJonesForcesBPP, fval);
CU_SAFE_CALL(cuParamSetSize( lennardJonesForcesBPP, offset ));
//parameter setup for lennardJonesForces
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(lennardJonesForces, devPosArray);
CUDA_POINTER_ALLOC(lennardJonesForces, devForceArray);
val = 0; //temporarily
CUDA_GET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(lennardJonesForces, val);
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(lennardJonesForces, val);
fval = lj.rcutsq;
CUDA_FLOAT_ALLOC(lennardJonesForces, fval);
CU_SAFE_CALL(cuParamSetSize( lennardJonesForces, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( lennardJonesForces, ThreadsPerBlocks, 1, 1 ));
}
if (config->useManyBody)
{
//parameter setup for manyBodyForcesBPP1
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(manyBodyForcesBPP1, devPosArray);
CUDA_POINTER_ALLOC(manyBodyForcesBPP1, devForceArray);
fval = mb.rcutsq;
CUDA_FLOAT_ALLOC(manyBodyForcesBPP1, fval);
val = config->ManyBodyParticles;
CUDA_UINT_ALLOC(manyBodyForcesBPP1, val);
CUDA_POINTER_ALLOC(manyBodyForcesBPP1, devMemAlloc);
val = config->useLennardJones;
CUDA_UINT_ALLOC(manyBodyForcesBPP1, val);
CU_SAFE_CALL(cuParamSetSize( manyBodyForcesBPP1, offset ));
//parameter setup for manyBodyForcesBPP2
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(manyBodyForcesBPP2, devPosArray);
CUDA_POINTER_ALLOC(manyBodyForcesBPP2, devForceArray);
fval = mb.rcutsq;
CUDA_FLOAT_ALLOC(manyBodyForcesBPP2, fval);
val = config->ManyBodyParticles;
CUDA_UINT_ALLOC(manyBodyForcesBPP2, val);
CUDA_POINTER_ALLOC(manyBodyForcesBPP2, devMemAlloc);
CU_SAFE_CALL(cuParamSetSize( manyBodyForcesBPP2, offset ));
//parameter setup for manyBodyForces1
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(manyBodyForces1, devPosArray);
CUDA_POINTER_ALLOC(manyBodyForces1, devForceArray);
val = 0; //temporarily
CUDA_GET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(manyBodyForces1, val);
val = config->ManyBodyParticles;
CUDA_UINT_ALLOC(manyBodyForces1, val);
fval = mb.rcutsq;
CUDA_FLOAT_ALLOC(manyBodyForces1, fval);
CUDA_POINTER_ALLOC(manyBodyForces1, devMemAlloc);
val = config->useLennardJones;
CUDA_UINT_ALLOC(manyBodyForces1, val);
CU_SAFE_CALL(cuParamSetSize( manyBodyForces1, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForces1, mbThreadsPerBlocks, 1, 1 ));
//parameter setup for manyBodyForces2
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(manyBodyForces2, devPosArray);
CUDA_POINTER_ALLOC(manyBodyForces2, devForceArray);
val = 0; //temporarily
CUDA_UINT_ALLOC(manyBodyForces2, val);
val = config->ManyBodyParticles;
CUDA_UINT_ALLOC(manyBodyForces2, val);
fval = mb.rcutsq;
CUDA_FLOAT_ALLOC(manyBodyForces2, fval);
CUDA_POINTER_ALLOC(manyBodyForces2, devMemAlloc);
CU_SAFE_CALL(cuParamSetSize( manyBodyForces2, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForces2, mbThreadsPerBlocks, 1, 1 ));
}
for(float vxcm=config->vxcmFrom; vxcm<=config->vxcmTo; vxcm+=config->vxcmStep)
{
//init
timesteps = 0;
ljNextBuild = mbNextBuild = 0;
//information
int printout = config->OutputTimesteps; //next debug output time step
int animts = config->animts; //next animation save time step
//read input file
readInput(config, (float*) posArray, (float*) velocityArray);
//push the particles outside the box into the box & vxcm
for (int id=0; id< (config->LennardJonesParticles + config->ManyBodyParticles); id++)
{
if (fabs(posArray[id].x) > (boxSize/2))
posArray[id].x = (boxSize/2) * (posArray[id].x/fabs(posArray[id].x));
if (fabs(posArray[id].y) > (boxSize/2))
posArray[id].y = (boxSize/2) * (posArray[id].y/fabs(posArray[id].y));
if (fabs(posArray[id].z) > (boxSize/2))
posArray[id].z = (boxSize/2) * (posArray[id].z/fabs(posArray[id].z));
velocityArray[id].x += vxcm;
}
//copy position & velocity to device memory
CU_SAFE_CALL(cuMemcpyHtoD(devPosArray, posArray, sizeof(real4) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemcpyHtoD(devVelocityArray, velocityArray, sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
//zero some device memory
CU_SAFE_CALL(cuMemsetD32(devAAccArray, 0, 3 * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemsetD32(devBAccArray, 0, 3 * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemsetD32(devCAccArray, 0, 3 * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemsetD8(devFlag, 0, sizeof(bool)));
//before sim output
cout << fixed << setprecision(6); //set maximal precision for output
cout.setf(ios::fixed,ios::floatfield); //zero padding
cout << "Before Simulation [VXCM = " << vxcm << "]:" << endl;
//calculate highest velocity and boxSizeList
readyList(posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles), highestVelocity, boxSizeList);
if (config->useLennardJones)
{
//build lennard jones list
buildList(posArray, &lj, boxSizeList, buckets, highestVelocity, (config->LennardJonesParticles + config->ManyBodyParticles), ljNextBuild, 0, &ljList, config->DT, "ljTexRef", &devLjList, &devLjTexRef, &module);
//check if a fallback is to be used
fallbacklj = (lj.nlargestsize > THREADSPERBLOCK) && config->Fallback;
//set the 'largest list size' according to the new data
if (config->lennardJonesBPP && !fallbacklj)
{
if (lj.nlargestsize > 0)
{
CU_SAFE_CALL(cuFuncSetBlockShape( lennardJonesForcesBPP, lj.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( lennardJonesForcesBPP, lj.nlargestsize*sizeof(real4)));
}
}
else
{
val = lj.nlargestsize;
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(lennardJonesForces, val);
}
}
if (config->useManyBody)
{
//build many body list
buildList(posArray, &mb, boxSizeList, buckets, highestVelocity, config->ManyBodyParticles, mbNextBuild, 0, &mbList, config->DT, "mbTexRef", &devMbList, &devMbTexRef, &module);
//check if a fallback is to be used
fallbackmb = (mb.nlargestsize > THREADSPERBLOCK) && config->Fallback;
//set the 'largest list size' according to the new data
if (config->manyBodyBPP && !fallbackmb)
{
if (mb.nlargestsize>0)
{
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForcesBPP1, mb.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( manyBodyForcesBPP1, mb.nlargestsize*sizeof(real4)));
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForcesBPP2, mb.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( manyBodyForcesBPP2, mb.nlargestsize*sizeof(real4)));
}
}
else
{
val = mb.nlargestsize;
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(manyBodyForces1, val);
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(manyBodyForces2, val);
}
}
//perform the output function
#ifdef USECUDADEBUG
performOutput(resultVec, BlocksPerGrid, informationSize, informationMemory, devInformation, performCalculations, calculatePotentional, timesteps, config->DT, true);
#else
performOutput(&resultVec, (config->LennardJonesParticles + config->ManyBodyParticles), posArray, velocityArray, devPosArray, devVelocityArray, timesteps, config->DT, true);
#endif
cout << endl;
if (config->animts>-1)
pushAnim(posVec, velVec, posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles));
//measure & perform
CU_SAFE_CALL(cuEventRecord(start,0));
if (config->useLennardJones && lj.nlargestsize>0) //calculate force for lennard jones
{
if (config->lennardJonesBPP && !fallbacklj) //bpp and no fallback
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForcesBPP, (config->LennardJonesParticles + config->ManyBodyParticles), 1));
CU_SAFE_CALL(cuCtxSynchronize()); //synchronize context
}
else //tpp
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForces, BlocksPerGrid, 1));
CU_SAFE_CALL(cuCtxSynchronize()); //synchronize context
}
}
if (config->useManyBody && mb.nlargestsize>0) //calculate force for many body
{
if (config->manyBodyBPP && !fallbackmb) //bpp and no fallback
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP1, config->ManyBodyParticles, 1)); //b-o 1
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP2, config->ManyBodyParticles, 1)); //b-o 2
CU_SAFE_CALL(cuCtxSynchronize());
}
else //tpp
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces1, BlocksPerGrid, 1)); //b-o 1
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces2, BlocksPerGrid, 1)); //b-o 2
CU_SAFE_CALL(cuCtxSynchronize());
}
}
//calculate the accelerations after the force
CU_SAFE_CALL(cuLaunchGrid(calculateAccelerations, BlocksPerGrid, 1));
CU_SAFE_CALL(cuCtxSynchronize());
//while not reached the timestep goal
while(timesteps<config->Timesteps)
{
if (ljNextBuild == timesteps || mbNextBuild == timesteps) //is is time to build any of the lists?
{
//copy memory from device
CU_SAFE_CALL(cuMemcpyDtoH(posArray, devPosArray, sizeof(real4) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemcpyDtoH(velocityArray, devVelocityArray, sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
readyList(posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles), highestVelocity, boxSizeList);
if (config->useLennardJones && ljNextBuild == timesteps) //is it time to build the lj list?
{
buildList(posArray, &lj, boxSizeList, buckets, highestVelocity, (config->LennardJonesParticles + config->ManyBodyParticles), ljNextBuild, timesteps, &ljList, config->DT, "ljTexRef", &devLjList, &devLjTexRef, &module);
fallbacklj = (lj.nlargestsize > THREADSPERBLOCK) && config->Fallback; //check for fallback
//set the 'largest list size' according to the new data
if (config->lennardJonesBPP && !fallbacklj)
{
if (lj.nlargestsize > 0)
{
CU_SAFE_CALL(cuFuncSetBlockShape( lennardJonesForcesBPP, lj.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( lennardJonesForcesBPP, lj.nlargestsize*sizeof(real4)));
}
}
else
{
val = lj.nlargestsize;
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(lennardJonesForces, val);
}
}
if (config->useManyBody && mbNextBuild == timesteps) // is it time to build the mb list?
{
buildList(posArray, &mb, boxSizeList, buckets, highestVelocity, config->ManyBodyParticles, mbNextBuild, timesteps, &mbList, config->DT, "mbTexRef", &devMbList, &devMbTexRef, &module);
fallbackmb = (mb.nlargestsize > THREADSPERBLOCK) && config->Fallback; //check for fallback
//set the 'largest list size' according to the new data
if (config->manyBodyBPP && !fallbackmb)
{
if (mb.nlargestsize>0)
{
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForcesBPP1, mb.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( manyBodyForcesBPP1, mb.nlargestsize*sizeof(real4)));
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForcesBPP2, mb.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( manyBodyForcesBPP2, mb.nlargestsize*sizeof(real4)));
}
}
else
{
val = mb.nlargestsize;
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(manyBodyForces1, val);
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(manyBodyForces2, val);
}
}
}
//predict
CU_SAFE_CALL(cuLaunchGrid(predict, BlocksPerGrid,1));
CU_SAFE_CALL(cuCtxSynchronize());
//force lj
if (config->useLennardJones && lj.nlargestsize>0)
{
if (config->lennardJonesBPP && !fallbacklj)
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForcesBPP, (config->LennardJonesParticles + config->ManyBodyParticles),1));
CU_SAFE_CALL(cuCtxSynchronize());
}
else
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForces, BlocksPerGrid,1));
CU_SAFE_CALL(cuCtxSynchronize());
}
}
//force mb
if (config->useManyBody && mb.nlargestsize>0)
{
if (config->manyBodyBPP && !fallbackmb) //bpp and no fallback
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP1, config->ManyBodyParticles,1));
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP2, config->ManyBodyParticles,1));
CU_SAFE_CALL(cuCtxSynchronize());
}
else
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces1, BlocksPerGrid,1));
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces2, BlocksPerGrid,1));
CU_SAFE_CALL(cuCtxSynchronize());
}
}
//correct
CU_SAFE_CALL(cuLaunchGrid(correct, BlocksPerGrid,1));
CU_SAFE_CALL(cuCtxSynchronize());
//copy flag mem
CU_SAFE_CALL(cuMemcpyDtoH(flag, devFlag, sizeof(bool)));
if (*flag)
{
if (config->useLennardJones && lj.nlargestsize>0) //calculate force for lennard jones
{
if (config->lennardJonesBPP && !fallbacklj) //bpp and no fallback
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForcesBPP, (config->LennardJonesParticles + config->ManyBodyParticles), 1));
CU_SAFE_CALL(cuCtxSynchronize()); //synchronize context
}
else //tpp
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForces, BlocksPerGrid, 1));
CU_SAFE_CALL(cuCtxSynchronize()); //synchronize context
}
}
if (config->useManyBody && mb.nlargestsize>0) //calculate force for many body
{
if (config->manyBodyBPP && !fallbackmb) //bpp and no fallback
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP1, config->ManyBodyParticles, 1)); //b-o 1
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP2, config->ManyBodyParticles, 1)); //b-o 2
CU_SAFE_CALL(cuCtxSynchronize());
}
else //tpp
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces1, BlocksPerGrid, 1)); //b-o 1
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces2, BlocksPerGrid, 1)); //b-o 2
CU_SAFE_CALL(cuCtxSynchronize());
}
}
//calculate the accelerations after the force
CU_SAFE_CALL(cuLaunchGrid(calculateAccelerations, BlocksPerGrid, 1));
CU_SAFE_CALL(cuCtxSynchronize());
//clear flag
CU_SAFE_CALL(cuMemsetD8(devFlag, 0, sizeof(bool)));
}
//results
if (printout==timesteps)
{
#ifdef USECUDADEBUG
performOutput(resultVec, BlocksPerGrid, informationSize, informationMemory, devInformation, performCalculations, calculatePotentional, timesteps, config->DT, config->Debug);
#else
performOutput(&resultVec, (config->LennardJonesParticles + config->ManyBodyParticles), posArray, velocityArray, devPosArray, devVelocityArray, timesteps, config->DT, config->Debug);
#endif
printout += config->OutputTimesteps;
}
//animation
if (animts==timesteps)
{
//copy memory from device
CU_SAFE_CALL(cuMemcpyDtoH(posArray, devPosArray, sizeof(real4) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemcpyDtoH(velocityArray, devVelocityArray, sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
pushAnim(posVec, velVec, posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles));
animts += config->animts;
}
timesteps++;
}
//stop measuring
CU_SAFE_CALL(cuEventRecord(stop,0));
CU_SAFE_CALL(cuEventSynchronize(stop));
//calculate time
CU_SAFE_CALL(cuEventElapsedTime(&elapsedTime,start,stop));
//after sim output
cout << "\nAfter Simulation [VXCM = " << vxcm << "]:" << endl;
#ifdef USECUDADEBUG
performOutput(resultVec, BlocksPerGrid, informationSize, informationMemory, devInformation, performCalculations, calculatePotentional, timesteps, config->DT, true);
#else
performOutput(&resultVec, (config->LennardJonesParticles + config->ManyBodyParticles), posArray, velocityArray, devPosArray, devVelocityArray, timesteps, config->DT, true);
#endif
cout << "\nTime took: " << elapsedTime << "ms" << endl;
//copy memory from device
CU_SAFE_CALL(cuMemcpyDtoH(posArray, devPosArray, sizeof(real4) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemcpyDtoH(velocityArray, devVelocityArray, sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
//write the output
writeOutput(config, (float*) posArray, (float*) velocityArray);
//output info to log & results
writeResults(resultVec, config, elapsedTime, tailResults(posArray, config->ManyBodyParticles), vxcm);
if (config->animts>-1)
writeAnimationBinaryData(posVec, velVec, config, vxcm);
flushVectors(resultVec, posVec, velVec);
}
//release lists memory
if (ljList)
{
delete [] ljList;
ljList = NULL;
}
if (mbList)
{
delete [] mbList;
mbList = NULL;
}
//free events
CU_SAFE_CALL(cuEventDestroy(start));
CU_SAFE_CALL(cuEventDestroy(stop));
//free device memory
CU_SAFE_CALL(cuMemFree(devPosArray));
CU_SAFE_CALL(cuMemFree(devVelocityArray));
CU_SAFE_CALL(cuMemFree(devAAccArray));
CU_SAFE_CALL(cuMemFree(devForceArray));
CU_SAFE_CALL(cuMemFree(devBAccArray));
CU_SAFE_CALL(cuMemFree(devCAccArray));
#ifdef USECUDADEBUG
CU_SAFE_CALL(cuMemFree(devInformation));
#endif
CU_SAFE_CALL(cuMemFree(devFlag));
if (config->useManyBody)
CU_SAFE_CALL(cuMemFree(devMemAlloc));
//free memory
CU_SAFE_CALL(cuMemFreeHost(posArray));
CU_SAFE_CALL(cuMemFreeHost(velocityArray));
CU_SAFE_CALL(cuMemFreeHost(flag));
#ifdef USECUDADEBUG
CU_SAFE_CALL(cuMemFreeHost(informationMemory));
#endif
//drop context
CU_SAFE_CALL(cuCtxDetach(context));
//free module path
cutFree(module_path);
return EXIT_SUCCESS;
}
#ifdef USECUDADEBUG
void performOutput(vector<results> & resultVec, int BlocksPerGrid, int informationSize, float * informationMemory, CUdeviceptr & devInformation, CUfunction & performCalculations, CUfunction & calculatePotentional, int timesteps, float dt, bool print)
{
real3 cmassTmp;
real3 momentumTmp;
//reset information memory on device
CU_SAFE_CALL(cuMemsetD32(devInformation, 0, informationSize/sizeof(float)));
//kinetic, memontum an so
CU_SAFE_CALL(cuLaunchGrid(performCalculations, 1, 1));
CU_SAFE_CALL(cuCtxSynchronize());
//potentional energy calculation
CU_SAFE_CALL(cuLaunchGrid(calculatePotentional, BlocksPerGrid, 1));
CU_SAFE_CALL(cuCtxSynchronize());
//copy from device to host
CU_SAFE_CALL(cuMemcpyDtoH(informationMemory, devInformation, informationSize));
//fill results structure and push into vector
results res;
res.time = timesteps * dt;
res.ek = (double)*(informationMemory+2);
res.eu = (double)*informationMemory + (double)*(informationMemory+1);
res.e = (double)res.ek + res.eu;
res.temperature = (double)*(informationMemory+3);
cmassTmp = *(real3*)(informationMemory+4);
momentumTmp = *(real3*)(informationMemory+7);
res.centerOfMassx = (double)cmassTmp.x;
res.centerOfMassy = (double)cmassTmp.y;
res.centerOfMassz = (double)cmassTmp.z;
res.momentumx = (double)momentumTmp.x;
res.momentumy = (double)momentumTmp.y;
res.momentumz = (double)momentumTmp.z;
if (print) //debug-output
cout << "t=" << res.time
<< "\tT=" << res.temperature
<< "\tE=" << res.e
<< "\tEK=" << res.ek
<< "\tEU=" << res.eu
<< endl;
resultVec.push_back(res);
}
#else
void performOutput(vector<results> * resultVec, int NumberOfParticles, real4 * posArray, real3 * velocityArray, CUdeviceptr & devPosArray, CUdeviceptr & devVelocityArray, int timesteps, real dt, bool print)
{
CU_SAFE_CALL(cuMemcpyDtoH(posArray, devPosArray, sizeof(real4) * NumberOfParticles));
CU_SAFE_CALL(cuMemcpyDtoH(velocityArray, devVelocityArray, sizeof(real3) * NumberOfParticles));
performOutput(resultVec, NumberOfParticles, posArray, velocityArray, timesteps, dt, print);
}
#endif
///
/// Get Highest Velocity & Box Size
///
void readyList(real4 * posArray, real3 * velocityArray, int NumberOfParticles, float & highestVelocity, float & boxSize)
{
highestVelocity = 0;
boxSize = 0;
for(int i=0; i<NumberOfParticles; i++)
{
//calculate highest velocity
float velocity = sqrt(velocityArray[i].x * velocityArray[i].x + velocityArray[i].y * velocityArray[i].y + velocityArray[i].z * velocityArray[i].z);
if (velocity>highestVelocity)
highestVelocity = velocity;
//boxsize = (the particle that is far the most from 0,0,0) * 2
if (boxSize<abs(posArray[i].x))
boxSize = abs(posArray[i].x);
if (boxSize<abs(posArray[i].y))
boxSize = abs(posArray[i].y);
if (boxSize<abs(posArray[i].z))
boxSize = abs(posArray[i].z);
}
boxSize*=2; //final box size
}
///
/// Build Neighbor List
///
void buildList(real4 * posArray, listSettings * listsettings, float boxSize, int buckets, float highestVelocity, int NumberOfParticles, int & nextBuild, int currentTimestep, int ** list, float dt, char * lpTexRef, CUarray * cu_array, CUtexref * cu_texref, CUmodule * module)
{
CUDA_ARRAY_DESCRIPTOR desc;
CUDA_MEMCPY2D copyParam;
//free memory if needed
if (*list)
{
delete [] *list;
*list = NULL;
}
//build list
*list = buildNeighborList(posArray, listsettings, boxSize, buckets, NumberOfParticles);
//calculte next build time step
nextBuild = (int) ((listsettings->maxnlmove / highestVelocity) / fabs(dt));
nextBuild += currentTimestep;
//create texture
if (*cu_array)
CU_SAFE_CALL( cuArrayDestroy( *cu_array));
desc.Format = CU_AD_FORMAT_SIGNED_INT32;
desc.NumChannels = 1;
desc.Width = listsettings->nlistsize;
desc.Height = NumberOfParticles;
CU_SAFE_CALL( cuArrayCreate( cu_array, &desc ));
//set memory copy params host-to-cuda-array
memset(©Param, 0, sizeof(copyParam));
copyParam.dstMemoryType = CU_MEMORYTYPE_ARRAY;
copyParam.dstArray = *cu_array;
copyParam.srcMemoryType = CU_MEMORYTYPE_HOST;
copyParam.srcHost = *list;
copyParam.srcPitch = listsettings->nlistsize * sizeof(int);
copyParam.WidthInBytes = copyParam.srcPitch;
copyParam.Height = NumberOfParticles;
CU_SAFE_CALL(cuMemcpy2D(©Param));
//build texture
CU_SAFE_CALL(cuModuleGetTexRef(cu_texref, *module, lpTexRef));
CU_SAFE_CALL(cuTexRefSetArray(*cu_texref, *cu_array, CU_TRSA_OVERRIDE_FORMAT));
CU_SAFE_CALL(cuTexRefSetAddressMode(*cu_texref, 0, CU_TR_ADDRESS_MODE_CLAMP));
CU_SAFE_CALL(cuTexRefSetAddressMode(*cu_texref, 1, CU_TR_ADDRESS_MODE_CLAMP));
CU_SAFE_CALL(cuTexRefSetFilterMode(*cu_texref, CU_TR_FILTER_MODE_POINT));
CU_SAFE_CALL(cuTexRefSetFlags(*cu_texref, CU_TRSF_READ_AS_INTEGER));
CU_SAFE_CALL(cuTexRefSetFormat(*cu_texref, CU_AD_FORMAT_SIGNED_INT32, 1));
//free memory
if (*list)
{
delete [] *list;
*list = NULL;
}
} | 39.194925 | 275 | 0.731122 | vakuras |
6dd279a35cd5586705bac9ecb509f1606d9aba00 | 2,351 | cpp | C++ | examples/st7920_12864_8080_example.cpp | lin2010304125/rt-u8g2 | bca73e4406193e5986e0fffadc0aba2daa68bca1 | [
"CC-BY-3.0"
] | null | null | null | examples/st7920_12864_8080_example.cpp | lin2010304125/rt-u8g2 | bca73e4406193e5986e0fffadc0aba2daa68bca1 | [
"CC-BY-3.0"
] | null | null | null | examples/st7920_12864_8080_example.cpp | lin2010304125/rt-u8g2 | bca73e4406193e5986e0fffadc0aba2daa68bca1 | [
"CC-BY-3.0"
] | null | null | null | #include <rthw.h>
#include <rtthread.h>
#include <rtdevice.h>
#include <U8g2lib.h>
// You may reference Drivers/drv_gpio.c for pinout
// In u8x8.h #define U8X8_USE_PINS
#define ST7920_8080_PIN_D0 36 // PB15
#define ST7920_8080_PIN_D1 35 // PB14
#define ST7920_8080_PIN_D2 34 // PB13
#define ST7920_8080_PIN_D3 33 // PB12
#define ST7920_8080_PIN_D4 37 // PC6
#define ST7920_8080_PIN_D5 38 // PC7
#define ST7920_8080_PIN_D6 39 // PC8
#define ST7920_8080_PIN_D7 40 // PC9
#define ST7920_8080_PIN_EN 50 // PA15
#define ST7920_8080_PIN_CS U8X8_PIN_NONE
#define ST7920_8080_PIN_DC 44 // PA11
#define ST7920_8080_PIN_RST 45 // PA12
// Check https://github.com/olikraus/u8g2/wiki/u8g2setupcpp for all supported devices
static U8G2_ST7920_128X64_F_8080 u8g2(U8G2_R0,
ST7920_8080_PIN_D0,
ST7920_8080_PIN_D1,
ST7920_8080_PIN_D2,
ST7920_8080_PIN_D3,
ST7920_8080_PIN_D4,
ST7920_8080_PIN_D5,
ST7920_8080_PIN_D6,
ST7920_8080_PIN_D7,
/*enable=*/ ST7920_8080_PIN_EN,
/*cs=*/ ST7920_8080_PIN_CS,
/*dc=*/ ST7920_8080_PIN_DC,
/*reset=*/ ST7920_8080_PIN_RST);
static void u8g2_st7920_12864_8080_example(int argc,char *argv[])
{
u8g2.begin();
u8g2.clearBuffer(); // clear the internal memory
u8g2.setFont(u8g2_font_6x13_tr); // choose a suitable font
u8g2.drawStr(1, 18, "U8g2 on RT-Thread"); // write something to the internal memory
u8g2.sendBuffer(); // transfer internal memory to the display
u8g2.setFont(u8g2_font_unifont_t_symbols);
u8g2.drawGlyph(112, 56, 0x2603 );
u8g2.sendBuffer();
}
MSH_CMD_EXPORT(u8g2_st7920_12864_8080_example, st7920 12864 LCD sample);
| 47.979592 | 90 | 0.522756 | lin2010304125 |
6dd56544fcecaecfd25b6a183cc3753589d6bcc0 | 3,474 | inl | C++ | test/bincore.inl | PredatorCZ/PreCore | 98f5896e35371d034e6477dd0ce9edeb4fd8d814 | [
"Apache-2.0"
] | 5 | 2019-10-17T15:52:38.000Z | 2021-08-10T18:57:32.000Z | test/bincore.inl | PredatorCZ/PreCore | 98f5896e35371d034e6477dd0ce9edeb4fd8d814 | [
"Apache-2.0"
] | null | null | null | test/bincore.inl | PredatorCZ/PreCore | 98f5896e35371d034e6477dd0ce9edeb4fd8d814 | [
"Apache-2.0"
] | 1 | 2021-01-31T20:37:42.000Z | 2021-01-31T20:37:42.000Z | #include "../datas/binwritter.hpp"
#include "../datas/binreader.hpp"
#include <sstream>
struct BinStr00 {
int8 v0;
bool v1;
int16 v2;
uint32 v3;
};
struct BinStr00_Fc : BinStr00 {
void Read(BinReaderRef rd) {
rd.Read(v0);
rd.Read(v3);
}
void Write(BinWritterRef wr) const {
wr.Write(v0);
wr.Write(v3);
}
};
struct BinStr00_Sw : BinStr00 {
void SwapEndian() {
FByteswapper(v2);
FByteswapper(v3);
}
};
int test_bincore_00() {
std::stringstream ss;
BinWritterRef mwr(ss);
BinStr00_Fc tst = {};
tst.v0 = 15;
tst.v1 = true;
tst.v2 = 584;
tst.v3 = 12418651;
mwr.Write(tst);
tst = {};
tst.v0 = 1;
tst.v1 = false;
tst.v2 = 2;
tst.v3 = 3;
BinReaderRef mrd(ss);
mrd.Read(tst);
TEST_EQUAL(tst.v0, 15);
TEST_EQUAL(tst.v1, false);
TEST_EQUAL(tst.v2, 2);
TEST_EQUAL(tst.v3, 12418651);
mwr.SwapEndian(true);
mwr.Write(tst);
tst.v1 = true;
tst.v2 = 3;
mrd.SwapEndian(true);
mrd.Read(tst);
TEST_EQUAL(tst.v0, 15);
TEST_EQUAL(tst.v1, true);
TEST_EQUAL(tst.v2, 3);
TEST_EQUAL(tst.v3, 12418651);
mwr.Seek(5);
mwr.Skip(-2);
TEST_EQUAL(mwr.Tell(), 3);
mrd.Seek(0);
TEST_EQUAL(mrd.Tell(), 0);
mrd.Skip(10);
TEST_EQUAL(mrd.Tell(), 10);
mrd.Skip(-3);
TEST_EQUAL(mrd.Tell(), 7);
return 0;
};
struct wtcounter {
uint8 count;
uint8 someData;
wtcounter() = default;
wtcounter(size_t cnt) : count(cnt) {}
void Read(BinReaderRef rd) {
rd.Read(count);
}
void Write(BinWritterRef wr) const {
wr.Write(count);
}
operator size_t() const {return count;}
};
int test_bincore_01() {
std::stringstream ss;
BinWritterRef mwr(ss);
std::vector<BinStr00_Fc> vec;
BinStr00_Fc tst = {};
tst.v0 = 15;
tst.v1 = true;
tst.v2 = 584;
tst.v3 = 12418651;
vec.push_back(tst);
tst.v0 = 79;
tst.v1 = false;
tst.v2 = 2100;
tst.v3 = 4248613;
vec.push_back(tst);
mwr.WriteContainerWCount<wtcounter>(vec);
vec.clear();
BinReaderRef mrd(ss);
mrd.ReadContainer<wtcounter>(vec);
TEST_EQUAL(vec.size(), 2);
TEST_EQUAL(vec[0].v0, 15);
TEST_EQUAL(vec[0].v1, false);
TEST_EQUAL(vec[0].v2, 0);
TEST_EQUAL(vec[0].v3, 12418651);
TEST_EQUAL(vec[1].v0, 79);
TEST_EQUAL(vec[1].v1, false);
TEST_EQUAL(vec[1].v2, 0);
TEST_EQUAL(vec[1].v3, 4248613);
return 0;
};
int test_bincore_02() {
std::stringstream ss;
BinWritterRef mwr(ss);
std::vector<BinStr00_Sw> vec;
BinStr00_Sw tst = {};
tst.v0 = 15;
tst.v1 = true;
tst.v2 = 584;
tst.v3 = 12418651;
vec.push_back(tst);
tst.v0 = 79;
tst.v1 = false;
tst.v2 = 2100;
tst.v3 = 4248613;
vec.push_back(tst);
mwr.WriteContainerWCount<wtcounter>(vec);
vec.clear();
BinReaderRef mrd(ss);
mrd.ReadContainer<wtcounter>(vec);
TEST_EQUAL(vec.size(), 2);
TEST_EQUAL(vec[0].v0, 15);
TEST_EQUAL(vec[0].v1, true);
TEST_EQUAL(vec[0].v2, 584);
TEST_EQUAL(vec[0].v3, 12418651);
TEST_EQUAL(vec[1].v0, 79);
TEST_EQUAL(vec[1].v1, false);
TEST_EQUAL(vec[1].v2, 2100);
TEST_EQUAL(vec[1].v3, 4248613);
mwr.SwapEndian(true);
mwr.WriteContainerWCount(vec);
mrd.SwapEndian(true);
vec.clear();
mrd.ReadContainer(vec);
TEST_EQUAL(vec.size(), 2);
TEST_EQUAL(vec[0].v0, 15);
TEST_EQUAL(vec[0].v1, true);
TEST_EQUAL(vec[0].v2, 584);
TEST_EQUAL(vec[0].v3, 12418651);
TEST_EQUAL(vec[1].v0, 79);
TEST_EQUAL(vec[1].v1, false);
TEST_EQUAL(vec[1].v2, 2100);
TEST_EQUAL(vec[1].v3, 4248613);
return 0;
};
| 16.782609 | 43 | 0.629246 | PredatorCZ |
6dd835d8b2e4ceaab87e1ac475894dc2c3cead8a | 12,243 | cpp | C++ | Blech/test.cpp | Natedog2012/dll | 5fb9414a5ebddf9c37809517eaf378a26b422d61 | [
"MIT"
] | 3 | 2021-06-25T00:03:25.000Z | 2021-11-30T19:45:27.000Z | Blech/test.cpp | Natedog2012/dll | 5fb9414a5ebddf9c37809517eaf378a26b422d61 | [
"MIT"
] | null | null | null | Blech/test.cpp | Natedog2012/dll | 5fb9414a5ebddf9c37809517eaf378a26b422d61 | [
"MIT"
] | 3 | 2021-09-21T23:33:31.000Z | 2022-02-18T08:13:20.000Z | #include "Blech.h"
#define CheckOne(ID) \
if (nevent != 1) { \
printf("bad event count %d != 1\n", nevent); \
exit(1); \
} \
if (eventarray[0].id != ID) { \
printf("bad event %d != " #ID "\n", eventarray[0].id); \
exit(1); \
}
struct {
int id, nvalues;
char name[50][100];
char value[50][100];
} eventarray[20];
int nevent = 0;
void __stdcall MyEvent(unsigned long ID, void *pData, PBLECHVALUE pValues)
{
int i = 0;
printf("MyEvent(%d,%d,%X)\n", ID, pData, pValues);
eventarray[nevent].id = (int) pData;
while (pValues) {
printf("\t'%s'=>'%s'\n", pValues->Name, pValues->Value);
strcpy(eventarray[nevent].name[i], pValues->Name);
strcpy(eventarray[nevent].value[i], pValues->Value);
i++;
pValues = pValues->pNext;
}
eventarray[nevent].nvalues = i;
printf("\n");
nevent++;
}
main()
{
Blech b('#');
int j = 0, i = 0, eventid[200];
for (int x = 0; x < 2; x++) {
eventid[i++] = b.AddEvent("Text with #variable# portion", MyEvent, (void *) 0);
eventid[i++] = b.AddEvent("#*#Text with #variable# portion", MyEvent, (void *) 1);
eventid[i++] = b.AddEvent("thisshouldnevertrigger", MyEvent, (void *) 2);
eventid[i++] = b.AddEvent("#*#while stunned#*#", MyEvent, (void *) 3);
eventid[i++] = b.AddEvent("#*#has been slain#*#", MyEvent, (void *) 4);
eventid[i++] = b.AddEvent("#*#gain experience!#*#", MyEvent, (void *) 5);
eventid[i++] = b.AddEvent("#*#Insufficient mana#*#", MyEvent, (void *) 6);
eventid[i++] = b.AddEvent("[MQ2] getout", MyEvent, (void *) 7);
eventid[i++] = b.AddEvent("#*#target is out of range#*#", MyEvent, (void *) 8);
eventid[i++] = b.AddEvent("You cannot see#*#", MyEvent, (void *) 9);
eventid[i++] =
b.AddEvent("#*#Returning to home point, please wait...#*#", MyEvent, (void *) 10);
eventid[i++] = b.AddEvent("#*#you have been slain#*#", MyEvent, (void *) 11);
eventid[i++] = b.AddEvent("#*#You have entered#*#", MyEvent, (void *) 12);
eventid[i++] = b.AddEvent("The shield fades away.", MyEvent, (void *) 13);
eventid[i++] = b.AddEvent("The maelstrom dissipates.", MyEvent, (void *) 14);
eventid[i++] = b.AddEvent("You have been summoned!", MyEvent, (void *) 15);
eventid[i++] = b.AddEvent("#*# YOU for #*#", MyEvent, (void *) 16);
eventid[i++] = b.AddEvent("#*# YOU, but #*#", MyEvent, (void *) 17);
eventid[i++] = b.AddEvent("[MQ2] nuke1 #1#", MyEvent, (void *) 18);
eventid[i++] = b.AddEvent("[MQ2] nuke2 #1#", MyEvent, (void *) 19);
eventid[i++] = b.AddEvent("[MQ2] domodrod", MyEvent, (void *) 20);
eventid[i++] = b.AddEvent("[MQ2] conc", MyEvent, (void *) 21);
eventid[i++] = b.AddEvent("[MQ2] concnum #1#", MyEvent, (void *) 22);
eventid[i++] = b.AddEvent("[MQ2] myfamiliar #1#", MyEvent, (void *) 23);
eventid[i++] = b.AddEvent("[MQ2] mainnukenum #1#", MyEvent, (void *) 24);
eventid[i++] = b.AddEvent("[MQ2] endnukenum #1#", MyEvent, (void *) 25);
eventid[i++] = b.AddEvent("[MQ2] maxbuffs #1#", MyEvent, (void *) 26);
eventid[i++] = b.AddEvent("[MQ2] mobhealth #1#", MyEvent, (void *) 27);
eventid[i++] = b.AddEvent("[MQ2] staffhealth #1#", MyEvent, (void *) 28);
eventid[i++] = b.AddEvent("[MQ2] stopnuke #1#", MyEvent, (void *) 29);
eventid[i++] = b.AddEvent("[MQ2] stopnuke2 #1#", MyEvent, (void *) 30);
eventid[i++] = b.AddEvent("[MQ2] engagedistance #1#", MyEvent, (void *) 31);
eventid[i++] = b.AddEvent("[MQ2] assist", MyEvent, (void *) 32);
eventid[i++] = b.AddEvent("[MQ2] doxuzl", MyEvent, (void *) 33);
eventid[i++] = b.AddEvent("[MQ2] manarobe", MyEvent, (void *) 34);
eventid[i++] = b.AddEvent("[MQ2] xuzlperc #1#", MyEvent, (void *) 35);
eventid[i++] = b.AddEvent("[MQ2] temp", MyEvent, (void *) 36);
eventid[i++] = b.AddEvent("[MQ2] dosnare", MyEvent, (void *) 37);
eventid[i++] = b.AddEvent("[MQ2] snareperc #1#", MyEvent, (void *) 38);
eventid[i++] = b.AddEvent("[MQ2] ss", MyEvent, (void *) 39);
eventid[i++] = b.AddEvent("[MQ2] mw", MyEvent, (void *) 40);
eventid[i++] = b.AddEvent("[MQ2] timewand", MyEvent, (void *) 41);
eventid[i++] = b.AddEvent("[MQ2] epic", MyEvent, (void *) 42);
eventid[i++] = b.AddEvent("[MQ2] forceshield", MyEvent, (void *) 43);
eventid[i++] = b.AddEvent("[MQ2] autosit", MyEvent, (void *) 44);
eventid[i++] = b.AddEvent("[MQ2] som", MyEvent, (void *) 45);
eventid[i++] = b.AddEvent("[MQ2] ma #1#", MyEvent, (void *) 46);
eventid[i++] = b.AddEvent("[MQ2] sa #1#", MyEvent, (void *) 47);
eventid[i++] = b.AddEvent("[MQ2] ta #1#", MyEvent, (void *) 48);
eventid[i++] = b.AddEvent("[MQ2] cycle", MyEvent, (void *) 49);
eventid[i++] = b.AddEvent("The magical barrier fades #*#", MyEvent, (void *) 50);
eventid[i++] = b.AddEvent("The blue aura fades #*#", MyEvent, (void *) 51);
eventid[i++] = b.AddEvent("[MQ2] exclude #*#", MyEvent, (void *) 52);
eventid[i++] = b.AddEvent("[MQ2] include #*#", MyEvent, (void *) 53);
eventid[i++] = b.AddEvent("[MQ2] addmaster #*#", MyEvent, (void *) 54);
eventid[i++] = b.AddEvent("[MQ2] delmaster #*#", MyEvent, (void *) 55);
eventid[i++] = b.AddEvent("[MQ2] addjunk #*#", MyEvent, (void *) 56);
eventid[i++] = b.AddEvent("[MQ2] deljunk #*#", MyEvent, (void *) 57);
eventid[i++] = b.AddEvent("[MQ2] pause", MyEvent, (void *) 58);
eventid[i++] = b.AddEvent("[MQ2] itemset #1# #2# #3#", MyEvent, (void *) 59);
eventid[i++] = b.AddEvent("[MQ2] itembounce #1# #2#", MyEvent, (void *) 60);
eventid[i++] = b.AddEvent("[MQ2] itemcast #1#", MyEvent, (void *) 61);
eventid[i++] = b.AddEvent("[MQ2] leash#*#", MyEvent, (void *) 62);
eventid[i++] = b.AddEvent("[MQ2] autofollow#*#", MyEvent, (void *) 63);
eventid[i++] = b.AddEvent("[MQ2] stopfollow#*#", MyEvent, (void *) 64);
eventid[i++] = b.AddEvent("[MQ2] afhelp", MyEvent, (void *) 65);
eventid[i++] = b.AddEvent("[MQ2] nukepause #*#", MyEvent, (void *) 66);
eventid[i++] = b.AddEvent("[MQ2] doharvest", MyEvent, (void *) 67);
eventid[i++] = b.AddEvent("[MQ2] harvestperc #1#", MyEvent, (void *) 68);
eventid[i++] = b.AddEvent("[MQ2] medtoggle", MyEvent, (void *) 69);
eventid[i++] = b.AddEvent("[MQ2] dopreconc", MyEvent, (void *) 70);
eventid[i++] = b.AddEvent("[MQ2] dopreconcxxxxx", MyEvent, (void *) 71);
eventid[i++] = b.AddEvent("[MQ2] preconcnum #1#", MyEvent, (void *) 72);
eventid[i++] = b.AddEvent("[MQ2] tlocate #*#", MyEvent, (void *) 73);
eventid[i++] = b.AddEvent("[MQ2] getout", MyEvent, (void *) 74);
eventid[i++] = b.AddEvent("You gain#*#", MyEvent, (void *) 75);
eventid[i++] = b.AddEvent("[MQ2] SetPCRadius#*#", MyEvent, (void *) 76);
eventid[i++] = b.AddEvent("[MQ2] SetNPCRadius#*#", MyEvent, (void *) 77);
eventid[i++] = b.AddEvent("[MQ2] Autoassist#*#", MyEvent, (void *) 78);
eventid[i++] = b.AddEvent("[MQ2] AutoTargetSwitch#*#", MyEvent, (void *) 79);
eventid[i++] = b.AddEvent("[MQ2] AutoTraps#*#", MyEvent, (void *) 80);
eventid[i++] = b.AddEvent("#1# begins to cast a spell.", MyEvent, (void *) 81);
eventid[i++] = b.AddEvent("#1# hits you for #2# damage.", MyEvent, (void *) 82);
nevent = 0;
b.Feed("[MQ2] Autoassist your mom");
CheckOne(78);
nevent = 0;
b.Feed("Text with extra bits of portion");
if (nevent != 2) {
printf("bad event count %d != 2\n", nevent);
exit(1);
}
if ((eventarray[0].id != 0) && (eventarray[0].id != 1)) {
printf("wrong events triggerd %d -- not 0 or 1\n", eventarray[0].id);
exit(1);
}
nevent = 0;
b.Feed("notText with extra bits of portion");
CheckOne(1);
nevent = 0;
b.Feed("[MQ2] maxbuffs 145");
CheckOne(26);
if (eventarray[0].nvalues != 1) {
printf("bad value count %d != 1\n", eventarray[0].nvalues);
exit(1);
}
if (strcmp(eventarray[0].name[0], "1")) {
printf("bad value name '%s' != 1\n", eventarray[0].name[0]);
exit(1);
}
if (strcmp(eventarray[0].value[0], "145")) {
printf("bad value value '%s' != 145\n", eventarray[0].value[0]);
exit(1);
}
nevent = 0;
b.Feed("The magical barrier fades yourmoma");
CheckOne(50);
if (eventarray[0].nvalues != 1) {
printf("bad value count %d != 1\n", eventarray[0].nvalues);
exit(1);
}
if (strcmp(eventarray[0].name[0], "*")) {
printf("bad value name '%s' != *\n", eventarray[0].name[0]);
exit(1);
}
if (strcmp(eventarray[0].value[0], "yourmoma")) {
printf("bad value value '%s' != yourmoma\n", eventarray[0].value[0]);
exit(1);
}
nevent = 0;
b.Feed("[MQ2] afhelp");
CheckOne(65);
nevent = 0;
b.Feed("[MQ2] ma 1");
CheckOne(46);
nevent = 0;
b.Feed("You can use the ability Fellstrike Discipline again in 20 minute(s) 19 seconds.");
if (nevent != 0) {
printf("bad event count %d != 0\n", nevent);
exit(1);
}
nevent = 0;
b.Feed("[MQ2] SetPCRadius");
CheckOne(76);
nevent = 0;
b.Feed("[MQ2] SetNPCRadius");
CheckOne(77);
nevent = 0;
b.Feed("[MQ2] itemset 3 2 1");
CheckOne(59);
if (eventarray[0].nvalues != 3) {
printf("bad value count %d != 3\n", eventarray[0].nvalues);
exit(1);
}
if (strcmp(eventarray[0].name[0], "1")) {
printf("bad value name0 '%s' != 1\n", eventarray[0].name[0]);
exit(1);
}
if (strcmp(eventarray[0].value[0], "3")) {
printf("bad value value '%s' != 3\n", eventarray[0].value[0]);
exit(1);
}
if (strcmp(eventarray[0].name[1], "2")) {
printf("bad value name1 '%s' != 2\n", eventarray[0].name[1]);
exit(1);
}
if (strcmp(eventarray[0].value[1], "2")) {
printf("bad value value '%s' != 2\n", eventarray[0].value[1]);
exit(1);
}
if (strcmp(eventarray[0].name[2], "3")) {
printf("bad value name2 '%s' != 3\n", eventarray[0].name[2]);
exit(1);
}
if (strcmp(eventarray[0].value[2], "1")) {
printf("bad value value '%s' != 1\n", eventarray[0].value[2]);
exit(1);
}
nevent = 0;
b.Feed("a mob with space in name begins to cast a spell.");
CheckOne(81);
if (eventarray[0].nvalues != 1) {
printf("bad value count %d != 1\n", eventarray[0].nvalues);
exit(1);
}
if (strcmp(eventarray[0].name[0], "1")) {
printf("bad value name '%s' != 1\n", eventarray[0].name[0]);
exit(1);
}
if (strcmp(eventarray[0].value[0], "a mob with space in name")) {
printf("bad value value '%s' != 'a mob with space in name'\n", eventarray[0].value[0]);
exit(1);
}
nevent = 0;
b.Feed("a mob hits you for lots of damage.");
if (nevent != 2) {
printf("bad event count %d != 2\n", nevent);
exit(1);
}
if (strcmp(eventarray[1].name[0], "1")) {
printf("bad value name0 '%s' != 1\n", eventarray[1].name[0]);
exit(1);
}
if (strcmp(eventarray[1].value[0], "a mob")) {
printf("bad value value '%s' != a mob\n", eventarray[1].value[0]);
exit(1);
}
if (strcmp(eventarray[1].name[1], "2")) {
printf("bad value name1 '%s' != 2\n", eventarray[1].name[1]);
exit(1);
}
if (strcmp(eventarray[1].value[1], "lots of")) {
printf("bad value value '%s' != lots of\n", eventarray[1].value[1]);
exit(1);
}
nevent = 0;
b.Feed("A bat hits you for 4 damage.");
if (nevent != 2) {
printf("bad event count %d != 2\n", nevent);
exit(1);
}
if (eventarray[1].nvalues != 2) {
printf("bad value count %d != 2\n", eventarray[1].nvalues);
exit(1);
}
if (strcmp(eventarray[1].name[0], "1")) {
printf("bad value name0 '%s' != 1\n", eventarray[1].name[0]);
exit(1);
}
if (strcmp(eventarray[1].value[0], "A bat")) {
printf("bad value value '%s' != A bat\n", eventarray[1].value[0]);
exit(1);
}
if (strcmp(eventarray[1].name[1], "2")) {
printf("bad value name1 '%s' != 2\n", eventarray[1].name[1]);
exit(1);
}
if (strcmp(eventarray[1].value[1], "4")) {
printf("bad value value '%s' != 4\n", eventarray[1].value[1]);
exit(1);
}
// watch j is not initialized here
for (; j < i; j++) {
if (eventid[j]) {
if (!b.RemoveEvent(eventid[j])) {
printf("removal failed %d\n", j);
exit(1);
}
} else {
printf("no event for %d\n", j);
}
}
}
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
}
| 38.140187 | 92 | 0.561545 | Natedog2012 |
6dd9babda4a11fbe0588758e8ccd994a30672af8 | 3,770 | cpp | C++ | src/appleseed/foundation/platform/defaulttimers.cpp | istemi-bahceci/appleseed | 2db1041acb04bad4742cf7826ce019f0e623fe35 | [
"MIT"
] | 1 | 2021-04-02T10:51:57.000Z | 2021-04-02T10:51:57.000Z | src/appleseed/foundation/platform/defaulttimers.cpp | istemi-bahceci/appleseed | 2db1041acb04bad4742cf7826ce019f0e623fe35 | [
"MIT"
] | null | null | null | src/appleseed/foundation/platform/defaulttimers.cpp | istemi-bahceci/appleseed | 2db1041acb04bad4742cf7826ce019f0e623fe35 | [
"MIT"
] | null | null | null |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "defaulttimers.h"
// appleseed.foundation headers.
#ifdef _WIN32
#include "foundation/platform/windows.h"
#endif
// Standard headers.
#include <ctime>
#if defined _WIN32
#include <sys/timeb.h>
#include <sys/types.h>
#elif defined __GNUC__
#include <sys/time.h>
#endif
using namespace std;
namespace foundation
{
//
// DefaultProcessorTimer class implementation.
//
DefaultProcessorTimer::DefaultProcessorTimer()
{
// Windows.
#if defined _WIN32
// Check whether QueryPerformanceCounter() is available.
LARGE_INTEGER frequency;
m_has_qpc = QueryPerformanceFrequency(&frequency) != 0;
#endif
}
uint64 DefaultProcessorTimer::frequency()
{
// Windows.
#if defined _WIN32
if (m_has_qpc)
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
return static_cast<uint64>(frequency.QuadPart);
}
else
{
return static_cast<uint64>(CLOCKS_PER_SEC);
}
// Other platforms.
#else
return static_cast<uint64>(CLOCKS_PER_SEC);
#endif
}
uint64 DefaultProcessorTimer::read()
{
// Windows.
#if defined _WIN32
if (m_has_qpc)
{
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
return static_cast<uint64>(count.QuadPart);
}
else
{
return static_cast<uint64>(clock());
}
// Other platforms.
#else
//
// On Linux, we might want to use clock_gettime(CLOCK_REALTIME).
//
// Andrei Alexandrescu, Writing Fast Code
// https://youtu.be/vrfYLlR8X8k?t=1973
//
return static_cast<uint64>(clock());
#endif
}
//
// DefaultWallclockTimer class implementation.
//
uint64 DefaultWallclockTimer::frequency()
{
// POSIX platforms.
#if defined __GNUC__
return 1000000;
// Windows.
#elif defined _WIN32
return 1000;
// Other platforms.
#else
return 1;
#endif
}
uint64 DefaultWallclockTimer::read()
{
// POSIX platforms.
#if defined __GNUC__
timeval tv;
gettimeofday(&tv, 0);
return static_cast<uint64>(tv.tv_sec) * 1000000 + static_cast<uint64>(tv.tv_usec);
// Windows.
#elif defined _WIN32
__timeb64 tb;
_ftime64(&tb);
return static_cast<uint64>(tb.time) * 1000 + static_cast<uint64>(tb.millitm);
// Other platforms.
#else
const time_t seconds = time(0);
return static_cast<uint64>(seconds);
#endif
}
} // namespace foundation
| 21.666667 | 86 | 0.711936 | istemi-bahceci |
6ddad5089bd8dc2a531736c0f047965a4d65b5ba | 4,080 | hpp | C++ | include/site.hpp | SavAct/SavWeb | 0c57ddb94df2a27d5a197cc23c481742cd85962b | [
"MIT"
] | null | null | null | include/site.hpp | SavAct/SavWeb | 0c57ddb94df2a27d5a197cc23c481742cd85962b | [
"MIT"
] | null | null | null | include/site.hpp | SavAct/SavWeb | 0c57ddb94df2a27d5a197cc23c481742cd85962b | [
"MIT"
] | null | null | null | #include "tables.hpp"
using namespace std;
using namespace eosio;
CONTRACT site : public contract {
public:
using contract::contract;
#define errorTableKey "There is no entry with this key."
#define errorOldNotMatch "Old reffered transaction doesn't match the last reffered transaction."
#define errorRefHigerOrEven "Reffered block has to be higher or even to old reffered block."
#define errorUserNotAuth "User is not authorized to perform this action."
#define errorFirstNotMatch "First reffered transaction doesn't match."
#define errorContractToManyRefs "Contract Error: There are more than two refrences."
#define errorMissingOldRef "Missing old reference."
/**
* First transaction to start the upload of a file. Additional parameters will be used to verify the files with the browser.
* @param scope Scope of the entry
* @param key Index key of the entry
* @param fname File name
* @param type Type of the file
* @param format Enryption format
* @param fsize Amount of bytes of the complete file
* @param attri Otional attributes of the file
* @param originators All originators with their share. (Prefixes define the type of a share and originator reference)
* @param resalefee This is the amount of fee which will granted to the originators by considering the share of each originator. Fee = (max value of uint16_t) / resalefee.
* @param hash The hash of the file as byte array
* @param code The first byte section of the file
*/
ACTION uploadbegin(name scope, uint64_t key, string& fname, string& type, string& format, uint32_t fsize, string& attri, string& originators, uint16_t resalefee, string& hash, string& code);
/**
* Upload the next file snipped
* @param scope Scope of the entry
* @param key Index key of the entry
* @param refs refs[0] is a reference to last transaction and refs[1] a reference to the old last transaction
* @param code The next byte section of the file
*/
ACTION uploadnext(name scope, uint64_t key, vector<Ref>& refs, string& code);
/**
* Update the references in the RAM to the very last transaction
* @param scope Scope of the entry
* @param key Index key of the entry
* @param refs refs[0] is a reference to last transaction and refs[1] a reference to the old last transaction
*/
ACTION updateref(name scope, uint64_t key, vector<Ref>& refs);
/**
* Delete an entry. This can be performed by the scope or owner of the contract
* @param scope The scope of the entry
* @param key The index key of the entry
*/
ACTION deleteentry(name scope, uint64_t key);
/**
* Delete a whole scope. This can be performed by the scope or owner of the contract
* @param scope The scope which will be deleted
*/
ACTION clearscope(name scope);
/**
* Change the index key of an entry
* @param scope The scope of the entry
* @param key The index key of the entry
* @param newkey The new index key
*/
ACTION changekey(name scope, uint64_t key, uint64_t newkey);
/**
* Functions without any checking or table entry. They are just to upload a file with a minimum need of CPU
*/
ACTION minbegin(name scope, uint64_t key, string& fname, string& type, string& format, uint32_t fsize, string& attri, string& originators, uint16_t resalefee, string& hash, string& code){}
ACTION minnext(name scope, uint64_t key, Ref& ref, string& code){}
ACTION minend(name scope, uint64_t key, Ref& ref, Ref& fref, string& code){}
/**
* Emplace the reference of an already uploaded file in a table
* @param scope Scope of the entry
* @param key Index key of the entry
* @param refs refs[0] is a reference to last transaction and refs[1] a reference to the first transaction if it differs from refs[0]
* @param attri Optional attributes of the file
*/
ACTION setref(name scope, uint64_t key, string& fname, vector<Ref> refs, string attri);
private:
};
| 44.835165 | 194 | 0.698775 | SavAct |
6ddc8b5b8ab78d0b2cf778fd67ad25399042660f | 1,716 | cpp | C++ | src/medCore/medJobManager.cpp | lcatanes/medInria-public | 5d79ce0085c11f2fb9277a06c8cf56b4258a9d9f | [
"BSD-4-Clause"
] | 1 | 2020-11-16T13:55:45.000Z | 2020-11-16T13:55:45.000Z | src/medCore/medJobManager.cpp | lcatanes/medInria-public | 5d79ce0085c11f2fb9277a06c8cf56b4258a9d9f | [
"BSD-4-Clause"
] | null | null | null | src/medCore/medJobManager.cpp | lcatanes/medInria-public | 5d79ce0085c11f2fb9277a06c8cf56b4258a9d9f | [
"BSD-4-Clause"
] | null | null | null | /*=========================================================================
medInria
Copyright (c) INRIA 2013 - 2014. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include <medJobManager.h>
#include <medJobItem.h>
medJobManager *medJobManager::s_instance = NULL;
class medJobManagerPrivate
{
public:
QList<medJobItem*> itemList;
bool m_IsActive;
};
medJobManager *medJobManager::instance(void)
{
if(!s_instance)
s_instance = new medJobManager;
return s_instance;
}
medJobManager::medJobManager( void ) : d(new medJobManagerPrivate)
{
d->m_IsActive = true;
}
medJobManager::~medJobManager( void )
{
delete d;
d = NULL;
}
bool medJobManager::registerJobItem( medJobItem* item, QString jobName)
{
if(d->m_IsActive)
{
d->itemList.append(item);
connect(this, SIGNAL(cancel(QObject*)), item, SLOT(onCancel(QObject*)) );
emit jobRegistered(item, jobName);
return true;
}
return false;
}
bool medJobManager::unRegisterJobItem( medJobItem* item )
{
int index = d->itemList.indexOf(item);
if (index != -1)
{
disconnect(this, SIGNAL(cancel(QObject*)), item, SLOT(onCancel(QObject*)) );
d->itemList.removeAt(index);
return true;
}
return false;
}
void medJobManager::dispatchGlobalCancelEvent(bool ignoreNewJobItems)
{
if (ignoreNewJobItems)
d->m_IsActive = false;
foreach( medJobItem* item, d->itemList )
emit cancel( item );
}
| 22.285714 | 84 | 0.617133 | lcatanes |
6ddd9bd83114b46592b1024577193156d431cea1 | 11,413 | cpp | C++ | Code/toolboxes/BSR/ucm/ucm_mean_pb.cpp | corganhejijun/crisp-boundaries-win32 | 8cfea4d1e337f4b30e1e1ad873683139ee7821fb | [
"BSD-3-Clause"
] | null | null | null | Code/toolboxes/BSR/ucm/ucm_mean_pb.cpp | corganhejijun/crisp-boundaries-win32 | 8cfea4d1e337f4b30e1e1ad873683139ee7821fb | [
"BSD-3-Clause"
] | null | null | null | Code/toolboxes/BSR/ucm/ucm_mean_pb.cpp | corganhejijun/crisp-boundaries-win32 | 8cfea4d1e337f4b30e1e1ad873683139ee7821fb | [
"BSD-3-Clause"
] | null | null | null | /*
Source code for computing ultrametric contour maps based on average boundary strength, as described in :
P. Arbelaez, M. Maire, C. Fowlkes, and J. Malik. From contours to regions: An empirical evaluation. In CVPR, 2009.
Pablo Arbelaez <arbelaez@eecs.berkeley.edu>
March 2009.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <iostream>
#include <deque>
#include <queue>
#include <vector>
#include <list>
#include <map>
using namespace std;
#include "mex.h"
/*************************************************************/
/******************************************************************************/
#ifndef Order_node_h
#define Order_node_h
class Order_node
{
public:
double energy;
int region1;
int region2;
Order_node(){ energy = 0.0; region1 = 0; region2 = 0; }
Order_node( const double& e, const int& rregion1, const int& rregion2 )
{
energy = e;
region1 = rregion1;
region2 = rregion2;
}
~Order_node(){}
// LEXICOGRAPHIC ORDER on priority queue: (energy,label)
bool operator < (const Order_node& x) const { return ( ( energy > x.energy ) ||(( energy == x.energy ) && (region1 > x.region1)) ||(( energy == x.energy ) && (region1 == x.region1)&& (region2 > x.region2))); }
};
#endif
/******************************************************************************/
#ifndef Neighbor_Region_h
#define Neighbor_Region_h
class Neighbor_Region
{
public:
double energy;
double total_pb;
double bdry_length;
Neighbor_Region()
{ energy = 0.0; total_pb = 0.0; bdry_length = 0.0; }
Neighbor_Region(const Neighbor_Region& v)
{ energy = v.energy; total_pb = v.total_pb; bdry_length = v.bdry_length; }
Neighbor_Region(const double& en, const double& tt, const double& bor )
{
energy = en;
total_pb = tt;
bdry_length = bor;
}
~Neighbor_Region(){}
};
#endif
/******************************************************************************/
#ifndef Bdry_element_h
#define Bdry_element_h
class Bdry_element
{
public:
int coord;
int cc_neigh;
Bdry_element(){}
Bdry_element(const int& c, const int& v) { coord = c; cc_neigh = v;}
Bdry_element(const Bdry_element& n) { coord = n.coord; cc_neigh = n.cc_neigh;}
~Bdry_element(){}
bool operator ==(const Bdry_element& n) const { return ( ( coord == n.coord) && ( cc_neigh == n.cc_neigh) ) ; }
// LEXICOGRAPHIC ORDER: (cc_neigh, coord)
bool operator < (const Bdry_element& n) const { return ( (cc_neigh < n.cc_neigh) || ((cc_neigh == n.cc_neigh) && ( coord < n.coord))); }
};
#endif
/******************************************************************************/
#ifndef Region_h
#define Region_h
class Region
{
public:
list<int> elements;
map<int, Neighbor_Region, less<int> > neighbors;
list<Bdry_element> boundary;
Region(){}
Region(const int& l) { elements.push_back(l); }
~Region(){}
void merge( Region& r, int* labels, const int& label, double* ucm, const double& saliency, const int& son, const int& tx );
};
void Region::merge( Region& r, int* labels, const int& label, double* ucm, const double& saliency, const int& son, const int& tx )
{
/* I. BOUNDARY */
// Ia. update father's boundary
list<Bdry_element>::iterator itrb, itrb2;
itrb = boundary.begin();
while ( itrb != boundary.end() )
{
if( labels[(*itrb).cc_neigh] == son )
{
itrb2 = itrb;
++itrb;
boundary.erase(itrb2);
}
else ++itrb;
}
int coord_contour;
// Ib. move son's boundary to father
for( itrb = r.boundary.begin(); itrb != r.boundary.end(); ++itrb )
{
if (ucm[(*itrb).coord] < saliency ) ucm[(*itrb).coord] = saliency;
if ( labels[(*itrb).cc_neigh] != label )
boundary.push_back( Bdry_element(*itrb) );
}
r.boundary.erase( r.boundary.begin(), r.boundary.end() );
/* II. ELEMENTS */
for( list<int>::iterator p = r.elements.begin(); p != r.elements.end(); ++p ) labels[*p] = label;
elements.insert( elements.begin(), r.elements.begin(), r.elements.end() );
r.elements.erase( r.elements.begin(), r.elements.end() );
/* III. NEIGHBORS */
map<int,Neighbor_Region, less<int> >::iterator itr, itr2;
// IIIa. remove inactive neighbors from father
itr = neighbors.begin();
while( itr != neighbors.end() )
{
if ( labels[(*itr).first] != (*itr).first )
{
itr2 = itr;
++itr;
neighbors.erase(itr2);
} else ++itr;
}
// IIIb. remove inactive neighbors from son y and neighbors belonging to father
itr = r.neighbors.begin();
while ( itr != r.neighbors.end() )
{
if ( ( labels[(*itr).first] != (*itr).first ) || ( labels[(*itr).first] == label ) )
{
itr2 = itr;
++itr;
r.neighbors.erase(itr2);
} else ++itr;
}
}
#endif
/*************************************************************/
void complete_contour_map(double* ucm, const int& txc, const int& tyc)
/* complete contour map by max strategy on Khalimsky space */
{
int vx[4] = { 1, 0, -1, 0 };
int vy[4] = { 0, 1, 0, -1 };
int nxp, nyp, cv;
double maximo;
for( int x = 0; x < txc; x = x + 2 ) for( int y = 0; y < tyc; y = y + 2 )
{
maximo = 0.0;
for( int v = 0; v < 4; v++ )
{
nxp = x + vx[v] ; nyp = y + vy[v]; cv = nxp + nyp * txc;
if ( (nyp >= 0) && (nyp < tyc) && (nxp < txc) && (nxp >= 0) && ( maximo < ucm[cv] ) )
maximo = ucm[cv];
}
ucm[x + y*txc] = maximo;
}
}
/***************************************************************************************************************************/
void compute_ucm
( double* local_boundaries, int* initial_partition, const int& totcc, double* ucm, const int& tx, const int& ty)
{
// I. INITIATE
int p,c;
int* labels = new int[totcc];
for(c = 0; c < totcc; c++ )
{
labels[c] = c;
}
// II. ULTRAMETRIC
Region* R = new Region[totcc];
priority_queue<Order_node, vector<Order_node>, less<Order_node> > merging_queue;
double totalPb, totalBdry, dissimilarity;
int v,px;
for( p = 0; p < (2*tx+1)*(2*ty+1); p++ ) ucm[p] = 0.0;
// INITIATE REGI0NS
for ( c = 0; c < totcc; c++ ) R[c] = Region(c);
// INITIATE UCM
int vx[4] = { 1, 0, -1, 0};
int vy[4] = { 0, 1, 0, -1};
int nxp, nyp, cnp, xp, yp, label;
for( p = 0; p < tx*ty; p++ )
{
xp = p%tx; yp = p/tx;
for( v = 0; v < 4; v++ )
{
nxp = xp + vx[v]; nyp = yp + vy[v]; cnp = nxp + nyp*tx;
if ( (nyp >= 0) && (nyp < ty) && (nxp < tx) && (nxp >= 0) && (initial_partition[cnp] != initial_partition[p]) )
R[initial_partition[p]].boundary.push_back(Bdry_element(( xp + nxp + 1 ) + ( yp + nyp + 1 )*(2*tx+1), initial_partition[cnp]));
}
}
// INITIATE merging_queue
list<Bdry_element>::iterator itrb;
for ( c = 0; c < totcc; c++ )
{
R[c].boundary.sort();
label = (*R[c].boundary.begin()).cc_neigh;
totalBdry = 0.0;
totalPb = 0.0;
for ( itrb = R[c].boundary.begin(); itrb != R[c].boundary.end(); ++itrb )
{
if ((*itrb).cc_neigh == label)
{
totalBdry++;
totalPb += local_boundaries[(*itrb).coord];
}
else
{
R[c].neighbors[label] = Neighbor_Region(totalPb/totalBdry, totalPb, totalBdry);
if( label > c ) merging_queue.push(Order_node(totalPb/totalBdry, c, label));
label = (*itrb).cc_neigh;
totalBdry = 1.0;
totalPb = local_boundaries[(*itrb).coord];
}
}
R[c].neighbors[label] = Neighbor_Region(totalPb/totalBdry, totalPb, totalBdry);
if( label > c ) merging_queue.push(Order_node(totalPb/totalBdry, c, label));
}
//MERGING
Order_node minor;
int father, son;
map<int,Neighbor_Region,less<int> >::iterator itr;
double current_energy = 0.0;
while ( !merging_queue.empty() )
{
minor = merging_queue.top(); merging_queue.pop();
if( (labels[minor.region1] == minor.region1) && (labels[minor.region2] == minor.region2) &&
(minor.energy == R[minor.region1].neighbors[minor.region2].energy) )
{
if (current_energy <= minor.energy) current_energy = minor.energy;
else
{
printf("\n ERROR : \n");
printf("\n current_energy = %f \n", current_energy);
printf("\n minor.energy = %f \n\n", minor.energy);
delete[] R; delete[] labels;
mexErrMsgTxt(" BUG: THIS IS NOT AN ULTRAMETRIC !!! ");
}
dissimilarity = R[minor.region1].neighbors[minor.region2].total_pb / R[minor.region1].neighbors[minor.region2].bdry_length ;
if (minor.region1 < minor.region2)
{ son = minor.region1; father = minor.region2; }
else
{ son = minor.region2; father = minor.region1; }
R[father].merge(R[son], labels, father, ucm, dissimilarity, son, tx);
// move and update neighbors
while ( R[son].neighbors.size() > 0 )
{
itr = R[son].neighbors.begin();
R[father].neighbors[(*itr).first].total_pb += (*itr).second.total_pb;
R[(*itr).first].neighbors[father].total_pb += (*itr).second.total_pb;
R[father].neighbors[(*itr).first].bdry_length += (*itr).second.bdry_length;
R[(*itr).first].neighbors[father].bdry_length += (*itr).second.bdry_length;
R[son].neighbors.erase(itr);
}
// update merging_queue
for (itr = R[father].neighbors.begin(); itr != R[father].neighbors.end(); ++itr )
{
dissimilarity = R[father].neighbors[(*itr).first].total_pb / R[father].neighbors[(*itr).first].bdry_length;
merging_queue.push(Order_node(dissimilarity, (*itr).first, father));
R[father].neighbors[(*itr).first].energy = dissimilarity;
R[(*itr).first].neighbors[father].energy = dissimilarity;
}
}
}
complete_contour_map(ucm, 2*tx+1, 2*ty+1 );
delete[] R; delete[] labels;
}
/*************************************************************************************************/
void mexFunction(int nlhs, mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
if (nrhs != 2) mexErrMsgTxt("INPUT: (local_boundaries, initial_partition) ");
if (nlhs != 1) mexErrMsgTxt("OUTPUT: [ucm] ");
double* local_boundaries = mxGetPr(prhs[0]);
double* pi = mxGetPr(prhs[1]);
// size of original image
int fil = mxGetM(prhs[1]);
int col = mxGetN(prhs[1]);
int totcc = -1;
int* initial_partition = new int[fil*col];
for( int px = 0; px < fil*col; px++ )
{
initial_partition[px] = (int) pi[px];
if (totcc < initial_partition[px]) totcc = initial_partition[px];
}
if (totcc < 0) mexErrMsgTxt("\n ERROR : number of connected components < 0 : \n");
totcc++;
plhs[0] = mxCreateDoubleMatrix(2*fil+1, 2*col+1, mxREAL);
double* ucm = mxGetPr(plhs[0]);
compute_ucm(local_boundaries, initial_partition, totcc, ucm, fil, col);
delete[] initial_partition;
}
| 28.748111 | 210 | 0.537194 | corganhejijun |
6ddf5189196626421b8e6d6b3cddaae2fd0c7626 | 3,822 | cpp | C++ | src/_OOP/Shader.cpp | haxpor/lgl | d87628f2a4653c0ebc80bca24bbd244993c63d77 | [
"MIT"
] | 3 | 2020-10-29T06:22:30.000Z | 2021-05-01T14:27:31.000Z | src/_OOP/Shader.cpp | haxpor/lgl | d87628f2a4653c0ebc80bca24bbd244993c63d77 | [
"MIT"
] | null | null | null | src/_OOP/Shader.cpp | haxpor/lgl | d87628f2a4653c0ebc80bca24bbd244993c63d77 | [
"MIT"
] | null | null | null | /*
====================
Uniforms
====================
*/
#include "lgl/Base.h"
#include <cmath>
float vertices[] = {
0.5f, 0.5f, 0.0f, // top right
0.5f, -0.5f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f // top left
};
unsigned int indices[] = {
0, 1, 2, // first triangle (right)
0, 2, 3 // second triangle (left)
};
class Demo : public lgl::App
{
public:
void UserSetup() override {
// compile vertex shader
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &VS_CODE, NULL);
glCompileShader(vertexShader);
lgl::error::PrintGLShaderErrorIfAny(vertexShader);
// compile fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &FS_CODE, NULL);
glCompileShader(fragmentShader);
lgl::error::PrintGLShaderErrorIfAny(fragmentShader);
// link all shaders together
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
lgl::util::PrintGLShaderProgramErrorIfAny(shaderProgram);
// delete un-needed shader objects
// note: in fact, it will mark them for deletion after our usage of shader program is done
// they will be deleted after that
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// wrap vertex attrib configurations via VAO
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// prepare vertex data
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); // or 3*sizeof(float) for its stride parameter
glEnableVertexAttribArray(0);
// prepare of EBO (Element Buffer Object) for indexed drawing
GLuint EBO;
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glBindVertexArray(0);
isFirstFrameWaitDone = false;
}
void UserUpdate(const double delta) override {
if (isFirstFrameWaitDone)
{
double currentTicks = glfwGetTime();
double greenValue = (std::sin(currentTicks) / 2.0f) + 0.5f;
// skip calling to glUseProgram(shaderProgram) as we wait for 1 frame
// shaderProgram by now is set to be active, so we save subsequent call from now on
glUniform4f(0, 0.0f, greenValue, 0.0f, 1.0f);
}
}
void UserRender() override {
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
if (!isFirstFrameWaitDone)
{
isFirstFrameWaitDone = true;
}
}
private:
const char* VS_CODE = R"(#version 330 core
layout (location = 0) in vec3 aPos;
void main()
{
gl_Position = vec4(aPos, 1.0);
})";
const char* FS_CODE = R"(#version 330 core
#extension GL_ARB_explicit_uniform_location : require
out vec4 FragColor;
layout (location = 0) uniform vec4 ourColor;
void main()
{
FragColor = ourColor;
}
)";
bool isFirstFrameWaitDone;
GLuint VAO;
GLuint shaderProgram;
};
int main()
{
Demo app;
app.Setup("Shader");
app.Start();
return 0;
}
| 29.175573 | 114 | 0.615646 | haxpor |
6de17176a7b9b2b179496ef2503903bc576cc5d9 | 1,214 | cpp | C++ | src/col.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | src/col.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | src/col.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | //
// Copyright (c) 2015, J2 Innovations
// Copyright (c) 2012 Brian Frank
// Licensed under the Academic Free License version 3.0
// History:
// 28 Aug 2014 Radu Racariu<radur@2inn.com> Ported to C++
// 06 Jun 2011 Brian Frank Creation
//
#include "col.hpp"
#include "str.hpp"
#include "dict.hpp"
////////////////////////////////////////////////
// Col
////////////////////////////////////////////////
using namespace haystack;
// public:
//////////////////////////////////////////////////////////////////////////
// Access
//////////////////////////////////////////////////////////////////////////
// Return programatic name of column
const std::string Col::name() const { return m_name; }
// Return display name of column which is meta.dis or name
const std::string Col::dis() const
{
const Val& dis = m_meta->get("dis");
if (dis.type() == Val::STR_TYPE)
return ((Str&)dis).value;
return m_name;
}
// Column meta-data tags
const Dict& Col::meta() const { return *m_meta; }
// Equality is name and meta
bool Col::operator== (const Col& that)
{
return m_name == that.m_name && *m_meta == *that.m_meta;
}
bool Col::operator!= (const Col& that)
{
return !(*this == that);
} | 25.829787 | 74 | 0.522241 | kushaldalsania |
6de17c3b0548814a4cfa34ad7a64798f4126af32 | 2,511 | hpp | C++ | src/tablestore/core/plainbuffer/consts.hpp | TimeExceed/aliyun-tablestore-cpp-sdk | f8d2fdf500badf70073dff4e21a5d2d7aa7d3853 | [
"BSD-3-Clause"
] | 2 | 2020-02-24T06:51:55.000Z | 2020-04-24T14:40:10.000Z | src/tablestore/core/plainbuffer/consts.hpp | TimeExceed/aliyun-tablestore-cpp-sdk | f8d2fdf500badf70073dff4e21a5d2d7aa7d3853 | [
"BSD-3-Clause"
] | null | null | null | src/tablestore/core/plainbuffer/consts.hpp | TimeExceed/aliyun-tablestore-cpp-sdk | f8d2fdf500badf70073dff4e21a5d2d7aa7d3853 | [
"BSD-3-Clause"
] | 1 | 2020-02-24T06:51:57.000Z | 2020-02-24T06:51:57.000Z | #pragma once
/*
BSD 3-Clause License
Copyright (c) 2017, Alibaba Cloud
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder 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.
*/
#ifndef TABLESTORE_CORE_PLAINBUFFER_PLAIN_BUFFER_CONSTS_HPP
#define TABLESTORE_CORE_PLAINBUFFER_PLAIN_BUFFER_CONSTS_HPP
#include <stdint.h>
namespace aliyun {
namespace tablestore {
namespace core {
namespace plainbuffer {
const uint32_t kHeader = 0x75;
enum Tag {
kTag_None = 0,
kTag_RowKey = 0x1,
kTag_RowData = 0x2,
kTag_Cell = 0x3,
kTag_CellName = 0x4,
kTag_CellValue = 0x5,
kTag_CellType = 0x6,
kTag_CellTimestamp = 0x7,
kTag_RowDeleteMarker = 0x8,
kTag_RowChecksum = 0x9,
kTag_CellChecksum = 0x0A,
};
enum CellDeleteMarker {
kCDM_DeleteAllVersions = 0x1,
kCDM_DeleteOneVersion = 0x3,
};
enum VariantType {
kVT_Integer = 0x0,
kVT_Double = 0x1,
kVT_Boolean = 0x2,
kVT_String = 0x3,
kVT_Null = 0x6,
kVT_Blob = 0x7,
kVT_InfMin = 0x9,
kVT_InfMax = 0xa,
kVT_AutoIncrement = 0xb,
};
} // namespace plainbuffer
} // namespace core
} // namespace tablestore
} // namespace aliyun
#endif
| 31 | 78 | 0.766627 | TimeExceed |
6de21abe33dd6600cebe17f5747a1ceb68bd0e4b | 9,581 | cpp | C++ | src/main.cpp | cultur98/ESP32_Vorrat | 0dba638677c32ccb46069403a71cefa2460974ad | [
"MIT"
] | null | null | null | src/main.cpp | cultur98/ESP32_Vorrat | 0dba638677c32ccb46069403a71cefa2460974ad | [
"MIT"
] | null | null | null | src/main.cpp | cultur98/ESP32_Vorrat | 0dba638677c32ccb46069403a71cefa2460974ad | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <Ticker.h>
#include <Button2.h>
#include "Config.h"
#include "vorratConfig.h"
#include "myTimer.h"
#include "wifiman.h"
#include "Logger.h"
#include "hch_stuff.h"
#include "ePaperBWR.h"
#include "lilygo.h"
#include "ota.h"
#include "deep_sleep_helper.h"
#include "batty.h"
// enable debug messages on the console
#define ARDUINOTRACE_ENABLE 1
#include "ArduinoTrace.h"
Logger myLogger;
ePaperBWR myEpaper;
Ticker watch_tick;
MyTimer myTimer;
TaskHandle_t TickTask;
int language = _GER_;
Button2 button1 = Button2(BUTTON_LAST);
Button2 button2 = Button2(BUTTON_NEXT);
Batty myBatt;
int the_page = 0;
uint32_t timer_ctr = 0;
uint32_t main_loop_ctr = 0;
int today = 0;
char time_string[MIN_STRING_LEN];
bool has_valid_config = false;
bool new_firmware = false;
bool timer_wakeup = false;
bool wasConnected = true;
bool isConnected = false;
RTC_DATA_ATTR int bootCount = 0;
touch_pad_t touchPin;
#define UP_TIMEOUT_SEC 30
#define TROUBLE_TIMEOUT_MIN 20
void watch_task() {
TRACE1();
timer_ctr++;
char uptime[80];
int up_seconds = (TICK_TASK_DELAY/1000)* timer_ctr;
hch_uptime(up_seconds, uptime);
isConnected = WiFi.isConnected();
Serial.printf("\nisConn %d | wasConn %d | valid_conf %d | timer_wake %d\n",
isConnected, wasConnected, has_valid_config, timer_wakeup);
if(up_seconds > UP_TIMEOUT_SEC)
{
if(wasConnected == true && isConnected == false && has_valid_config == true && timer_wakeup == true)
{
Serial.printf("TROUBLE detected - trying again in %d minutes\n", TROUBLE_TIMEOUT_MIN);
uint64_t wakeup_us = TROUBLE_TIMEOUT_MIN * (60 * 1000000);
esp_sleep_enable_timer_wakeup(wakeup_us);
set_deep_sleep();
}
if(wasConnected == true && isConnected == false)
{
Serial.println(F("watch_task() print AP mode"));
myEpaper.ap_mode("No access to WLAN");
set_timeout(LONG_TIMEOUT);
}
Serial.printf("WIFI was %d | is %d\n", wasConnected, isConnected);
wasConnected = isConnected;
}
uint32_t heap = esp_32_get_free_heap();
uint32_t psram = ESP.getPsramSize();
Serial.printf("NTP date %s\n", time_string);
Serial.printf("nuptime %s | min_uptime %d | %u boots\n", uptime, UP_TIMEOUT_SEC, hch_get_boot_ctr());
Serial.printf("main_loop: %u | timer %u | heap %u | psram %u\n", main_loop_ctr, timer_ctr, heap, psram);
Serial.printf("sleep in %ds\n", get_timeout_delta());
check_sleep();
}
void show_prev_screen()
{
set_timeout(MEDIUM_TIMEOUT);
Serial.println(F("UP clicked"));
if(the_page > 0)
the_page = the_page - 1;
myEpaper.print_lager_list(time_string, today, the_page, false);
set_timeout(MEDIUM_TIMEOUT);
}
void show_next_screen()
{
set_timeout(MEDIUM_TIMEOUT);
Serial.println(F("DOWN clicked"));
the_page = the_page + 1;
myEpaper.print_lager_list(time_string, today, the_page, false);
set_timeout(MEDIUM_TIMEOUT);
}
void click(Button2& btn) {
TRACE1();
if (btn == button1) {
show_prev_screen();
}
if ((btn == button2) || (btn == button2) ){
show_next_screen();
}
}
#define WAKE_UP_MINS_DELTA_MIN 30
void processWakeup()
{
int hours, mins;
char time_string[MIN_STRING_LEN];
int min_wakeup_mins = -1;
if(today <= 0)
{
Serial.printf("Time ist not defined. Cannot set wakeup!\n");
return;
}
for(int i = 0; i < WAKE_UP_TIMES; i++)
{
strcpy(time_string, vorrat_config.wakeup_time[i].c_str());
DUMP1(time_string);
int ret = sscanf(time_string, "%d:%d", &hours, &mins);
DUMP1(ret);
if(ret == 2)
{
DUMP2(hours);
DUMP2(mins);
if((hours >= 0) && (hours <= 23) && (mins >= 0) && (mins <= 59))
{
int wakeup_mins = mins + hours * 60;
DUMP2(wakeup_mins);
if (myTimer.getTimeStringShort(time_string, MIN_STRING_LEN) == true)
{
sscanf(time_string, "%d:%d", &hours, &mins);
DUMP2(hours);
DUMP2(mins);
if((hours >= 0) && (hours <= 23) && (mins >= 0) && (mins <= 59))
{
int the_mins = mins + hours * 60;
DUMP2(the_mins);
int wakeup_mins_delta = wakeup_mins - the_mins;
if(wakeup_mins_delta < 0)
{
wakeup_mins_delta = wakeup_mins_delta + 1440;
}
if(wakeup_mins_delta < WAKE_UP_MINS_DELTA_MIN)
{
wakeup_mins_delta = wakeup_mins_delta + 1440;
}
if((wakeup_mins_delta < min_wakeup_mins) || (min_wakeup_mins == -1))
{
min_wakeup_mins = wakeup_mins_delta;
DUMP1(min_wakeup_mins);
}
DUMP2(wakeup_mins_delta);
}
}
}
}
}
if(min_wakeup_mins > 0)
{
uint64_t wakeup_us = min_wakeup_mins;
wakeup_us = wakeup_us * 60 * 1000000;
esp_sleep_enable_timer_wakeup(wakeup_us);
Serial.printf("ESP will wake up in [%02d:%02d]\n", min_wakeup_mins / 60, min_wakeup_mins % 60);
}
}
bool setup_timer()
{
TRACE1();
int update_ctr = 0;
myTimer.init(vorrat_config.time_zone_offset);
while((myTimer.update() == false) && (update_ctr++ < 5))
{
Serial.print(F("Failed to get time via NTP.\n"));
Serial.printf("Trying again in %dms.\n", NTP_UPDATE_TIME);
delay(NTP_UPDATE_TIME);
}
myTimer.getTimeString(time_string, MIN_STRING_LEN);
today = myTimer.tick() / (60*60*24);
return(true);
}
bool process_list(bool new_fw)
{
TRACE1();
setup_timer();
myLogger.init();
if(vorrat_config.key.length() > 0)
{
if(myLogger.get_lager_list_server(vorrat_config.key.c_str(), vorrat_config.loc.c_str()) == true)
{
myEpaper.print_lager_list(time_string, today, the_page, new_fw);
set_timeout(SHORT_TIMEOUT);
processWakeup();
return(true);
}
}
else if((vorrat_config.googleID.length() > 0) && (vorrat_config.googleAPIkey.length() > 0))
{
if(myLogger.get_google_list(vorrat_config.googleID.c_str(), vorrat_config.googleAPIkey.c_str()) == true)
{
myEpaper.print_lager_list(time_string, today, the_page, new_fw);
set_timeout(SHORT_TIMEOUT);
processWakeup();
return(true);
}
}
processWakeup();
return(false);
}
bool setup_button_click()
{
TRACE1();
button1.setClickHandler(click);
button2.setClickHandler(click);
button1.setLongClickHandler(click);
button2.setLongClickHandler(click);
return(true);
}
void setup() {
TRACE1();
bool show_config = false;
bool ota_update = false;
bool force_ap_mode = false;
pinMode(BUTTON_WAKE, INPUT_PULLUP);
pinMode(BUTTON_LAST, INPUT_PULLUP);
pinMode(BUTTON_NEXT, INPUT_PULLUP);
ota_update = hch_init((char*)CLIENT_ID, 115200);
delay(100);
language = hch_get_lang();
bootCount++;
Serial.println("Boot number: " + String(bootCount));
// init wakeup and deep sleep behavior
timer_wakeup = init_wakeup();
set_timeout(LONG_TIMEOUT);
Serial.printf("CLIENT_ID %s\n", CLIENT_ID);
watch_tick.attach((float)(TICK_TASK_DELAY / 1000), watch_task);
Serial.printf("Button state [%d|%d|%d]\n",
digitalRead(BUTTON_WAKE), digitalRead(BUTTON_LAST),
digitalRead(BUTTON_NEXT));
if(digitalRead(BUTTON_NEXT) == LOW)
{
ota_update = true;
Serial.println(F("FIRMWARE UPDATE requested!"));
}
if( digitalRead(BUTTON_LAST) == LOW )
{
Serial.println(F("SHOW CONFIG requested!"));
show_config = true;
}
if( (digitalRead(BUTTON_LAST) == LOW) && (digitalRead(BUTTON_NEXT) == LOW) )
{
Serial.println(F("AP MODE requested!"));
force_ap_mode = true;
show_config = false;
ota_update = false;
}
has_valid_config = WiFiManager_loadConfigData();
myEpaper.init();
myBatt.init();
myBatt.test();
myBatt.read();
if(has_valid_config == false)
{
Serial.printf("Config status [%d]\n", has_valid_config);
}
new_firmware = hch_check_for_new_fw(FW_VERSION_MAJ, FW_VERSION_MIN);
DUMP1(new_firmware);
DUMP1(FW_VERSION_MAJ);
DUMP1(FW_VERSION_MIN);
if(new_firmware == true)
{
myEpaper.firmware_change(FW_VERSION_MAJ, FW_VERSION_MIN);
}
/*
if(force_ap_mode == true)
{
myEpaper.ap_mode("Button Pressed");
}
*/
wasConnected = true;
WiFiManager_init(CLIENT_ID, force_ap_mode);
bool new_online_fw = checkVersion();
if(ota_update == true)
{
hch_clear_ota_request();
if(new_online_fw == true)
{
myEpaper.show_ota_update(theVersion.new_major, theVersion.new_minor);
checkForUpdates();
Serial.println(F("New Update available\n"));
return;
}
else
{
myEpaper.show_firmware();
Serial.println(F("Firmware up to date .... continue!\n"));
}
}
setup_button_click();
TRACE1();
if(show_config == true)
{
myEpaper.show_config();
Serial.println(F("setup() long timeout"));
}
else
{
if(has_valid_config == true)
{
bool process_status = process_list(new_online_fw);
if(process_status == false)
{
char mess[MIN_STRING_LEN];
Serial.println(F("NO TABLE FOUND!"));
sprintf(mess, "[%d|%d|%d][%d|%d|%d][%d|%d|%d][%d]",
has_valid_config, new_firmware, timer_wakeup,
wasConnected, isConnected, show_config,
ota_update, force_ap_mode, new_online_fw,
process_status);
myEpaper.no_conn(mess);
}
}
else
{
Serial.println(F("NO CONFIGURATION FOUND!"));
myEpaper.config_mode();
}
}
}
void loop() {
TRACE2();
main_loop_ctr++;
WiFiManager_loop();
button1.loop();
button2.loop();
check_sleep();
}
| 26.249315 | 108 | 0.650663 | cultur98 |
6df1223aac31e1ad651fd2ceea8ed9c7c6707acd | 7,058 | cpp | C++ | test/src/distance_test.cpp | ericwa/vecmath | b1db3cedac39d380b4d65efc894c933c9f413030 | [
"MIT"
] | 1 | 2021-07-13T02:56:28.000Z | 2021-07-13T02:56:28.000Z | test/src/distance_test.cpp | ericwa/vecmath | b1db3cedac39d380b4d65efc894c933c9f413030 | [
"MIT"
] | null | null | null | test/src/distance_test.cpp | ericwa/vecmath | b1db3cedac39d380b4d65efc894c933c9f413030 | [
"MIT"
] | null | null | null | /*
Copyright 2010-2019 Kristian Duske
Copyright 2015-2019 Eric Wasylishen
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 <gtest/gtest.h>
#include "test_utils.h"
#include <vecmath/forward.h>
#include <vecmath/vec.h>
#include <vecmath/distance.h>
namespace vm {
TEST(distance_test, distance_ray_point) {
constexpr auto ray = ray3f(vec3f::zero(), vec3f::pos_z());
// point is behind ray
CER_ASSERT_FLOAT_EQ(0.0f, squared_distance(ray, vec3f(-1.0f, -1.0f, -1.0f)).position)
CER_ASSERT_FLOAT_EQ(3.0f, squared_distance(ray, vec3f(-1.0f, -1.0f, -1.0f)).distance)
// point is in front of ray
CER_ASSERT_FLOAT_EQ(1.0f, squared_distance(ray, vec3f(1.0f, 1.0f, 1.0f)).position)
CER_ASSERT_FLOAT_EQ(2.0f, squared_distance(ray, vec3f(1.0f, 1.0f, 1.0f)).distance)
// point is on ray
CER_ASSERT_FLOAT_EQ(1.0f, squared_distance(ray, vec3f(0.0f, 0.0f, 1.0f)).position)
CER_ASSERT_FLOAT_EQ(0.0f, squared_distance(ray, vec3f(0.0f, 0.0f, 1.0f)).distance)
}
TEST(distance_test, distance_segment_point) {
constexpr auto segment = segment3f(vec3f::zero(), vec3f::pos_z());
// point is below start
ASSERT_FLOAT_EQ(0.0f, squared_distance(segment, vec3f(-1.0f, -1.0f, -1.0f)).position);
ASSERT_FLOAT_EQ(3.0f, squared_distance(segment, vec3f(-1.0f, -1.0f, -1.0f)).distance);
// point is within segment
ASSERT_FLOAT_EQ(1.0f, squared_distance(segment, vec3f(1.0f, 1.0f, 1.0f)).position);
ASSERT_FLOAT_EQ(2.0f, squared_distance(segment, vec3f(1.0f, 1.0f, 1.0f)).distance);
// point is above end
ASSERT_FLOAT_EQ(1.0f, squared_distance(segment, vec3f(0.0f, 0.0f, 2.0f)).position);
ASSERT_FLOAT_EQ(1.0f, squared_distance(segment, vec3f(0.0f, 0.0f, 2.0f)).distance);
}
TEST(distance_test, distance_ray_segment) {
constexpr auto ray = ray3f(vec3f::zero(), vec3f::pos_z());
line_distance<float> segDist;
segDist = squared_distance(ray, segment3f(vec3f(0.0f, 0.0f, 0.0f), vec3f(0.0f, 0.0f, 1.0f)));
ASSERT_TRUE(segDist.parallel);
ASSERT_FLOAT_EQ(0.0f, segDist.distance);
segDist = squared_distance(ray, segment3f(vec3f(1.0f, 1.0f, 0.0f), vec3f(1.0f, 1.0f, 1.0f)));
ASSERT_TRUE(segDist.parallel);
ASSERT_FLOAT_EQ(2.0f, segDist.distance);
segDist = squared_distance(ray, segment3f(vec3f(1.0f, 0.0f, 0.0f), vec3f(0.0f, 1.0f, 0.0f)));
ASSERT_FALSE(segDist.parallel);
ASSERT_FLOAT_EQ(0.0f, segDist.position1);
ASSERT_FLOAT_EQ(0.5f, segDist.distance);
ASSERT_FLOAT_EQ(0.70710677f, segDist.position2);
segDist = squared_distance(ray, segment3f(vec3f(1.0f, 0.0f, 0.0f), vec3f(2.0f, -1.0f, 0.0f)));
ASSERT_FALSE(segDist.parallel);
ASSERT_FLOAT_EQ(0.0f, segDist.position1);
ASSERT_FLOAT_EQ(1.0f, segDist.distance);
ASSERT_FLOAT_EQ(0.0f, segDist.position2);
segDist = distance(ray, segment3f(vec3f(-1.0f, 1.5f, 2.0f), vec3f(+1.0f, 1.5f, 2.0f)));
ASSERT_FALSE(segDist.parallel);
ASSERT_FLOAT_EQ(2.0f, segDist.position1);
ASSERT_FLOAT_EQ(1.5f, segDist.distance);
ASSERT_FLOAT_EQ(1.0f, segDist.position2);
}
TEST(distance_test, distance_ray_ray) {
constexpr auto ray1 = ray3f(vec3f::zero(), vec3f::pos_z());
constexpr auto segDist1 = squared_distance(ray1, ray1);
CER_ASSERT_TRUE(segDist1.parallel)
CER_ASSERT_NEAR(0.0f, segDist1.distance, 0.001f)
constexpr auto segDist2 = squared_distance(ray1, ray3f(vec3f(1.0f, 1.0, 0.0f), vec3f::pos_z()));
CER_ASSERT_TRUE(segDist2.parallel)
CER_ASSERT_NEAR(2.0f, segDist2.distance, 0.001f)
constexpr auto segDist3 = squared_distance(ray1, ray3f(vec3f(1.0f, 1.0f, 0.0f), normalize_c(vec3f(1.0f, 1.0f, 1.0f))));
CER_ASSERT_FALSE(segDist3.parallel)
CER_ASSERT_NEAR(0.0f, segDist3.position1, 0.001f)
CER_ASSERT_NEAR(2.0f, segDist3.distance, 0.001f)
CER_ASSERT_NEAR(0.0f, segDist3.position2, 0.001f)
constexpr auto segDist4 = squared_distance(ray1, ray3f(vec3f(1.0f, 1.0f, 0.0f), normalize_c(vec3f(-1.0f, -1.0f, +1.0f))));
CER_ASSERT_FALSE(segDist4.parallel)
CER_ASSERT_NEAR(1.0f, segDist4.position1, 0.001f)
CER_ASSERT_NEAR(0.0f, segDist4.distance, 0.001f)
CER_ASSERT_NEAR(length(vec3f(1.0f, 1.0f, 1.0f)), segDist4.position2, 0.001f)
constexpr auto segDist5 = squared_distance(ray1, ray3f(vec3f(1.0f, 1.0f, 0.0f), normalize_c(vec3f(-1.0f, 0.0f, +1.0f))));
CER_ASSERT_FALSE(segDist5.parallel)
CER_ASSERT_NEAR(1.0f, segDist5.position1, 0.001f)
CER_ASSERT_NEAR(1.0f, segDist5.distance, 0.001f)
CER_ASSERT_NEAR(length(vec3f(1.0f, 0.0f, 1.0f)), segDist5.position2, 0.001f)
}
TEST(distance_test, distance_ray_line) {
constexpr auto ray = ray3f(vec3f::zero(), vec3f::pos_z());
constexpr auto segDist1 = squared_distance(ray, line3f(vec3f(0.0f, 0.0f, 0.0f), vec3f::pos_z()));
CER_ASSERT_TRUE(segDist1.parallel)
CER_ASSERT_FLOAT_EQ(0.0f, segDist1.distance)
constexpr auto segDist2 = squared_distance(ray, line3f(vec3f(1.0f, 1.0f, 0.0f), vec3f::pos_z()));
CER_ASSERT_TRUE(segDist2.parallel)
CER_ASSERT_FLOAT_EQ(2.0f, segDist2.distance)
constexpr auto segDist3 = squared_distance(ray, line3f(vec3f(1.0f, 0.0f, 0.0f), normalize_c(vec3f(-1.0f, 1.0f, 0.0f))));
CER_ASSERT_FALSE(segDist3.parallel)
CER_ASSERT_FLOAT_EQ(0.0f, segDist3.position1)
CER_ASSERT_FLOAT_EQ(0.5f, segDist3.distance)
CER_ASSERT_FLOAT_EQ(sqrt_c(2.0f) / 2.0f, segDist3.position2)
constexpr auto segDist4 = squared_distance(ray, line3f(vec3f(1.0f, 0.0f, 0.0f), normalize_c(vec3f(1.0f, -1.0f, 0.0f))));
CER_ASSERT_FALSE(segDist4.parallel)
CER_ASSERT_FLOAT_EQ(0.0f, segDist4.position1)
CER_ASSERT_FLOAT_EQ(0.5f, segDist4.distance)
CER_ASSERT_FLOAT_EQ(-sqrt_c(2.0f) / 2.0f, segDist4.position2)
}
}
| 48.675862 | 130 | 0.685463 | ericwa |
6df41b02c4b178a772645eac31c372d79c57d7a1 | 1,421 | cpp | C++ | Google Code Jam/2018/Round 1C/A Whole New Word.cpp | pratyaydeep/Competitive-Programming | c6ee9a492915e39b7b4c54d167a3c027a64b48b1 | [
"MIT"
] | null | null | null | Google Code Jam/2018/Round 1C/A Whole New Word.cpp | pratyaydeep/Competitive-Programming | c6ee9a492915e39b7b4c54d167a3c027a64b48b1 | [
"MIT"
] | null | null | null | Google Code Jam/2018/Round 1C/A Whole New Word.cpp | pratyaydeep/Competitive-Programming | c6ee9a492915e39b7b4c54d167a3c027a64b48b1 | [
"MIT"
] | 1 | 2021-07-19T08:39:38.000Z | 2021-07-19T08:39:38.000Z | // Problem 1: A Whole New Word
// Idea: Brute Force (just generating all strings of given characters, return the first generated string that is not found in the dictionary)
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e5 + 5;
const int MAX_L = 20; // ~ Log N
const long long MOD = 1e9 + 7;
const long long INF = 1e18;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ii> vii;
typedef vector<vi> vvi;
#define LSOne(S) (S & (-S))
#define isBitSet(S, i) ((S >> i) & 1)
int N, L;
set<string> dict;
vector<set<char>> arr;
string build(string cur, int pos) {
if (pos == L) {
return (dict.find(cur) == dict.end()) ? cur : "-";
}
for (char c : arr[pos]) {
string res = build(cur + c, pos + 1);
if (res != "-") return res;
}
return "-";
}
void solve() {
cin >> N >> L;
dict.clear();
arr.clear(); arr.resize(L);
for (int i = 0; i < N; i++) {
string str; cin >> str;
dict.insert(str);
for (int j = 0; j < L; j++) {
arr[j].insert(str[j]);
}
}
cout << build("", 0) << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int tc; cin >> tc;
for (int t = 1; t <= tc; t++) {
cout << "Case #" << t << ": ";
solve();
}
}
| 22.555556 | 141 | 0.532723 | pratyaydeep |
6df8b3d9ad306a18bc5943553fe6eed3a1c29df2 | 5,021 | cpp | C++ | test/parse_tree.cpp | cmargiotta/ratl | 84d76f23bbc52d3e581cfbb5e5a3dd04993e74c2 | [
"MIT"
] | null | null | null | test/parse_tree.cpp | cmargiotta/ratl | 84d76f23bbc52d3e581cfbb5e5a3dd04993e74c2 | [
"MIT"
] | null | null | null | test/parse_tree.cpp | cmargiotta/ratl | 84d76f23bbc52d3e581cfbb5e5a3dd04993e74c2 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_ENABLE_BENCHMARKING
#include <catch2/catch.hpp>
#include <fstream>
#include <iostream>
#include <math/fraction.hpp>
#include <parser/dice.hpp>
#include <parser/math.hpp>
#include <parser/math_function.hpp>
#include <parser/regex.hpp>
SCENARIO("Regex parse tree")
{
GIVEN("A regex parser and an expression tree")
{
ratl::regex_parser parser_;
std::string parse_expr("1*2+a?[\\dA]*");
auto tree = parser_(parse_expr);
std::string parse_expr1("[1-2]+");
auto tree1 = parser_(parse_expr1);
REQUIRE(tree->to_string() == parse_expr);
REQUIRE(tree1->to_string() == parse_expr1);
WHEN("It is asked to compute")
{
THEN("It correctly interprets its language")
{
std::string expression("1222");
REQUIRE(tree->compute(expression));
expression = "22222";
REQUIRE(tree->compute(expression));
expression = "1111122222";
REQUIRE(tree->compute(expression));
expression = "122222a";
REQUIRE(tree->compute(expression));
expression = "122222a9999";
REQUIRE(tree->compute(expression));
expression = "122222aAAAA";
REQUIRE(tree->compute(expression));
expression = "122222a9AA999";
REQUIRE(tree->compute(expression));
expression = "22222aa";
REQUIRE(tree->compute(expression));
expression = "111aa";
REQUIRE(!tree->compute(expression));
expression = "111";
REQUIRE(!tree->compute(expression));
expression = "";
REQUIRE(!tree->compute(expression));
expression = "12344";
REQUIRE(tree1->compute(expression));
}
}
AND_WHEN("Two trees are merged")
{
ratl::regex_parser parser_;
std::string parse_expr("1*2+a?[\\dA]*");
auto tree = parser_(parse_expr);
std::string parse_expr1 = "[1-2]+";
auto tree1 = parser_(parse_expr1);
tree->merge(std::move(tree1));
THEN("They are correctly merged")
{
REQUIRE(tree->to_string() == ("(" + parse_expr + ")|(" + parse_expr1 + ")"));
std::string expression = "12344";
REQUIRE(tree->compute(expression));
expression = "22222aa";
REQUIRE(tree->compute(expression));
}
}
}
}
SCENARIO("Math parse tree")
{
GIVEN("A regex parser and an expression tree")
{
ratl::math_parser parser_;
WHEN("It is asked to compute")
{
THEN("It correctly interprets its expression")
{
std::string parse_expr("12+5*2");
auto tree = parser_(parse_expr);
REQUIRE(tree->to_string() == parse_expr);
REQUIRE(tree->compute() == 34);
parse_expr = "(12+5)*2";
tree = parser_(parse_expr);
REQUIRE(tree->to_string() == parse_expr);
REQUIRE(tree->compute() == 34);
parse_expr = "12+5^2";
tree = parser_(parse_expr);
REQUIRE(tree->to_string() == parse_expr);
REQUIRE(tree->compute() == 289);
}
}
}
}
SCENARIO("Math function parse tree")
{
GIVEN("A regex parser and an expression tree")
{
ratl::math_function_parser parser_;
WHEN("It is asked to compute")
{
THEN("It correctly interprets it")
{
std::string parse_expr("12/2+2+5xy");
auto tree = parser_(parse_expr);
std::unordered_map<std::string, ratl::math::fraction<int>> unknowns;
unknowns["x"] = ratl::math::fraction<int>(1, 2);
unknowns["y"] = ratl::math::fraction<int>(2, 1);
REQUIRE(tree->to_string() == "13xy");
auto result = tree->compute(unknowns);
REQUIRE(result.numerator == 13);
REQUIRE(result.denominator == 1);
}
}
}
}
SCENARIO("Dice parse tree")
{
GIVEN("A regex parser and an expression tree")
{
ratl::dice_parser parser_;
std::string parse_expr("10d6");
auto tree = parser_(parse_expr);
REQUIRE(tree->to_string() == parse_expr);
WHEN("It is asked to compute")
{
THEN("It correctly interprets its expression")
{
for (int i = 0; i < 100; ++i)
{
auto result = tree->compute();
REQUIRE(result <= 60);
REQUIRE(result >= 1);
}
}
}
}
} | 28.856322 | 93 | 0.49293 | cmargiotta |
6df8e55ef6356d1bd6e87c4f7b67cd5cec20118e | 1,788 | cpp | C++ | test/snippet/alignment/matrix/debug_matrix_trace.cpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | test/snippet/alignment/matrix/debug_matrix_trace.cpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | test/snippet/alignment/matrix/debug_matrix_trace.cpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <seqan3/alphabet/nucleotide/dna4.hpp>
#include <seqan3/alignment/matrix/debug_matrix.hpp>
#include <seqan3/core/debug_stream.hpp>
#include <seqan3/range/views/to_char.hpp>
int main()
{
// using namespace seqan3;
using seqan3::detail::debug_matrix;
using seqan3::operator""_dna4;
using seqan3::operator|;
std::vector<seqan3::dna4> database = "AACCGGTT"_dna4;
std::vector<seqan3::dna4> query = "ACGT"_dna4;
auto N = seqan3::detail::trace_directions::none;
auto D = seqan3::detail::trace_directions::diagonal;
auto U = seqan3::detail::trace_directions::up;
auto L = seqan3::detail::trace_directions::left;
seqan3::detail::row_wise_matrix<seqan3::detail::trace_directions> trace_matrix
{
seqan3::detail::number_rows{5u},
seqan3::detail::number_cols{9u},
std::vector
{
N,L,L ,L ,L ,L ,L ,L,L ,
U,D,D|L,L ,L ,L ,L ,L,L ,
U,U,D ,D ,D|L,L ,L ,L,L ,
U,U,D|U,D|U,D ,D ,D|L,L,L ,
U,U,D|U,D|U,D|U,D|U,D ,D,D|L
}
};
seqan3::debug_stream << "database:\t" << database << std::endl;
seqan3::debug_stream << "query:\t\t" << query << std::endl;
seqan3::debug_stream << std::endl;
seqan3::debug_stream << "trace_matrix: " << trace_matrix.cols() << " columns and "
<< trace_matrix.rows() << " rows" << std::endl;
// Prints out the matrix in a convenient way
seqan3::debug_stream << trace_matrix << std::endl; // without sequences
seqan3::debug_stream << debug_matrix{trace_matrix, database, query} << std::endl; // with sequences
seqan3::debug_stream << seqan3::fmtflags2::utf8 << debug_matrix{trace_matrix, database, query}; // as utf8
return 0;
}
| 35.76 | 110 | 0.615213 | marehr |
a301d0bf6bf24f228b6516bb9883443158fc5dc7 | 4,897 | hpp | C++ | include/RED4ext/Map.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Map.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Map.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <cstdint>
#include <functional>
#include <RED4ext/Common.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/REDfunc.hpp>
namespace RED4ext
{
struct IMemoryAllocator;
template<typename K, typename T, class Compare = std::less<K>>
struct Map
{
enum class Flags : int32_t
{
NotSorted = 1 << 0
};
Map(IMemoryAllocator* aAllocator = nullptr)
: Map(aAllocator, aAllocator)
{
}
Map(IMemoryAllocator* aKeyAllocator, IMemoryAllocator* aValueAllocator)
: keys(aKeyAllocator)
, values(aValueAllocator)
, flags(0)
{
}
void ForEach(std::function<void(const K&, T&)> aFunctor) const
{
uint32_t size = GetSize();
for (uint32_t i = 0; i != size; ++i)
{
aFunctor(keys[i], const_cast<T&>(values[i]));
}
}
uint32_t GetCapactiy() const
{
return keys.capacity;
}
uint32_t GetSize() const
{
return keys.size;
}
T* Get(const K& aKey)
{
const auto it = LowerBound(aKey);
if (it == keys.end() || *it != aKey)
return nullptr;
uint32_t index = static_cast<uint32_t>(it - keys.begin());
return &values[index];
}
std::pair<T*, bool> Insert(const K& aKey, const T& aValue)
{
return Emplace(std::forward<const K&>(aKey), std::forward<const T&>(aValue));
}
std::pair<T*, bool> Insert(const K& aKey, T&& aValue)
{
return Emplace(std::forward<const K&>(aKey), std::forward<T&&>(aValue));
}
std::pair<T*, bool> InsertOrAssign(const K& aKey, const T& aValue)
{
std::pair<T*, bool> pair = Emplace(std::forward<const K&>(aKey), std::forward<const T&>(aValue));
if (!pair.second)
{
*pair.first = aValue;
}
return pair;
}
std::pair<T*, bool> InsertOrAssign(const K& aKey, T&& aValue)
{
std::pair<T*, bool> pair = Emplace(std::forward<const K&>(aKey), std::forward<T&&>(aValue));
if (!pair.second)
{
*pair.first = std::move(aValue);
}
return pair;
}
template<class... TArgs>
std::pair<T*, bool> Emplace(const K& aKey, TArgs&&... aArgs)
{
const auto it = LowerBound(aKey);
uint32_t index = static_cast<uint32_t>(it - keys.begin());
if (it != keys.end() && *it == aKey)
{
// Do nothing if the map already contains this key.
return {&values[index], false};
}
keys.Emplace(&keys.entries[index], std::forward<const K&>(aKey));
values.Emplace(&values.entries[index], std::forward<TArgs>(aArgs)...);
return {&values[index], true};
}
bool Remove(const K& aKey)
{
const T* valuePtr = Get(aKey);
if (valuePtr == nullptr)
return false;
uint32_t index = static_cast<uint32_t>(valuePtr - values.begin());
return RemoveAt(index);
}
bool RemoveAt(uint32_t aIndex)
{
if (aIndex >= GetSize())
return false;
keys.RemoveAt(aIndex);
values.RemoveAt(aIndex);
return true;
}
void Sort()
{
// Need to somehow use std::sort...
// This is how the game does it:
uint32_t size = GetSize();
for (uint32_t i = 1; i < size; ++i)
{
K tmpKey = std::move(keys[i]);
T tmpValue = std::move(values[i]);
uint32_t currentIdx = i;
while (currentIdx != 0)
{
if (!Compare{}(tmpKey, keys[currentIdx - 1]))
break;
keys[currentIdx] = std::move(keys[currentIdx - 1]);
values[currentIdx] = std::move(values[currentIdx - 1]);
--currentIdx;
}
keys[currentIdx] = std::move(tmpKey);
values[currentIdx] = std::move(tmpValue);
}
flags &= ~(int32_t)Flags::NotSorted;
}
void Clear()
{
keys.Clear();
values.Clear();
}
void Reserve(uint32_t aCount)
{
keys.Reserve(aCount);
values.Reserve(aCount);
}
DynArray<K> keys; // 00
DynArray<T> values; // 10
int32_t flags; // 20
private:
const K* LowerBound(const K& aKey) const
{
if ((flags & (int32_t)Flags::NotSorted) == (int32_t)Flags::NotSorted)
{
const_cast<Map*>(this)->Sort();
}
return std::lower_bound(keys.begin(), keys.end(), aKey, Compare{});
}
};
RED4EXT_ASSERT_SIZE(RED4EXT_ASSERT_ESCAPE(Map<void*, void*>), 0x28);
RED4EXT_ASSERT_OFFSET(RED4EXT_ASSERT_ESCAPE(Map<void*, void*>), keys, 0);
RED4EXT_ASSERT_OFFSET(RED4EXT_ASSERT_ESCAPE(Map<void*, void*>), values, 0x10);
RED4EXT_ASSERT_OFFSET(RED4EXT_ASSERT_ESCAPE(Map<void*, void*>), flags, 0x20);
} // namespace RED4ext
| 25.638743 | 105 | 0.550541 | Cyberpunk-Extended-Development-Team |
a3023474f92dcc869cfa07d44bca6f0ade4ebe44 | 788 | hpp | C++ | inc/Game.hpp | fklemme/DungeonsAndDoenekes | ce57b3f445ba3cf3e6f82922abd08dd58894c33c | [
"MIT"
] | null | null | null | inc/Game.hpp | fklemme/DungeonsAndDoenekes | ce57b3f445ba3cf3e6f82922abd08dd58894c33c | [
"MIT"
] | null | null | null | inc/Game.hpp | fklemme/DungeonsAndDoenekes | ce57b3f445ba3cf3e6f82922abd08dd58894c33c | [
"MIT"
] | 1 | 2020-06-24T16:08:05.000Z | 2020-06-24T16:08:05.000Z | #pragma once
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <memory>
#include <vector>
#include "Layers/Layer.hpp"
#include "Player.hpp"
class Game {
public:
Game();
~Game();
void run();
void push_layer(std::unique_ptr<Layer> layer);
template <typename LayerType, typename... Args>
void emplace_layer(Args&&... args) {
push_layer(std::make_unique<LayerType>(std::forward<Args>(args)...));
}
inline void update_layers() { m_layers_update = true; }
inline const sf::Font& font() const { return m_font; }
private:
sf::RenderWindow m_main_window;
sf::Font m_font;
std::vector<std::unique_ptr<Layer>> m_layers;
bool m_layers_update = false;
std::unique_ptr<Player> m_player;
}; | 21.888889 | 77 | 0.666244 | fklemme |
a30496fde2ace9a9a4e85b8e631f083e94e6ed2a | 1,929 | inl | C++ | source/Locks_Win32.inl | CodeChex/ConcurrentLock | 42d8e140c4352c425cf59a7e73493edc7d74d9d4 | [
"MIT"
] | null | null | null | source/Locks_Win32.inl | CodeChex/ConcurrentLock | 42d8e140c4352c425cf59a7e73493edc7d74d9d4 | [
"MIT"
] | null | null | null | source/Locks_Win32.inl | CodeChex/ConcurrentLock | 42d8e140c4352c425cf59a7e73493edc7d74d9d4 | [
"MIT"
] | null | null | null | #pragma once
#ifdef IMPL_USING_MFC
typedef class CSyncObject cclSyncObject;
typedef class CSingleLock cclSingleLock;
typedef class CMutex cclMutex;
typedef class CCriticalSection cclCriticalSection;
typedef class CEvent cclEvent;
#else
class _CCL_API cclMutex : public cclSyncObject
{
public:
cclMutex() : cclSyncObject()
{
m_mtx = ::CreateMutex(NULL,FALSE,NULL);
};
virtual ~cclMutex()
{
Unlock();
if ( m_mtx ) ::CloseHandle(m_mtx);
m_mtx = NULL;
};
protected:
virtual BOOL Lock(DWORD dwTimeout=INFINITE)
{
return ( ::WaitForSingleObjectEx(m_mtx,dwTimeout,TRUE) == WAIT_OBJECT_0 );
}
virtual BOOL Unlock()
{
return ::ReleaseMutex(m_mtx);
}
protected:
HANDLE m_mtx;
};
class _CCL_API cclCriticalSection : public cclSyncObject
{
public:
cclCriticalSection() : cclSyncObject()
{
memset(&m_critsec,0,sizeof(m_critsec));
::InitializeCriticalSection(&m_critsec);
};
virtual ~cclCriticalSection()
{
Unlock();
::DeleteCriticalSection(&m_critsec);
memset(&m_critsec,0,sizeof(m_critsec));
};
protected:
virtual BOOL Lock(DWORD dwTimeout=INFINITE)
{
::EnterCriticalSection(&m_critsec);
return TRUE;
};
virtual BOOL Unlock()
{
::LeaveCriticalSection(&m_critsec);
return TRUE;
}
protected:
CRITICAL_SECTION m_critsec;
};
class _CCL_API cclEvent
{
public:
cclEvent()
{
m_evt = ::CreateEvent(NULL,FALSE,FALSE,NULL);
};
virtual ~cclEvent()
{
PulseEvent();
if ( m_evt ) ::CloseHandle(m_evt);
};
BOOL SetEvent()
{
return ::SetEvent(m_evt);
};
BOOL ResetEvent()
{
return ::ResetEvent(m_evt);
};
BOOL PulseEvent()
{
return ::PulseEvent(m_evt);
};
DWORD Wait(DWORD dwTimeout=INFINITE)
{
//ResetEvent();
return ( ::WaitForSingleObjectEx(m_evt,dwTimeout,TRUE) == WAIT_OBJECT_0 );
};
protected:
HANDLE m_evt;
};
#endif // _AFXDLL | 17.536364 | 77 | 0.66563 | CodeChex |
a3053f70ec5b4b24801fc1b36e908bf2462bde63 | 811 | cpp | C++ | src/network/scope_runner.cpp | Andrei-Masilevich/barbacoa-server-lib | 2eda2fab20c6c1d5a8a78b71952ca61330d04878 | [
"MIT"
] | null | null | null | src/network/scope_runner.cpp | Andrei-Masilevich/barbacoa-server-lib | 2eda2fab20c6c1d5a8a78b71952ca61330d04878 | [
"MIT"
] | null | null | null | src/network/scope_runner.cpp | Andrei-Masilevich/barbacoa-server-lib | 2eda2fab20c6c1d5a8a78b71952ca61330d04878 | [
"MIT"
] | null | null | null | #include <server_lib/network/scope_runner.h>
#include <server_lib/asserts.h>
namespace server_lib {
namespace network {
std::unique_ptr<scope_runner::shared_lock> scope_runner::continue_lock()
{
long expected = count;
while (expected >= 0 && !count.compare_exchange_weak(expected, expected + 1))
spin_loop_pause();
if (expected < 0)
return nullptr;
else
return std::unique_ptr<shared_lock>(new shared_lock(count));
}
void scope_runner::stop()
{
long expected = 0;
while (!count.compare_exchange_weak(expected, -1))
{
if (expected < 0)
return;
expected = 0;
spin_loop_pause();
}
}
} // namespace network
} // namespace server_lib
| 23.852941 | 85 | 0.583231 | Andrei-Masilevich |
a306029088ea13bc75f5ea6a091d0a886c784f89 | 8,586 | inl | C++ | include/util/Quaternion.inl | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 227 | 2018-09-17T16:03:35.000Z | 2022-03-19T02:02:45.000Z | include/util/Quaternion.inl | DragonJoker/RendererLib | 0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a | [
"MIT"
] | 39 | 2018-02-06T22:22:24.000Z | 2018-08-29T07:11:06.000Z | include/util/Quaternion.inl | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 8 | 2019-05-04T10:33:32.000Z | 2021-04-05T13:19:27.000Z | /*
This file belongs to Ashes.
See LICENSE file in root folder
*/
#include <math.h>
#include "util/Vectorisation.hpp"
namespace utils
{
template< typename T >
QuaternionT< T >::QuaternionT( NoInit const & )noexcept
{
}
template< typename T >
constexpr QuaternionT< T >::QuaternionT()noexcept
: x{}
, y{}
, z{}
, w{ T{ 1 } }
{
}
template< typename T >
template< typename W
, typename X
, typename Y
, typename Z >
constexpr QuaternionT< T >::QuaternionT( W const & w
, X const & x
, Y const & y
, Z const & z )noexcept
: x{ T( x ) }
, y{ T( y ) }
, z{ T( z ) }
, w{ T( w ) }
{
}
template< typename T >
QuaternionT< T >::QuaternionT( Vec3T< T > const & u, Vec3T< T > const & v )noexcept
{
Vec3T< T > const localW( cross( u, v ) );
T dot = dot( u, v );
QuaternionT< T > q( T{ 1 } + dot, localW.x, localW.y, localW.z );
*this = normalize( q );
}
template< typename T >
QuaternionT< T >::QuaternionT( Vec3T< RadiansT< T > > const & euler )noexcept
{
Vec3T< T > c{ vectorCall( utils::cos< T >, euler * T{ 0.5 } ) };
Vec3T< T > s{ vectorCall( utils::sin< T >, euler * T{ 0.5 } ) };
w = c.x * c.y * c.z + s.x * s.y * s.z;
x = s.x * c.y * c.z - c.x * s.y * s.z;
y = c.x * s.y * c.z + s.x * c.y * s.z;
z = c.x * c.y * s.z - s.x * s.y * c.z;
}
template< typename T >
template< typename U >
QuaternionT< T >::QuaternionT( QuaternionT< U > const & rhs )noexcept
: x{ T( rhs.x ) }
, y{ T( rhs.y ) }
, z{ T( rhs.z ) }
, w{ T( rhs.w ) }
{
}
template< typename T >
template< typename U >
QuaternionT< T > & QuaternionT< T >::operator=( QuaternionT< U > const & rhs )noexcept
{
x = T( rhs.x );
y = T( rhs.y );
z = T( rhs.z );
w = T( rhs.w );
}
template< typename T >
template< typename U >
inline QuaternionT< T > & QuaternionT< T >::operator+=( QuaternionT< U > const & rhs )noexcept
{
x = T( x + rhs.x );
y = T( y + rhs.y );
z = T( z + rhs.z );
w = T( w + rhs.w );
return *this;
}
template< typename T >
template< typename U >
inline QuaternionT< T > & QuaternionT< T >::operator-=( QuaternionT< U > const & rhs )noexcept
{
x = T( x - rhs.x );
y = T( y - rhs.y );
z = T( z - rhs.z );
w = T( w - rhs.w );
return *this;
}
template< typename T >
template< typename U >
inline QuaternionT< T > & QuaternionT< T >::operator*=( QuaternionT< U > const & rhs )noexcept
{
QuaternionT< T > const p{ *this };
w = p.w * rhs.w - p.x * rhs.x - p.y * rhs.y - p.z * rhs.z;
x = p.w * rhs.x + p.x * rhs.w + p.y * rhs.z - p.z * rhs.y;
y = p.w * rhs.y + p.y * rhs.w + p.z * rhs.x - p.x * rhs.z;
z = p.w * rhs.z + p.z * rhs.w + p.x * rhs.y - p.y * rhs.x;
return *this;
}
template< typename T >
template< typename U >
inline QuaternionT< T > & QuaternionT< T >::operator*=( U const & rhs )noexcept
{
x = T( x * rhs );
y = T( y * rhs );
z = T( z * rhs );
w = T( w * rhs );
return *this;
}
template< typename T >
template< typename U >
inline QuaternionT< T > & QuaternionT< T >::operator/=( U const & rhs )noexcept
{
x = T( x / rhs );
y = T( y / rhs );
z = T( z / rhs );
w = T( w / rhs );
return *this;
}
template< typename T >
T dot( QuaternionT< T > const & lhs, QuaternionT< T > const & rhs )noexcept
{
return sqrt( lhs.x * rhs.x
+ lhs.y * rhs.y
+ lhs.z * rhs.z
+ lhs.w * rhs.w );
}
template< typename T >
QuaternionT< T > cross( QuaternionT< T > const & lhs, QuaternionT< T > const & rhs )noexcept
{
return QuaternionT< T >
{
lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z,
lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y,
lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z,
lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x
};
}
template< typename T >
T length( QuaternionT< T > const & quat )noexcept
{
return dot( quat, quat );
}
template< typename T >
T distance( QuaternionT< T > const & lhs, QuaternionT< T > const & rhs )noexcept
{
return length( rhs - lhs );
}
template< typename T >
QuaternionT< T > normalize( QuaternionT< T > const & vec )noexcept
{
auto norm = length( vec );
return QuaternionT< T >
{
vec.x / norm,
vec.y / norm,
vec.z / norm,
vec.w / norm
};
}
template <typename T >
QuaternionT< T > conjugate( QuaternionT< T > const & q )noexcept
{
return QuaternionT< T >( q.w, -q.x, -q.y, -q.z );
}
template <typename T >
QuaternionT< T > inverse( QuaternionT< T > const & q )noexcept
{
return conjugate( q ) / dot( q, q );
}
template< typename T, typename U >
Vec3T< T > rotate( QuaternionT< T > const & q, Vec3T< U > const & v )noexcept
{
return q * v;
}
template< typename T, typename U >
Vec4T< T > rotate( QuaternionT< T > const & q, Vec4T< U > const & v )noexcept
{
return q * v;
}
template< typename T >
QuaternionT< T > rotate( QuaternionT< T > const & q,
RadiansT < T > const & angle,
Vec3T< T > const & axis )noexcept
{
assert( std::abs( length( axis ) - T( 1 ) ) <= T( 0.001 ) );
T const sinA = sin( angle * T( 0.5 ) );
return q * QuaternionT< T >{ cos( angle * T( 0.5 ) )
, axis.x * sinA
, axis.y * sinA
, axis.z * sinA };
}
template< typename T >
QuaternionT< T > pitch( QuaternionT< T > const & q,
RadiansT < T > const & angle )noexcept
{
return rotate( q, angle, Vec3T< T >{ T{ 1 }, T{}, T{} } );
}
template< typename T >
QuaternionT< T > yaw( QuaternionT< T > const & q,
RadiansT < T > const & angle )noexcept
{
return rotate( q, angle, Vec3T< T >{ T{}, T{ 1 }, T{} } );
}
template< typename T >
QuaternionT< T > roll( QuaternionT< T > const & q,
RadiansT < T > const & angle )noexcept
{
return rotate( q, angle, Vec3T< T >{ T{}, T{}, T{ 1 } } );
}
template< typename T >
Mat4T< T > toMat4( QuaternionT< T > const & q )noexcept
{
Mat4T< T > result{ T{ 1 } };
T qxx{ q.x * q.x };
T qyy{ q.y * q.y };
T qzz{ q.z * q.z };
T qxz{ q.x * q.z };
T qxy{ q.x * q.y };
T qyz{ q.y * q.z };
T qwx{ q.w * q.x };
T qwy{ q.w * q.y };
T qwz{ q.w * q.z };
result[0][0] = T{ 1 } - T{ 2 } * ( qyy + qzz );
result[0][1] = T{ 2 } * ( qxy + qwz );
result[0][2] = T{ 2 } * ( qxz - qwy );
result[1][0] = T{ 2 } * ( qxy - qwz );
result[1][1] = T{ 1 } - T{ 2 } * ( qxx + qzz );
result[1][2] = T{ 2 } * ( qyz + qwx );
result[2][0] = T{ 2 } * ( qxz + qwy );
result[2][1] = T{ 2 } * ( qyz - qwx );
result[2][2] = T{ 1 } - T{ 2 } * ( qxx + qyy );
return result;
}
template< typename T >
inline bool operator==( QuaternionT< T > const & lhs
, QuaternionT< T > const & rhs )noexcept
{
return lhs.x == rhs.x
&& lhs.y == rhs.y
&& lhs.z == rhs.z
&& lhs.w == rhs.w;
}
template< typename T >
inline bool operator!=( QuaternionT< T > const & lhs
, QuaternionT< T > const & rhs )noexcept
{
return lhs.x != rhs.x
|| lhs.y != rhs.y
|| lhs.z != rhs.z
|| lhs.w != rhs.w;
}
template< typename T, typename U >
inline QuaternionT< T > operator+( QuaternionT< T > const & lhs
, QuaternionT< U > const & rhs )noexcept
{
QuaternionT< T > result{ lhs };
result += rhs;
return result;
}
template< typename T, typename U >
inline QuaternionT< T > operator-( QuaternionT< T > const & lhs
, QuaternionT< U > const & rhs )noexcept
{
QuaternionT< T > result{ lhs };
result -= rhs;
return result;
}
template< typename T, typename U >
inline QuaternionT< T > operator*( QuaternionT< T > const & lhs
, QuaternionT< U > const & rhs )noexcept
{
QuaternionT< T > result{ lhs };
result *= rhs;
return result;
}
template< typename T, typename U >
inline QuaternionT< T > operator*( QuaternionT< T > const & lhs
, U const & rhs )noexcept
{
QuaternionT< T > result{ lhs };
result *= rhs;
return result;
}
template< typename T, typename U >
inline QuaternionT< T > operator/( QuaternionT< T > const & lhs
, U const & rhs )noexcept
{
QuaternionT< T > result{ lhs };
result /= rhs;
return result;
}
template< typename T, typename U >
inline Vec3T< T > operator*( QuaternionT< T > const & lhs
, Vec3T< U > const & rhs )noexcept
{
Vec3T< T > const quatVector{ lhs.x, lhs.y, lhs.z };
Vec3T< T > const uv{ cross( quatVector, rhs ) };
Vec3T< T > const uuv{ cross( quatVector, uv ) };
return rhs + ( ( uv * lhs.w ) + uuv ) * static_cast< T >( 2 );
}
template< typename T, typename U >
inline Vec4T< T > operator*( QuaternionT< T > const & lhs
, Vec4T< U > const & rhs )noexcept
{
return Vec4T< T >
{
lhs.x * rhs.x,
lhs.y * rhs.y,
lhs.z * rhs.z,
lhs.w * rhs.w
};
}
}
| 23.718232 | 95 | 0.555439 | DragonJoker |
a30829060bc8c519ef8adb29efe198508ef8b566 | 993 | hh | C++ | include/ATLHECTBPrimaryGeneratorAction.hh | lopezzot/ATLHECTB | 1d45179e70aaa6b7dd6eb08c3d13063f440cfc9f | [
"MIT"
] | 5 | 2021-05-20T15:54:33.000Z | 2022-03-14T14:08:42.000Z | include/ATLHECTBPrimaryGeneratorAction.hh | lopezzot/ATLHECTB | 1d45179e70aaa6b7dd6eb08c3d13063f440cfc9f | [
"MIT"
] | 8 | 2021-09-14T15:06:04.000Z | 2021-10-17T15:35:03.000Z | include/ATLHECTBPrimaryGeneratorAction.hh | lopezzot/ATLHECTB | 1d45179e70aaa6b7dd6eb08c3d13063f440cfc9f | [
"MIT"
] | null | null | null | //**************************************************
// \file ATLHECTBPrimaryGeneratorAction.hh
// \brief: Definition of ATLHECTBPrimaryGeneratorAction class
// \author: Lorenzo Pezzotti (CERN EP-SFT-sim) @lopezzot
// \start date: 11 May 2021
//**************************************************
//Prevent including header multiple times
//
#ifndef ATLHECTBPrimaryGeneratorAction_h
#define ATLHECTBPrimaryGeneratorAction_h 1
//Includers from Geant4
//
#include "G4VUserPrimaryGeneratorAction.hh"
#include "globals.hh"
class G4ParticleGun;
class G4Event;
class ATLHECTBPrimaryGeneratorAction : public G4VUserPrimaryGeneratorAction {
public:
ATLHECTBPrimaryGeneratorAction();
virtual ~ATLHECTBPrimaryGeneratorAction();
virtual void GeneratePrimaries( G4Event* event );
void SetRandomFlag( G4bool value ); //to check what this does
private:
G4ParticleGun* fParticleGun;
};
#endif
//**************************************************
| 25.461538 | 77 | 0.633434 | lopezzot |
a3134f0ddf77dd8ab6ea8aab99f7033f4c6e4618 | 1,209 | cpp | C++ | source/mango/filesystem/path.cpp | aniketanvit/mango | 659a6836354ae881c6860f5b961d65ac1f1e85c6 | [
"Zlib"
] | 1 | 2021-08-06T09:27:45.000Z | 2021-08-06T09:27:45.000Z | source/mango/filesystem/path.cpp | galek/mango | 975b438ac9a22ed3a849da6187e1fdf3d547c926 | [
"Zlib"
] | null | null | null | source/mango/filesystem/path.cpp | galek/mango | 975b438ac9a22ed3a849da6187e1fdf3d547c926 | [
"Zlib"
] | 1 | 2021-07-10T11:41:01.000Z | 2021-07-10T11:41:01.000Z | /*
MANGO Multimedia Development Platform
Copyright (C) 2012-2016 Twilight Finland 3D Oy Ltd. All rights reserved.
*/
#include <algorithm>
#include <mango/filesystem/path.hpp>
namespace mango
{
// -----------------------------------------------------------------
// Path
// -----------------------------------------------------------------
Path::Path(const std::string& pathname, const std::string& password)
{
// create mapper to raw filesystem
m_mapper = getFileMapper();
// parse and create mappers
m_pathname = parse(pathname, password);
m_mapper->index(m_files, m_pathname);
}
Path::Path(const Path& path, const std::string& pathname, const std::string& password)
{
// use parent's mapper
m_mapper = path.m_mapper;
// parse and create mappers
m_pathname = parse(path.m_pathname + pathname, password);
m_mapper->index(m_files, m_pathname);
}
Path::~Path()
{
}
void Path::updateIndex()
{
m_files.clear();
m_mapper->index(m_files, m_pathname);
}
const std::string& Path::pathname() const
{
return m_pathname;
}
} // namespace mango
| 23.705882 | 90 | 0.548387 | aniketanvit |
a314039585b82df9ad2ef923cf0f75ed7b4d8ec3 | 329 | hh | C++ | Resources/Sources/Includes/Timer/Timer.hh | hunyadix/dcolscan_tools | df5fb7a01d43dec358f24808b9bbf1c7baf75c7d | [
"MIT"
] | null | null | null | Resources/Sources/Includes/Timer/Timer.hh | hunyadix/dcolscan_tools | df5fb7a01d43dec358f24808b9bbf1c7baf75c7d | [
"MIT"
] | null | null | null | Resources/Sources/Includes/Timer/Timer.hh | hunyadix/dcolscan_tools | df5fb7a01d43dec358f24808b9bbf1c7baf75c7d | [
"MIT"
] | null | null | null | #ifndef TIMER_H
#define TIMER_H
#include <string>
#include <iostream>
class Timer
{
protected:
time_t start_t;
time_t current_t;
double seconds_elapsed;
public:
Timer();
~Timer();
virtual void restart(std::string text_p);
virtual void print_seconds(std::string pretext_p, std::string post_text_p);
};
#endif
| 15.666667 | 77 | 0.723404 | hunyadix |
a314f906e51cbfbcb7d7bb92ba8c975db7a82c02 | 7,687 | cpp | C++ | src/sim/displays/testmfd.cpp | Terebinth/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 117 | 2015-01-13T14:48:49.000Z | 2022-03-16T01:38:19.000Z | src/sim/displays/testmfd.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 4 | 2015-05-01T13:09:53.000Z | 2017-07-22T09:11:06.000Z | src/sim/displays/testmfd.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 78 | 2015-01-13T09:27:47.000Z | 2022-03-18T14:39:09.000Z | #include "stdhdr.h"
#include "camplib.h"
#include "mfd.h"
#include "Graphics/Include/render2d.h"
#include "dispcfg.h"
#include "simdrive.h"
#include "camp2sim.h"
#include "hud.h"
#include "aircrft.h"
#include "fack.h"
#include "otwdrive.h" //MI
#include "cpmanager.h" //MI
#include "icp.h" //MI
#include "aircrft.h" //MI
#include "fcc.h" //MI
#include "radardoppler.h" //MI
//MI
void DrawBullseyeCircle(VirtualDisplay* display, float cursorX, float cursorY);
struct MfdTestButtons
{
char *label1, *label2;
enum { ModeNoop = 0, // do nothing
ModeParent, // hand off to parent
ModeTest1,
ModeTest2, // two test sub modes
ModeRaltTest,
ModeRunTest,
ModeClear,
};
int nextMode;
};
#define NOENTRY { NULL, NULL, MfdTestButtons::ModeNoop}
#define PARENT { NULL, NULL, MfdTestButtons::ModeParent}
static const MfdTestButtons testpage1[20] =
{
// test page menu
{"BIT1", NULL, MfdTestButtons::ModeTest2}, // 1
NOENTRY,
{"CLR", NULL, MfdTestButtons::ModeClear},
NOENTRY,
NOENTRY, // 5
{"MFDS", NULL, MfdTestButtons::ModeRunTest},
{"RALT", "500", MfdTestButtons::ModeRaltTest},
{"TGP", NULL, MfdTestButtons::ModeRunTest},
{"FINS", NULL, MfdTestButtons::ModeRunTest},
{"TFR", NULL, MfdTestButtons::ModeRunTest}, // 10
PARENT,
PARENT,
PARENT,
PARENT, // current mode
PARENT, // 15
{"RSU", NULL, MfdTestButtons::ModeRunTest},
{"INS", NULL, MfdTestButtons::ModeRunTest},
{"SMS", NULL, MfdTestButtons::ModeNoop},
{"FCR", NULL, MfdTestButtons::ModeRunTest},
{"DTE", NULL, MfdTestButtons::ModeRunTest}, // 20
};
static const MfdTestButtons testpage2[20] =
{
// test page menu
{"BIT2", NULL, MfdTestButtons::ModeTest1}, // 1
NOENTRY,
{"CLR", NULL, MfdTestButtons::ModeClear},
NOENTRY,
NOENTRY, // 5
{"IFF1", NULL, MfdTestButtons::ModeRunTest},
{"IFF2", NULL, MfdTestButtons::ModeRunTest},
{"IFF3", NULL, MfdTestButtons::ModeRunTest},
{"IFFC", NULL, MfdTestButtons::ModeRunTest},
{"TCN", NULL, MfdTestButtons::ModeRunTest}, // 10
PARENT,
PARENT,
PARENT,
PARENT,
PARENT, // 15
{NULL, NULL, MfdTestButtons::ModeNoop},
{NULL, NULL, MfdTestButtons::ModeNoop},
{NULL, NULL, MfdTestButtons::ModeNoop},
{"TISL", NULL, MfdTestButtons::ModeRunTest},
{"UFC", NULL, MfdTestButtons::ModeRunTest}, // 20
};
struct MfdTestPage
{
const MfdTestButtons *buttons;
};
static const MfdTestPage mfdpages[] =
{
{testpage1},
{testpage2},
};
static const int NMFDPAGES = sizeof(mfdpages) / sizeof(mfdpages[0]);
TestMfdDrawable::TestMfdDrawable()
{
bitpage = 0;
bittest = -1;
timer = 0;
}
void TestMfdDrawable::Display(VirtualDisplay* newDisplay)
{
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
//MI
float cX, cY = 0;
if (g_bRealisticAvionics)
{
RadarDopplerClass* theRadar = (RadarDopplerClass*)FindSensor(playerAC, SensorClass::Radar);
if ( not theRadar)
{
ShiWarning("Oh Oh shouldn't be here without a radar");
return;
}
else
{
theRadar->GetCursorPosition(&cX, &cY);
}
}
display = newDisplay;
ShiAssert(bitpage >= 0 and bitpage < sizeof(mfdpages) / sizeof(mfdpages[0]));
ShiAssert(display not_eq NULL);
const MfdTestButtons *mb = mfdpages[bitpage].buttons;
AircraftClass *self = MfdDisplay[OnMFD()]->GetOwnShip();
ShiAssert(self not_eq NULL);
//MI changed
if (g_bRealisticAvionics)
{
if (OTWDriver.pCockpitManager and OTWDriver.pCockpitManager->mpIcp and
OTWDriver.pCockpitManager->mpIcp->ShowBullseyeInfo)
{
DrawBullseyeCircle(display, cX, cY);
}
else
DrawReference(self);
}
else
DrawReference(self);
display->SetColor(GetMfdColor(MFD_LABELS));
char buf[100];
for (int i = 0; i < 20; i++)
{
int hilite = 0;
if (i == bittest and timer > SimLibElapsedTime)
hilite = 1;
switch (mb[i].nextMode)
{
case MfdTestButtons::ModeRaltTest:
sprintf(buf, "%.0f", hilite ? 300.0f : TheHud->lowAltWarning);
LabelButton(i, mb[i].label1, buf, hilite);
break;
default:
if (mb[i].label1)
LabelButton(i, mb[i].label1, mb[i].label2, hilite);
else if (mb[i].nextMode == MfdTestButtons::ModeParent)
MfdDrawable::DefaultLabel(i);
}
}
if (playerAC and playerAC->mFaults)
{
FackClass *fack = playerAC->mFaults;
float yinc = display->TextHeight();
const static float namex = -0.6f;
const static float starty = 0.6f;
float y = starty;
float x = namex;
float xinc = 0.3F;
for (int i = 0; i < fack->GetMflListCount(); i++)
{
const char *fname;
int subsys;
int count;
char timestr[100];
if (fack->GetMflEntry(i, &fname, &subsys, &count, timestr) == false)
continue;
char outstr[100];
for (int i = 0; i < 5; i++)
{
switch (i)
{
case 1:
sprintf(outstr, "%-4s", fname);
display->TextLeft(x, y, outstr);
x += xinc;
break;
case 2:
sprintf(outstr, "%03d", subsys);
display->TextLeft(x, y, outstr);
x += xinc;
break;
case 3:
x -= 0.1F;
sprintf(outstr, "%2d", count);
display->TextLeft(x, y, outstr);
x += xinc;
break;
case 4:
x -= 0.1F;
sprintf(outstr, "%s", timestr);
display->TextLeft(x, y, outstr);
x += xinc;
break;
default:
break;
}
}
//sprintf (outstr, "%-4s %03d %2d %s", fname, subsys, count, timestr);
//ShiAssert(strlen(outstr) < sizeof outstr);
//display->TextLeft(namex, y, outstr);
y -= yinc;
x = namex;
}
}
}
void TestMfdDrawable::PushButton(int whichButton, int whichMFD)
{
ShiAssert(bitpage >= 0 and bitpage < sizeof(mfdpages) / sizeof(mfdpages[0]));
ShiAssert(whichButton >= 0 and whichButton < 20);
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
switch (mfdpages[bitpage].buttons[whichButton].nextMode)
{
case MfdTestButtons::ModeNoop:
break;
case MfdTestButtons::ModeRaltTest:
case MfdTestButtons::ModeRunTest:
bittest = whichButton;
timer = SimLibElapsedTime + 5 * CampaignSeconds;
break;
case MfdTestButtons::ModeTest2:
bitpage = 1;
break;
case MfdTestButtons::ModeTest1:
bitpage = 0;
break;
case MfdTestButtons::ModeParent:
MfdDrawable::PushButton(whichButton, whichMFD);
break;
case MfdTestButtons::ModeClear: // clear MFL
if (playerAC and playerAC->mFaults)
playerAC->mFaults->ClearMfl();
break;
}
}
| 27.651079 | 99 | 0.540263 | Terebinth |
a315cdc1064f02ffa24047319bab9fe841bf95bb | 404 | cpp | C++ | General/Learning/C++/2/main.cpp | 123456789x/usaco-guide-solutions | fa3ea5c7c8160aec29f48187e39b0301a4d633fd | [
"MIT"
] | null | null | null | General/Learning/C++/2/main.cpp | 123456789x/usaco-guide-solutions | fa3ea5c7c8160aec29f48187e39b0301a4d633fd | [
"MIT"
] | null | null | null | General/Learning/C++/2/main.cpp | 123456789x/usaco-guide-solutions | fa3ea5c7c8160aec29f48187e39b0301a4d633fd | [
"MIT"
] | null | null | null | #include "ops.h"
#include <iostream>
using std::cin;
using std::cout;
int main()
{
int a;
cout << "Enter first integer: ";
cin >> a;
int b;
cout << "Enter second integer: ";
cin >> b;
cout << "Sum: " << add(a, b) << "\n";
cout << "Difference: " << subtract(a, b) << "\n";
cout << "Product: " << multiply(a, b) << "\n";
cout << "Quotient: " << divide(a, b) << "\n";
return 0;
}
| 16.833333 | 51 | 0.502475 | 123456789x |
a31c7917c40f652b2f9ef88a3bd093593060846b | 9,091 | cpp | C++ | emulation/hel/lib/athena/HAL.cpp | NWalker1208/synthesis | c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34 | [
"Apache-2.0"
] | null | null | null | emulation/hel/lib/athena/HAL.cpp | NWalker1208/synthesis | c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34 | [
"Apache-2.0"
] | null | null | null | emulation/hel/lib/athena/HAL.cpp | NWalker1208/synthesis | c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34 | [
"Apache-2.0"
] | null | null | null | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "HAL/HAL.h"
//#include <signal.h> // linux for kill
//#include <unistd.h>
//#include <sys/time.h>
#include <atomic>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <mutex>
#include <thread>
#include "FRC_NetworkCommunication/CANSessionMux.h"
#include "FRC_NetworkCommunication/FRCComm.h"
#include "FRC_NetworkCommunication/LoadOut.h"
#include "HAL/ChipObject.h"
#include "HAL/DriverStation.h"
#include "HAL/Errors.h"
#include "HAL/Notifier.h"
#include "HAL/cpp/priority_mutex.h"
#include "HAL/handles/HandlesInternal.h"
#include "ctre/ctre.h"
#include "visa/visa.h"
#include <chrono>
using namespace hal;
static std::unique_ptr<tGlobal> global;
static std::unique_ptr<tSysWatchdog> watchdog;
const char* WPILibVersion = "Fake";
static hal::priority_mutex timeMutex;
static uint32_t timeEpoch = 0;
static uint32_t prevFPGATime = 0;
static HAL_NotifierHandle rolloverNotifier = 0;
using namespace hal;
extern "C" {
HAL_PortHandle HAL_GetPort(int32_t channel) {
// Dont allow a number that wouldn't fit in a uint8_t
if (channel < 0 || channel >= 255) return HAL_kInvalidHandle;
return createPortHandle(channel, 1);
}
/**
* @deprecated Uses module numbers
*/
HAL_PortHandle HAL_GetPortWithModule(int32_t module, int32_t channel) {
// Dont allow a number that wouldn't fit in a uint8_t
if (channel < 0 || channel >= 255) return HAL_kInvalidHandle;
if (module < 0 || module >= 255) return HAL_kInvalidHandle;
return createPortHandle(channel, module);
}
const char* HAL_GetErrorMessage(int32_t code) {
switch (code) {
case 0:
return "";
case CTR_RxTimeout:
return CTR_RxTimeout_MESSAGE;
case CTR_TxTimeout:
return CTR_TxTimeout_MESSAGE;
case CTR_InvalidParamValue:
return CTR_InvalidParamValue_MESSAGE;
case CTR_UnexpectedArbId:
return CTR_UnexpectedArbId_MESSAGE;
case CTR_TxFailed:
return CTR_TxFailed_MESSAGE;
case CTR_SigNotUpdated:
return CTR_SigNotUpdated_MESSAGE;
case NiFpga_Status_FifoTimeout:
return NiFpga_Status_FifoTimeout_MESSAGE;
case NiFpga_Status_TransferAborted:
return NiFpga_Status_TransferAborted_MESSAGE;
case NiFpga_Status_MemoryFull:
return NiFpga_Status_MemoryFull_MESSAGE;
case NiFpga_Status_SoftwareFault:
return NiFpga_Status_SoftwareFault_MESSAGE;
case NiFpga_Status_InvalidParameter:
return NiFpga_Status_InvalidParameter_MESSAGE;
case NiFpga_Status_ResourceNotFound:
return NiFpga_Status_ResourceNotFound_MESSAGE;
case NiFpga_Status_ResourceNotInitialized:
return NiFpga_Status_ResourceNotInitialized_MESSAGE;
case NiFpga_Status_HardwareFault:
return NiFpga_Status_HardwareFault_MESSAGE;
case NiFpga_Status_IrqTimeout:
return NiFpga_Status_IrqTimeout_MESSAGE;
case SAMPLE_RATE_TOO_HIGH:
return SAMPLE_RATE_TOO_HIGH_MESSAGE;
case VOLTAGE_OUT_OF_RANGE:
return VOLTAGE_OUT_OF_RANGE_MESSAGE;
case LOOP_TIMING_ERROR:
return LOOP_TIMING_ERROR_MESSAGE;
case SPI_WRITE_NO_MOSI:
return SPI_WRITE_NO_MOSI_MESSAGE;
case SPI_READ_NO_MISO:
return SPI_READ_NO_MISO_MESSAGE;
case SPI_READ_NO_DATA:
return SPI_READ_NO_DATA_MESSAGE;
case INCOMPATIBLE_STATE:
return INCOMPATIBLE_STATE_MESSAGE;
case NO_AVAILABLE_RESOURCES:
return NO_AVAILABLE_RESOURCES_MESSAGE;
case RESOURCE_IS_ALLOCATED:
return RESOURCE_IS_ALLOCATED_MESSAGE;
case RESOURCE_OUT_OF_RANGE:
return RESOURCE_OUT_OF_RANGE_MESSAGE;
case HAL_INVALID_ACCUMULATOR_CHANNEL:
return HAL_INVALID_ACCUMULATOR_CHANNEL_MESSAGE;
case HAL_HANDLE_ERROR:
return HAL_HANDLE_ERROR_MESSAGE;
case NULL_PARAMETER:
return NULL_PARAMETER_MESSAGE;
case ANALOG_TRIGGER_LIMIT_ORDER_ERROR:
return ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE;
case ANALOG_TRIGGER_PULSE_OUTPUT_ERROR:
return ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE;
case PARAMETER_OUT_OF_RANGE:
return PARAMETER_OUT_OF_RANGE_MESSAGE;
case HAL_COUNTER_NOT_SUPPORTED:
return HAL_COUNTER_NOT_SUPPORTED_MESSAGE;
case ERR_CANSessionMux_InvalidBuffer:
return ERR_CANSessionMux_InvalidBuffer_MESSAGE;
case ERR_CANSessionMux_MessageNotFound:
return ERR_CANSessionMux_MessageNotFound_MESSAGE;
case WARN_CANSessionMux_NoToken:
return WARN_CANSessionMux_NoToken_MESSAGE;
case ERR_CANSessionMux_NotAllowed:
return ERR_CANSessionMux_NotAllowed_MESSAGE;
case ERR_CANSessionMux_NotInitialized:
return ERR_CANSessionMux_NotInitialized_MESSAGE;
case VI_ERROR_SYSTEM_ERROR:
return VI_ERROR_SYSTEM_ERROR_MESSAGE;
case VI_ERROR_INV_OBJECT:
return VI_ERROR_INV_OBJECT_MESSAGE;
case VI_ERROR_RSRC_LOCKED:
return VI_ERROR_RSRC_LOCKED_MESSAGE;
case VI_ERROR_RSRC_NFOUND:
return VI_ERROR_RSRC_NFOUND_MESSAGE;
case VI_ERROR_INV_RSRC_NAME:
return VI_ERROR_INV_RSRC_NAME_MESSAGE;
case VI_ERROR_QUEUE_OVERFLOW:
return VI_ERROR_QUEUE_OVERFLOW_MESSAGE;
case VI_ERROR_IO:
return VI_ERROR_IO_MESSAGE;
case VI_ERROR_ASRL_PARITY:
return VI_ERROR_ASRL_PARITY_MESSAGE;
case VI_ERROR_ASRL_FRAMING:
return VI_ERROR_ASRL_FRAMING_MESSAGE;
case VI_ERROR_ASRL_OVERRUN:
return VI_ERROR_ASRL_OVERRUN_MESSAGE;
case VI_ERROR_RSRC_BUSY:
return VI_ERROR_RSRC_BUSY_MESSAGE;
case VI_ERROR_INV_PARAMETER:
return VI_ERROR_INV_PARAMETER_MESSAGE;
case HAL_PWM_SCALE_ERROR:
return HAL_PWM_SCALE_ERROR_MESSAGE;
case HAL_SERIAL_PORT_NOT_FOUND:
return HAL_SERIAL_PORT_NOT_FOUND_MESSAGE;
case HAL_THREAD_PRIORITY_ERROR:
return HAL_THREAD_PRIORITY_ERROR_MESSAGE;
case HAL_THREAD_PRIORITY_RANGE_ERROR:
return HAL_THREAD_PRIORITY_RANGE_ERROR_MESSAGE;
case HAL_SERIAL_PORT_OPEN_ERROR:
return HAL_SERIAL_PORT_OPEN_ERROR_MESSAGE;
case HAL_SERIAL_PORT_ERROR:
return HAL_SERIAL_PORT_ERROR_MESSAGE;
default:
return "Unknown error status";
}
}
/**
* Returns the runtime type of this HAL
*/
HAL_RuntimeType HAL_GetRuntimeType() { return HAL_Athena; }
/**
* Return the FPGA Version number.
* For now, expect this to be competition year.
* @return FPGA Version number.
*/
int32_t HAL_GetFPGAVersion(int32_t* status) {
if (!global) {
*status = NiFpga_Status_ResourceNotInitialized;
return 0;
}
return global->readVersion(status);
}
/**
* Return the FPGA Revision number.
* The format of the revision is 3 numbers.
* The 12 most significant bits are the Major Revision.
* the next 8 bits are the Minor Revision.
* The 12 least significant bits are the Build Number.
* @return FPGA Revision number.
*/
int64_t HAL_GetFPGARevision(int32_t* status) {
return 0;
}
/**
* Read the microsecond-resolution timer on the FPGA.
*
* @return The current time in microseconds according to the FPGA (since FPGA
* reset).
*/
uint64_t HAL_GetFPGATime(int32_t* status) {
*status = 0;
return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
/**
* Get the state of the "USER" button on the roboRIO
* @return true if the button is currently pressed down
*/
HAL_Bool HAL_GetFPGAButton(int32_t* status) {
return false;
}
HAL_Bool HAL_GetSystemActive(int32_t* status) {
return false;
}
HAL_Bool HAL_GetBrownedOut(int32_t* status) {
return false;
}
static void timerRollover(uint64_t currentTime, HAL_NotifierHandle handle) {}
void HAL_BaseInitialize(int32_t* status) {
static std::atomic_bool initialized{false};
static hal::priority_mutex initializeMutex;
// Initial check, as if it's true initialization has finished
if (initialized) return;
std::lock_guard<hal::priority_mutex> lock(initializeMutex);
// Second check in case another thread was waiting
if (initialized) return;
initialized = true;
}
/**
* Call this to start up HAL. This is required for robot programs.
*/
int32_t HAL_Initialize(int32_t timeout, int32_t mode) {
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
HAL_InitializeDriverStation();
return 1;
}
int64_t HAL_Report(int32_t resource, int32_t instanceNumber, int32_t context,
const char* feature) {
if (feature == nullptr) {
feature = "";
}
return 0;
}
// TODO: HACKS
// No need for header definitions, as we should not run from user code.
void NumericArrayResize() {}
void RTSetCleanupProc() {}
void EDVR_CreateReference() {}
} // extern "C"
| 31.456747 | 124 | 0.738093 | NWalker1208 |
a31e176d85994ea627a676eb124c63c4048eb030 | 6,103 | hpp | C++ | include/System/Net/SimpleAsyncResult_--c__DisplayClass11_0.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/System/Net/SimpleAsyncResult_--c__DisplayClass11_0.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/System/Net/SimpleAsyncResult_--c__DisplayClass11_0.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Net.SimpleAsyncResult
#include "System/Net/SimpleAsyncResult.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
}
// Forward declaring namespace: System::Net
namespace System::Net {
// Forward declaring type: SimpleAsyncCallback
class SimpleAsyncCallback;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Net::SimpleAsyncResult::$$c__DisplayClass11_0);
DEFINE_IL2CPP_ARG_TYPE(::System::Net::SimpleAsyncResult::$$c__DisplayClass11_0*, "System.Net", "SimpleAsyncResult/<>c__DisplayClass11_0");
// Type namespace: System.Net
namespace System::Net {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: System.Net.SimpleAsyncResult/System.Net.<>c__DisplayClass11_0
// [TokenAttribute] Offset: FFFFFFFF
// [CompilerGeneratedAttribute] Offset: FFFFFFFF
class SimpleAsyncResult::$$c__DisplayClass11_0 : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// public System.Func`2<System.Net.SimpleAsyncResult,System.Boolean> func
// Size: 0x8
// Offset: 0x10
::System::Func_2<::System::Net::SimpleAsyncResult*, bool>* func;
// Field size check
static_assert(sizeof(::System::Func_2<::System::Net::SimpleAsyncResult*, bool>*) == 0x8);
// public System.Object locker
// Size: 0x8
// Offset: 0x18
::Il2CppObject* locker;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
// public System.Net.SimpleAsyncCallback callback
// Size: 0x8
// Offset: 0x20
::System::Net::SimpleAsyncCallback* callback;
// Field size check
static_assert(sizeof(::System::Net::SimpleAsyncCallback*) == 0x8);
public:
// Get instance field reference: public System.Func`2<System.Net.SimpleAsyncResult,System.Boolean> func
::System::Func_2<::System::Net::SimpleAsyncResult*, bool>*& dyn_func();
// Get instance field reference: public System.Object locker
::Il2CppObject*& dyn_locker();
// Get instance field reference: public System.Net.SimpleAsyncCallback callback
::System::Net::SimpleAsyncCallback*& dyn_callback();
// System.Boolean <RunWithLock>b__0(System.Net.SimpleAsyncResult inner)
// Offset: 0x1B35664
bool $RunWithLock$b__0(::System::Net::SimpleAsyncResult* inner);
// System.Void <RunWithLock>b__1(System.Net.SimpleAsyncResult inner)
// Offset: 0x1B356EC
void $RunWithLock$b__1(::System::Net::SimpleAsyncResult* inner);
// public System.Void .ctor()
// Offset: 0x1B351A4
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static SimpleAsyncResult::$$c__DisplayClass11_0* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<SimpleAsyncResult::$$c__DisplayClass11_0*, creationType>()));
}
}; // System.Net.SimpleAsyncResult/System.Net.<>c__DisplayClass11_0
#pragma pack(pop)
static check_size<sizeof(SimpleAsyncResult::$$c__DisplayClass11_0), 32 + sizeof(::System::Net::SimpleAsyncCallback*)> __System_Net_SimpleAsyncResult_$$c__DisplayClass11_0SizeCheck;
static_assert(sizeof(SimpleAsyncResult::$$c__DisplayClass11_0) == 0x28);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::$RunWithLock$b__0
// Il2CppName: <RunWithLock>b__0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::*)(::System::Net::SimpleAsyncResult*)>(&System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::$RunWithLock$b__0)> {
static const MethodInfo* get() {
static auto* inner = &::il2cpp_utils::GetClassFromName("System.Net", "SimpleAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Net::SimpleAsyncResult::$$c__DisplayClass11_0*), "<RunWithLock>b__0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inner});
}
};
// Writing MetadataGetter for method: System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::$RunWithLock$b__1
// Il2CppName: <RunWithLock>b__1
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::*)(::System::Net::SimpleAsyncResult*)>(&System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::$RunWithLock$b__1)> {
static const MethodInfo* get() {
static auto* inner = &::il2cpp_utils::GetClassFromName("System.Net", "SimpleAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Net::SimpleAsyncResult::$$c__DisplayClass11_0*), "<RunWithLock>b__1", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inner});
}
};
// Writing MetadataGetter for method: System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 52.162393 | 247 | 0.720957 | RedBrumbler |
a3209886efc315f89493c2ee1a487458965182fa | 2,196 | hpp | C++ | geo/po.hpp | ExploreWilder/libgeo | 118ba7f527cbfb5fc6b600495208c1c7d4178414 | [
"BSD-2-Clause"
] | 1 | 2019-11-17T11:47:27.000Z | 2019-11-17T11:47:27.000Z | externals/browser/externals/browser/externals/libgeo/geo/po.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 1 | 2021-01-07T03:37:34.000Z | 2021-01-08T03:33:51.000Z | externals/browser/externals/browser/externals/libgeo/geo/po.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 2 | 2019-09-25T05:22:02.000Z | 2021-02-14T14:10:03.000Z | /**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef geo_po_hpp_included_
#define geo_po_hpp_included_
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include "srsdef.hpp"
namespace geo {
inline void validate(boost::any &v
, const std::vector<std::string> &values
, SrsDefinition*, int)
{
namespace po = boost::program_options;
namespace ba = boost::algorithm;
po::validators::check_first_occurrence(v);
auto srs(SrsDefinition::fromString
(po::validators::get_single_string(values)));
if (srs.empty()) {
throw po::validation_error(po::validation_error::invalid_option_value);
}
// ok
v = boost::any(srs);
}
} // namespace geo
#endif // geo_po_hpp_included_
| 35.419355 | 79 | 0.729964 | ExploreWilder |
a320b15e86086b1e0bb832f591301d234fe314d6 | 523 | cpp | C++ | source/ItemRocket.cpp | fgrehm/pucrs-doom2d | edea7d5d762f427a5a8c944d36819009eb514429 | [
"MIT"
] | 1 | 2016-08-15T16:11:40.000Z | 2016-08-15T16:11:40.000Z | source/ItemRocket.cpp | fgrehm/pucrs-doom2d | edea7d5d762f427a5a8c944d36819009eb514429 | [
"MIT"
] | null | null | null | source/ItemRocket.cpp | fgrehm/pucrs-doom2d | edea7d5d762f427a5a8c944d36819009eb514429 | [
"MIT"
] | null | null | null |
#include "ItemRocket.h"
ItemRocket::ItemRocket(int _x, int _y):
x(_x),
y(_y)
{
sprite = new cgf::Sprite();
sprite->load("data/img/rocket.png");
sprite->scale(1.2, 1.2);
sf::Vector2f vpos = sf::Vector2f();
vpos.x = x;
vpos.y = y;
sprite->setPosition(vpos);
}
ItemRocket::~ItemRocket(){
if (sprite){
delete sprite;
}
}
void ItemRocket::visit(Inventory *iv) {
iv->refillRocketLauncher(1);
}
void ItemRocket::draw(cgf::Game* game){
game->getScreen()->draw(*sprite);
}
| 16.34375 | 40 | 0.602294 | fgrehm |
a321d9f446d98819bfdb96a0c0f06b204ad73d0b | 767 | cpp | C++ | HackerEarth/Number Theory/Basics/expmodulo.cpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | 1 | 2022-03-25T10:20:25.000Z | 2022-03-25T10:20:25.000Z | HackerEarth/Number Theory/Basics/expmodulo.cpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | null | null | null | HackerEarth/Number Theory/Basics/expmodulo.cpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <limits>
#include <string.h>
using namespace std;
typedef long long int ll ;
ll expmodulo(ll a, ll b, ll mod)
{
if(a == 0 || b == 0 || a < 0 || b < 0) return 0;
else if(b == 0) return 1;
else if(b == 1) return a % mod;
else if(b&1) return (a * expmodulo(a * a, b>>1, mod) % mod); // No Overflow.
else {
return expmodulo(a * a, b>>1, mod);
}
}
int main(int argc, char *argv[])
{
if(argc < 3)
{
cout << "Enter the base, power & mod-num : [b,pb,md] " << endl;
return -1;
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int mod = atoi(argv[3]);
cout << "Exponent Modulo is : " << expmodulo(a,b,mod) << endl;
return 0;
} | 25.566667 | 80 | 0.529335 | hendry19901990 |
a324b0a39da5ae987baf61cc4429f2866caecd8e | 9,059 | cpp | C++ | ouzel/graphics/opengl/ShaderOGL.cpp | keima97/ouzel | e6673e678b4739235371a15ae3863942b692c5fb | [
"BSD-2-Clause"
] | null | null | null | ouzel/graphics/opengl/ShaderOGL.cpp | keima97/ouzel | e6673e678b4739235371a15ae3863942b692c5fb | [
"BSD-2-Clause"
] | null | null | null | ouzel/graphics/opengl/ShaderOGL.cpp | keima97/ouzel | e6673e678b4739235371a15ae3863942b692c5fb | [
"BSD-2-Clause"
] | null | null | null | // Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "ShaderOGL.h"
#include "core/Engine.h"
#include "RendererOGL.h"
#include "files/FileSystem.h"
#include "utils/Log.h"
namespace ouzel
{
namespace graphics
{
ShaderOGL::ShaderOGL()
{
}
ShaderOGL::~ShaderOGL()
{
if (programId)
{
RendererOGL::deleteResource(programId, RendererOGL::ResourceType::Program);
}
if (vertexShaderId)
{
RendererOGL::deleteResource(vertexShaderId, RendererOGL::ResourceType::Shader);
}
if (pixelShaderId)
{
RendererOGL::deleteResource(pixelShaderId, RendererOGL::ResourceType::Shader);
}
}
void ShaderOGL::free()
{
Shader::free();
pixelShaderConstantLocations.clear();
vertexShaderConstantLocations.clear();
if (programId)
{
RendererOGL::deleteResource(programId, RendererOGL::ResourceType::Program);
programId = 0;
}
if (vertexShaderId)
{
RendererOGL::deleteResource(vertexShaderId, RendererOGL::ResourceType::Shader);
vertexShaderId = 0;
}
if (pixelShaderId)
{
RendererOGL::deleteResource(pixelShaderId, RendererOGL::ResourceType::Shader);
pixelShaderId = 0;
}
}
void ShaderOGL::printShaderMessage(GLuint shaderId)
{
GLint logLength = 0;
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0)
{
std::vector<char> logMessage(static_cast<size_t>(logLength));
glGetShaderInfoLog(shaderId, logLength, nullptr, logMessage.data());
Log(Log::Level::ERR) << "Shader compilation error: " << logMessage.data();
}
}
void ShaderOGL::printProgramMessage()
{
GLint logLength = 0;
glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0)
{
std::vector<char> logMessage(static_cast<size_t>(logLength));
glGetProgramInfoLog(programId, logLength, nullptr, logMessage.data());
Log(Log::Level::ERR) << "Shader linking error: " << logMessage.data();
}
}
bool ShaderOGL::upload()
{
if (uploadData.dirty)
{
if (!pixelShaderId)
{
pixelShaderId = glCreateShader(GL_FRAGMENT_SHADER);
const GLchar* pixelShaderBuffer = reinterpret_cast<const GLchar*>(uploadData.pixelShaderData.data());
GLint pixelShaderSize = static_cast<GLint>(uploadData.pixelShaderData.size());
glShaderSource(pixelShaderId, 1, &pixelShaderBuffer, &pixelShaderSize);
glCompileShader(pixelShaderId);
GLint status;
glGetShaderiv(pixelShaderId, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
Log(Log::Level::ERR) << "Failed to compile pixel shader";
printShaderMessage(pixelShaderId);
return false;
}
if (RendererOGL::checkOpenGLError())
{
return false;
}
}
if (!vertexShaderId)
{
vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
const GLchar* vertexShaderBuffer = reinterpret_cast<const GLchar*>(uploadData.vertexShaderData.data());
GLint vertexShaderSize = static_cast<GLint>(uploadData.vertexShaderData.size());
glShaderSource(vertexShaderId, 1, &vertexShaderBuffer, &vertexShaderSize);
glCompileShader(vertexShaderId);
GLint status;
glGetShaderiv(vertexShaderId, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
Log(Log::Level::ERR) << "Failed to compile vertex shader";
printShaderMessage(vertexShaderId);
return false;
}
}
if (!programId)
{
programId = glCreateProgram();
glAttachShader(programId, vertexShaderId);
glAttachShader(programId, pixelShaderId);
GLuint index = 0;
if (uploadData.vertexAttributes & VERTEX_POSITION)
{
glBindAttribLocation(programId, index, "in_Position");
++index;
}
if (uploadData.vertexAttributes & VERTEX_COLOR)
{
glBindAttribLocation(programId, index, "in_Color");
++index;
}
if (uploadData.vertexAttributes & VERTEX_NORMAL)
{
glBindAttribLocation(programId, index, "in_Normal");
++index;
}
if (uploadData.vertexAttributes & VERTEX_TEXCOORD0)
{
glBindAttribLocation(programId, index, "in_TexCoord0");
++index;
}
if (uploadData.vertexAttributes & VERTEX_TEXCOORD1)
{
glBindAttribLocation(programId, index, "in_TexCoord1");
++index;
}
glLinkProgram(programId);
GLint status;
glGetProgramiv(programId, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
Log(Log::Level::ERR) << "Failed to link shader";
printProgramMessage();
return false;
}
if (RendererOGL::checkOpenGLError())
{
return false;
}
glDetachShader(programId, vertexShaderId);
glDeleteShader(vertexShaderId);
vertexShaderId = 0;
glDetachShader(programId, pixelShaderId);
glDeleteShader(pixelShaderId);
pixelShaderId = 0;
if (RendererOGL::checkOpenGLError())
{
return false;
}
RendererOGL::useProgram(programId);
GLint texture0Location = glGetUniformLocation(programId, "texture0");
if (texture0Location != -1) glUniform1i(texture0Location, 0);
GLint texture1Location = glGetUniformLocation(programId, "texture1");
if (texture1Location != -1) glUniform1i(texture1Location, 1);
if (RendererOGL::checkOpenGLError())
{
return false;
}
}
pixelShaderConstantLocations.clear();
pixelShaderConstantLocations.reserve(uploadData.pixelShaderConstantInfo.size());
for (const ConstantInfo& info : uploadData.pixelShaderConstantInfo)
{
GLint location = glGetUniformLocation(programId, info.name.c_str());
if (location == -1 || RendererOGL::checkOpenGLError())
{
Log(Log::Level::ERR) << "Failed to get OpenGL uniform location";
return false;
}
pixelShaderConstantLocations.push_back({ location, info.size });
}
vertexShaderConstantLocations.clear();
vertexShaderConstantLocations.reserve(uploadData.vertexShaderConstantInfo.size());
for (const ConstantInfo& info : uploadData.vertexShaderConstantInfo)
{
GLint location = glGetUniformLocation(programId, info.name.c_str());
if (location == -1 || RendererOGL::checkOpenGLError())
{
Log(Log::Level::ERR) << "Failed to get OpenGL uniform location";
return false;
}
vertexShaderConstantLocations.push_back({ location, info.size });
}
uploadData.dirty = false;
}
return true;
}
} // namespace graphics
} // namespace ouzel
| 34.842308 | 123 | 0.48725 | keima97 |
a325a79cfcd6b9e8bf4d890f77532e9828eb62cd | 1,446 | cpp | C++ | src/GL.cpp | neo-bolea/procedurally | 449d583dc09f3779617490b26d4af469b31ec414 | [
"MIT"
] | 4 | 2019-11-19T17:05:44.000Z | 2020-03-30T20:09:53.000Z | src/GL.cpp | neo-bolea/procedurally | 449d583dc09f3779617490b26d4af469b31ec414 | [
"MIT"
] | 5 | 2019-12-07T18:07:30.000Z | 2020-03-23T10:47:41.000Z | src/GL.cpp | neo-bolea/procedurally | 449d583dc09f3779617490b26d4af469b31ec414 | [
"MIT"
] | null | null | null | #include "Graphics/GL.h"
#include "Common/Debug.h"
#include "Graphics/MathGL.h"
#include "Graphics/Shader.h"
#include <GL/glew.h>
#define NOMINMAX
#include <fstream>
#include <Shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
namespace GL
{
void GLAPIENTRY
ErrorCallback( GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam )
{
if(type != GL_DEBUG_TYPE_ERROR) { return; }
Debug::Log(std::string("OpenGL: ")
+ "Type = " + std::to_string(type)
+ ", Severity = " + std::to_string(severity)
+ ", " + (char *)message, Debug::Error, { "Graphics" });
}
#undef StaticGLGetInteger
#define StaticGLGetInteger(name, handle) \
int name() \
{ \
static int name = -1; \
if(name == -1) \
{ glGetIntegerv(handle, &name); } \
return name; \
}
StaticGLGetInteger(TextureMaxSize, GL_MAX_TEXTURE_SIZE)
StaticGLGetInteger(Texture3DMaxSize, GL_MAX_3D_TEXTURE_SIZE)
}
namespace GLHelper
{
uint CreateUBO(uint bindingPoint, uint size, GL::DrawType drawType)
{
uint ubo;
glGenBuffers(1, &ubo);
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
glBufferData(GL_UNIFORM_BUFFER, size, NULL, (int)drawType);
glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, ubo);
return ubo;
}
void BindUBOData(uint offset, uint size, void *data)
{ glBufferSubData(GL_UNIFORM_BUFFER, offset, size, data); }
} | 22.59375 | 68 | 0.670816 | neo-bolea |
a32846cdfeefc5f63c158d789962d8646e0f2b3f | 5,461 | cpp | C++ | 2course/Programming/examples/2018_2019/lecture_9_10_1903_01to15_1st.cpp | posgen/OmsuMaterials | 6132fe300154db97327667728c4cf3b0e19420e6 | [
"Unlicense"
] | 9 | 2017-04-03T08:52:58.000Z | 2020-06-05T18:25:02.000Z | 2course/Programming/examples/2018_2019/lecture_9_10_1903_01to15_1st.cpp | posgen/OmsuMaterials | 6132fe300154db97327667728c4cf3b0e19420e6 | [
"Unlicense"
] | 6 | 2018-02-07T18:26:27.000Z | 2021-09-02T04:46:06.000Z | 2course/Programming/examples/2018_2019/lecture_9_10_1903_01to15_1st.cpp | posgen/OmsuMaterials | 6132fe300154db97327667728c4cf3b0e19420e6 | [
"Unlicense"
] | 10 | 2018-11-12T18:18:47.000Z | 2020-06-06T06:17:01.000Z | #include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <algorithm>
#include <random>
#include <ctime>
using namespace std;
double rand_a_b(double a, double b)
{
static mt19937_64 gnr{ time(nullptr) };
static const size_t max_gnr = gnr.max();
return a + (b - a) * ( double(gnr()) / max_gnr );
}
/**
Задумка для собственного типа данных: релализовать динамический массив
действительных чисел с возможностью положительных и отрицательных индексов.
Пример массива: [ 10.5, 5.6, -9.3, 11.1, 0.567 ]
'+' индексы: 0 1 2 3 4
'-' индексы: -5 -4 -3 -2 -1
Условия на создаваемый тип:
- создание массива заданной размерности;
- создание массива заданной размерности и заполнение каждого элемента
конкретным значением;
- нет проверки выхода индекса массива за его границы;
*/
class DynArray1D
{
public:
/**
Конструктор с одним параметром:
создаёт динамический массив на число элементов,
заданных значением параметра *array_size*.
*/
DynArray1D(size_t array_size);
/**
Конструктор с двумя параметрами:
создаёт динамический массив на число элементов,
заданных значением параметра *array_size* и
каждому элементу присваивает значение *value*.
*/
DynArray1D(size_t array_size, double value);
/**
Конструктор копий:
создаёт копию другого динамического массива типа DynArray1D.
Нужен для предотвращения копирования по умолчанию, когда в разные
переменные-объекты данного типа попадают адреса одного и того же
блока динамической памяти.
*/
DynArray1D(const DynArray1D& other);
/**
Деструктор:
автоматически удаляет динамическую память, когда перемнная
данного класса выходит из области видимости.
*/
~DynArray1D();
/// Методы класса
/// Узнать длину конкретного объекта данного типа
size_t length() const;
/// Узнать ёмкость конкретного объекта данного типа
size_t capacity() const;
/// Перегруженные операторы
/**
Оператор "квадратные скобки" используется для обращения к элементам
массива по положительному или отрицательному индексу.
Возращает ссылку на конкретный элемент.
*/
double& operator[](int index);
/**
Оператор "<<" перегружен для добавления элементов в конкретный массив.
*/
DynArray1D& operator<<(double value);
/// Оператор присваивания - перегружен для правильно копирования одного объекта массива в другой.
void operator=(const DynArray1D& other);
private:
/**
Поля класса DynArray1D.
- _arr - указатель, использующийся для хранения элементов массива;
- _length - текущая длина массива;
- _capacity - текущая ёмкость массива, т.е. количество элементов
типа double, которые уже выделены в виде динамической памяти.
Для каждого из полей указаны значения по умолчанию.
*/
double *_arr = nullptr;
size_t _length = 0;
size_t _capacity = 0;
};
int main()
{
DynArray1D vec{10, 4.5};
cout << vec.length() << endl;
vec[-4] = 15.0;
vec << 3.7 << 6.8 << 9.88 << 33.33323;
for (size_t i = 0; i < vec.length(); i++) {
cout << vec[i] << ' ';
}
cout << endl;
DynArray1D another_array{2};
another_array = vec;
for (size_t i = 0; i < another_array.length(); i++) {
cout << another_array[i] << ' ';
}
cout << endl;
}
/// Определение конструкторов и деструктора:
DynArray1D::DynArray1D(size_t array_size)
{
_arr = new double[array_size];
_length = _capacity = array_size;
}
DynArray1D::DynArray1D(size_t array_size, double value)
{
_arr = new double[array_size];
_length = _capacity = array_size;
for (size_t i = 0; i < _length; i++) {
_arr[i] = value;
}
}
DynArray1D::DynArray1D(const DynArray1D& other)
{
cout << "Copy ctor" << endl;
_length = other._length;
_capacity = other._capacity;
_arr = new double[_capacity];
for (size_t i = 0; i < _length; i++)
{
_arr[i] = other._arr[i];
}
}
~DynArray1D()
{
delete[] _arr;
}
/// Определение методов-класса:
size_t DynArray1D::length() const
{
return _length;
}
size_t DynArray1D::capacity() const
{
return _capacity;
}
double& DynArray1D::operator[](int index)
{
if (index >= 0) {
return _arr[index];
}
return _arr[_length + index];
}
DynArray1D& DynArray1D::operator<<(double value)
{
if (_capacity == 0) {
_capacity = 8;
_arr = new double[_capacity];
_arr[0] = value;
_length++;
return *this;
}
if (_capacity == _length) {
double *ptr = new double[2 * _capacity];
_capacity *= 2;
for (size_t i = 0; i < _length; i++) {
ptr[i] = _arr[i];
}
ptr[_length] = value;
_length++;
delete[] _arr;
_arr = ptr;
return *this;
}
_arr[_length] = value;
_length++;
return *this;
}
void DynArray1D::operator=(const DynArray1D& other)
{
cout << "Operator= called" << endl;
delete[] _arr;
_length = other._length;
_capacity = other._capacity;
_arr = new double[_capacity];
for (size_t i = 0; i < _length; i++)
{
_arr[i] = other._arr[i];
}
}
| 23.640693 | 101 | 0.609412 | posgen |
cd165cb5ba7a1c9856c9d5e9fe5a555d9f5cf20b | 14,800 | cpp | C++ | Client/userlist.cpp | alice-create/O-Chat | fea0ebe0f19cfeaca068468b87684e2421ad5700 | [
"Apache-2.0"
] | null | null | null | Client/userlist.cpp | alice-create/O-Chat | fea0ebe0f19cfeaca068468b87684e2421ad5700 | [
"Apache-2.0"
] | null | null | null | Client/userlist.cpp | alice-create/O-Chat | fea0ebe0f19cfeaca068468b87684e2421ad5700 | [
"Apache-2.0"
] | null | null | null | #include "userlist.h"
#include "ui_userlist.h"
#include "info.h"
#include "addfriend.h"
userlist::userlist(QWidget *parent) :
QWidget(parent),
ui(new Ui::userlist)
{
ui->setupUi(this);
// sock = new QTcpSocket(this);
// lists = ui -> listWidget;
// person = new user();
// QListWidgetItem *itemN = new QListWidgetItem();
// lists -> addItem(itemN);
// lists -> setItemWidget(itemN, person);
// QString IP = "192.168.43.143";
// quint16 port = 1023;
// sock->connectToHost(IP, port);
// connect(sock, SIGNAL(connected()), this, SLOT(slot_connected()));
}
userlist::userlist(QTcpSocket *socket,QString id, QString name, quint16 People, QStringList IDList, QStringList NameList, QStringList onList, QWidget *parent) :
QWidget(parent),
ui(new Ui::userlist)
{
ui->setupUi(this);
// this->setWindowFlags(Qt::FramelessWindowHint);
sock = socket;
lists = ui -> listWidget; //框架
/*生成个人信息*/
off = ui -> pushButton_2;
myname = ui -> label;
myID = ui -> label_2;
off -> setText("Off-Line");
mID = id;
mName = name;
myID -> setText("ID:" + mID);
myname -> setText(mName);
/*好友列表*/
people = People;
IDlist = IDList;
Namelist = NameList;
onlist = onList;
initList();
/*重要:设置QListWidget的contextMenuPolicy属性,不然不能显示右键菜单*/
ui -> widget -> setProperty("contextMenuPolicy", Qt::CustomContextMenu);
/*初始化一个包含rename的菜单*/
menu = new QMenu(this);
rename = new QAction(tr("Config Username"), this);
menu -> addAction(rename);
/*绑定右键显示菜单:在单击右键之后会执行槽函数, 槽函数中负责弹出右键菜单*/
connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(on_widget_customContextMenuRequested(const QPoint &pos)));
/*为菜单上的Delete选项添加响应函数*/
connect(this -> rename, SIGNAL(triggered()), this, SLOT(slot_changename()));
connect(sock, SIGNAL(readyRead()), this, SLOT(slot_recvmessage()));
}
userlist::~userlist()
{
delete ui;
}
void userlist::on_pushButton_clicked()
{
QString b_id = ui -> lineEdit -> text();
QString id = mID;
QString sendData = "#04|" + id + "|" + b_id;
qDebug() << sendData;
sock -> write(sendData.toUtf8());
}
void userlist::slot_recvmessage() {
QByteArray recvArray = sock -> readAll();
qDebug() << recvArray;
QString recvStr(recvArray);
qDebug() << recvStr;
QStringList recvList = recvStr.split("|");
if(recvList[0] == "#04") {//发送好友邀请
// qDebug() << recvStr;
if(recvList[1] == "0") {
info *information = new info(sock, "04", "0", "0");
information -> show();
}
else
{
if(recvList[2] == "0") {
info *information = new info(sock, "04", "1", "0");
information -> show();
}
if(recvList[2] == "1") {
info *information = new info(sock, "04", "1", "1");
information -> show();
}
if(recvList[2] == "2") {
info *information = new info(sock, "04", "1", "2");
information -> show();
}
}
}
if(recvList[0] == "###05") {//展示邀请
QStringList noList = recvList[0].split("###");
QString no = noList[1];
QString id = recvList[1];
QString b_id = recvList[2];
info *infomation = new info(sock, no, id, b_id);
infomation -> show();
}
if(recvList[0] == "###04")
{
QStringList noList = recvList[0].split("###");
QString no = noList[1];
QString id = recvList[1];
QString b_id = recvList[2];
addFriend *infomation = new addFriend(sock, no, id, b_id);
infomation -> show();
}
if(recvList[0] == "###07")//同意
{
qDebug() << "###07";
QStringList noList = recvList[0].split("###");
QString no = noList[1];
QString id = recvList[1];
QString b_id = recvList[2];
QString Name = recvList[3];
QString status = recvList[4];
people += 1;
IDlist.append(b_id);
Namelist.append(Name);
onlist.append(status);
person = new user(sock, mID, Name, b_id, status, false);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> addItem(itemN);
lists -> setItemWidget(itemN, person);
// info *infomation = new info(sock, no, id, b_id);
// infomation -> show();
}
if(recvList[0] == "###00")
//chatting
{
quint16 row = 0;
quint16 i = 0;
QString b_id = recvList[2];
QString is_chat = recvList[3];
QString s;
QString n;
if(is_chat == "0") {
for(i = 0; i < people; i++) {
if(IDlist[i] == b_id) {
row = i;
s = onlist[i];
n = Namelist[i];
if(s == "0") {
onlist.removeAt(row);
Namelist.removeAt(row);
IDlist.removeAt(row);
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
onlist.append(s);
Namelist.append(n);
IDlist.append(b_id);
person = new user(sock, mID, n, b_id, s, true);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> addItem(itemN);
lists -> setItemWidget(itemN, person);
break;
}
else {
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
person = new user(sock, mID, n, b_id, s, true);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> insertItem(row, itemN);
lists -> setItemWidget(itemN, person);
break;
}
}
}
}
else {
//传消息
chatwindow -> MainChatWin::send_tochat(recvStr);
}
}
if(recvList[0] == "#07") {//点开聊天框
if(recvList[1] == "1") {
info *information = new info(sock, "07", "1", "0");
information -> show();
} else {
quint16 i;
QString uID = recvList[2];
QString uName = recvList[3];
QString s;
for(i = 0; i < people; i++) {
if(IDlist[i] == uID) {
s = onlist[i];
break;
}
}
chatwindow = new MainChatWin(sock, mID, mName, uID, uName, s);
chatwindow -> show();
}
}
if(recvList[0] == "###03") {//好友申请
QString b_id = recvList[2];
QString have_info = recvList[3];
bool flag = false;
if(have_info == "0") flag = false;
else flag = true;
info *information = new info(sock, "###03", "0", b_id);
information -> show();
QString s = "0";
QString n;
quint16 row = 0;
quint16 i = 0;
for(i = 0; i < people; i++) {
if(IDlist[i] == b_id) {
row = i;
n = Namelist[i];
if(s == "0") {
onlist.removeAt(row);
Namelist.removeAt(row);
IDlist.removeAt(row);
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
onlist.append("0");
Namelist.append(n);
IDlist.append(b_id);
person = new user(sock, mID, n, b_id, s, flag);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> addItem(itemN);
lists -> setItemWidget(itemN, person);
break;
}
}
}
}
if(recvList[0] == "###02") {//下线
qDebug() << "###02";
QString b_id = recvList[2];
QString have_info = recvList[3];
bool flag = false;
if(have_info == "0") flag = false;
else flag = true;
info *information = new info(sock, "###02", "0", b_id);
information -> show();
QString s = "1";
QString n;
quint16 row = 0;
quint16 i = 0;
for(i = 0; i < people; i++) {
qDebug() << "i:" << i;
if(IDlist[i] == b_id) {
row = i;
n = Namelist[i];
if(s == "1") {
onlist[i] = "1";
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
person = new user(sock, mID, n, b_id, s, flag);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> insertItem(row, itemN);
lists -> setItemWidget(itemN, person);
break;
}
}
}
}
if(recvList[0] == "#14") {//删除好友
QString if_success = recvList[1];
QString b_id = recvList[2];
if(if_success == "0") {
info *information = new info(sock, "#14", "0", "0");
information -> show();
QString n;
quint16 row = 0;
quint16 i = 0;
for(i = 0; i < people; i++) {
if(IDlist[i] == b_id) {
row = i;
n = Namelist[i];
onlist.removeAt(row);
Namelist.removeAt(row);
IDlist.removeAt(row);
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
people -= 1;
break;
}
}
}
else {
info * information = new info(sock, "#14", "1", "0");
information -> show();
}
}
if(recvList[0] == "#11") {//修改备注
QString is_success = recvList[1];
QString id = recvList[2];
QString nickname = recvList[3];
QString s;
QString is_info = recvList[4];
bool flag = false;
if(is_info == "0") flag = false;
else flag = true;
if(is_success == "0") {
info *information = new info(sock, "11", "0", "0");
information -> show();
for(quint16 i = 0; i < people; i++) {
if(IDlist[i] == id) {
Namelist[i] = nickname;
s = onlist[i];
QListWidgetItem* item = lists -> takeItem(i);
lists -> removeItemWidget(item);
person = new user(sock, mID, nickname, id, s, flag);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> insertItem(i, itemN);
lists -> setItemWidget(itemN, person);
break;
}
}
} else {
info *information = new info(sock, "11", "1", "0");
information -> show();
}
}
if(recvList[0] == "#12") {//修改昵称
QString is_success = recvList[1];
if(is_success == "0") {
info *information = new info(sock, "12", "0", "0");
information -> show();
QString newname = recvList[4];
myname -> setText(newname);
} else {
QString errortype = recvList[2];
if(errortype == "0") {
info *information = new info(sock, "12", "1", "0");
information -> show();
}
if(errortype == "1") {
info *information = new info(sock, "12", "1", "1");
information -> show();
}
if(errortype == "2") {
info *information = new info(sock, "12", "1", "2");
information -> show();
}
}
}
if(recvList[0] == "###06") {
QString uid = recvList[2];
QString n;
quint16 row = 0;
quint16 i = 0;
for(i = 0; i < people; i++) {
if(IDlist[i] == uid) {
row = i;
n = Namelist[i];
onlist.removeAt(row);
Namelist.removeAt(row);
IDlist.removeAt(row);
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
people -= 1;
break;
}
}
}
if(recvList[0] == "#16") {//历史消息
chatwindow -> send_tochat(recvStr);
}
}
void userlist::initList() {
quint16 i;
for(i = 0; i < people; i++) {
QString Name = Namelist[i];
QString ID = IDlist[i];
QString status =onlist[i];
person = new user(sock, mID, Name, ID, status, false);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> addItem(itemN);
lists -> setItemWidget(itemN, person);
}
}
void userlist::on_pushButton_2_clicked()
{
QString sendData = "#03|" + mID;
sock->write(sendData.toUtf8());
this -> close();
}
//修改名字
void userlist::slot_changename() {
configname *info = new configname(sock, mID, mName);
info -> show();
// QString nickname = info -> nickname;
// ui -> label -> setText(nickname);
}
void userlist::mousePressEvent(QMouseEvent *evt) {
mousePos = QPoint(evt -> x(), evt -> y());
}
void userlist::mouseReleaseEvent(QMouseEvent *evt) {
if(mousePos == QPoint(evt->x(), evt->y()) & evt -> button() & Qt::LeftButton)
{
emit clicked();
}
}
void userlist::on_widget_customContextMenuRequested(const QPoint &pos)
{
menu -> exec(QCursor::pos());
}
| 33.408578 | 160 | 0.45223 | alice-create |
cd1781c14ed9473225ed64a08227af44da19bd24 | 449 | hpp | C++ | lib/libCFG/include/CapstoneHelper.hpp | cyber-itl/citl-static-analysis | 32ef8e519dac1c6a49ff41d902a62df8f5a8e948 | [
"MIT"
] | 14 | 2021-05-03T16:03:22.000Z | 2022-02-14T23:42:39.000Z | lib/libCFG/include/CapstoneHelper.hpp | cyber-itl/citl-static-analysis | 32ef8e519dac1c6a49ff41d902a62df8f5a8e948 | [
"MIT"
] | 1 | 2021-09-27T12:01:33.000Z | 2021-09-27T12:01:33.000Z | lib/libCFG/include/CapstoneHelper.hpp | cyber-itl/citl-static-analysis | 32ef8e519dac1c6a49ff41d902a62df8f5a8e948 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <tuple>
#include <vector>
#include "capstone/capstone.h"
std::tuple<cs_arch, cs_mode> map_triple_cs(uint32_t triple);
std::vector<uint64_t> get_imm_vals(const cs_insn &insn, cs_arch arch, uint32_t base_reg, uint64_t reg_val);
bool is_nop(cs_arch arch, cs_insn *insn);
bool is_pc_in_arm_ops(cs_arm arm_details);
bool is_lr_in_arm_ops(cs_arm arm_details);
unsigned rotr32(unsigned val, unsigned amt);
| 21.380952 | 107 | 0.781737 | cyber-itl |
cd1ba70d97f48201fb4cad0a3bcfb145b041d3cb | 647 | cpp | C++ | SRCS/Sound.cpp | Dreinale/Bomberman_project | ed98d44f54906b1e3f7941b58d8e1493711f355b | [
"MIT"
] | 1 | 2021-07-12T21:59:28.000Z | 2021-07-12T21:59:28.000Z | SRCS/Sound.cpp | Dreinale/Bomberman_project | ed98d44f54906b1e3f7941b58d8e1493711f355b | [
"MIT"
] | null | null | null | SRCS/Sound.cpp | Dreinale/Bomberman_project | ed98d44f54906b1e3f7941b58d8e1493711f355b | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2021
** sound
** File description:
** soudn
*/
#include "Sound.hpp"
Zic::Zic(float *volume, int play_time, std::string path)
{
_play_time = play_time;
music = LoadMusicStream(path.c_str());
_volume = volume;
}
void Zic::play_music()
{
PlayMusicStream(music);
SetMusicVolume(music, *_volume);
}
void Zic::stop()
{
StopMusicStream(music);
}
void Zic::update()
{
UpdateMusicStream(music);
int timePlayed = GetMusicTimePlayed(music)/GetMusicTimeLength(music)*400;
if (_play_time != 0 && timePlayed > _play_time) StopMusicStream(music);
}
Zic::~Zic()
{
UnloadMusicStream(music);
}
| 15.780488 | 77 | 0.669243 | Dreinale |
cd1d14a8b2a9f623c969a7ac83bc5af4c5a425d4 | 732 | cpp | C++ | src/battery.cpp | Fanteria/bar-indicators | cdc19c80a0d6917be9ed2cdabe09e8a5c8e7b624 | [
"MIT"
] | null | null | null | src/battery.cpp | Fanteria/bar-indicators | cdc19c80a0d6917be9ed2cdabe09e8a5c8e7b624 | [
"MIT"
] | null | null | null | src/battery.cpp | Fanteria/bar-indicators | cdc19c80a0d6917be9ed2cdabe09e8a5c8e7b624 | [
"MIT"
] | null | null | null | #include<iostream>
#include<fstream>
#include<string>
std::string batteryStatus[] = {"", "", "", "", ""};
int main (int argc, char ** argv) {
if (argc != 3)
exit(1);
// Load percentage.
std::string line;
std::ifstream f(*(argv + 1));
std::getline(f, line);
f.close();
std::cout << line << " ";
int percentage = std::stoi(line);
// Load charging status.
std::ifstream statusFile(*(argv + 2));
std::getline(statusFile, line);
statusFile.close();
// Charging status icon.
if (line == "Charging")
std::cout << "";
else if (line == "Discharging")
std::cout << "";
std::cout << batteryStatus[percentage / 25] << std::endl;
return 0;
} | 22.181818 | 61 | 0.538251 | Fanteria |
cd1d1bb00f17e4b5cccd14584692d6c8100f57f1 | 13,350 | cpp | C++ | lgc/patch/PatchInitializeWorkgroupMemory.cpp | flygod1159/llpc | 58664d422f062ce29680f7ca40407cdf70944209 | [
"MIT"
] | 1 | 2022-01-13T16:44:16.000Z | 2022-01-13T16:44:16.000Z | lgc/patch/PatchInitializeWorkgroupMemory.cpp | flygod1159/llpc | 58664d422f062ce29680f7ca40407cdf70944209 | [
"MIT"
] | null | null | null | lgc/patch/PatchInitializeWorkgroupMemory.cpp | flygod1159/llpc | 58664d422f062ce29680f7ca40407cdf70944209 | [
"MIT"
] | null | null | null | /*
***********************************************************************************************************************
*
* Copyright (c) 2021-2021 Advanced Micro Devices, Inc. All Rights Reserved.
*
* 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.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file PatchInitializeWorkgroupMemory.cpp
* @brief LLPC source file: contains declaration and implementation of class lgc::PatchInitializeWorkgroupMemory.
***********************************************************************************************************************
*/
#include "lgc/patch/PatchInitializeWorkgroupMemory.h"
#include "lgc/patch/ShaderInputs.h"
#include "lgc/state/PipelineShaders.h"
#include "lgc/state/PipelineState.h"
#include "lgc/util/BuilderBase.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"
#define DEBUG_TYPE "lgc-patch-initialize-workgroup-memory"
using namespace lgc;
using namespace llvm;
static cl::opt<bool>
ForceInitWorkgroupMemory("force-init-workgroup-memory",
cl::desc("Force to initialize the workgroup memory with zero for internal use"),
cl::init(false));
namespace lgc {
// =====================================================================================================================
// Initializes static members.
char LegacyPatchInitializeWorkgroupMemory::ID = 0;
// =====================================================================================================================
// Pass creator, creates the pass of setting up the value for workgroup global variables.
ModulePass *createLegacyPatchInitializeWorkgroupMemory() {
return new LegacyPatchInitializeWorkgroupMemory();
}
// =====================================================================================================================
LegacyPatchInitializeWorkgroupMemory::LegacyPatchInitializeWorkgroupMemory() : ModulePass(ID) {
}
// =====================================================================================================================
// Executes this LLVM patching pass on the specified LLVM module.
//
// @param [in/out] module : LLVM module to be run on
// @returns : True if the module was modified by the transformation and false otherwise
bool LegacyPatchInitializeWorkgroupMemory::runOnModule(Module &module) {
PipelineState *pipelineState = getAnalysis<LegacyPipelineStateWrapper>().getPipelineState(&module);
PipelineShadersResult &pipelineShaders = getAnalysis<LegacyPipelineShaders>().getResult();
return m_impl.runImpl(module, pipelineShaders, pipelineState);
}
// =====================================================================================================================
// Executes this LLVM patching pass on the specified LLVM module.
//
// @param [in/out] module : LLVM module to be run on
// @param [in/out] analysisManager : Analysis manager to use for this transformation
// @returns : The preserved analyses (The analyses that are still valid after this pass)
PreservedAnalyses PatchInitializeWorkgroupMemory::run(Module &module, ModuleAnalysisManager &analysisManager) {
PipelineState *pipelineState = analysisManager.getResult<PipelineStateWrapper>(module).getPipelineState();
PipelineShadersResult &pipelineShaders = analysisManager.getResult<PipelineShaders>(module);
if (runImpl(module, pipelineShaders, pipelineState))
return PreservedAnalyses::none();
return PreservedAnalyses::all();
}
// =====================================================================================================================
// Executes this LLVM patching pass on the specified LLVM module.
//
// @param [in/out] module : LLVM module to be run on
// @param pipelineShaders : Pipeline shaders analysis result
// @param pipelineState : Pipeline state
// @returns : True if the module was modified by the transformation and false otherwise
bool PatchInitializeWorkgroupMemory::runImpl(Module &module, PipelineShadersResult &pipelineShaders,
PipelineState *pipelineState) {
LLVM_DEBUG(dbgs() << "Run the pass Patch-Initialize-Workgroup-Memory\n");
m_pipelineState = pipelineState;
// This pass works on compute shader.
if (!m_pipelineState->hasShaderStage(ShaderStageCompute))
return false;
SmallVector<GlobalVariable *> workgroupGlobals;
for (GlobalVariable &global : module.globals()) {
// The pass process the cases that the workgroup memory is forced to be initialized or the workgroup variable has an
// zero initializer
if (global.getType()->getPointerAddressSpace() == ADDR_SPACE_LOCAL &&
(ForceInitWorkgroupMemory || (global.hasInitializer() && global.getInitializer()->isNullValue())))
workgroupGlobals.push_back(&global);
}
if (workgroupGlobals.empty())
return false;
Patch::init(&module);
m_shaderStage = ShaderStageCompute;
m_entryPoint = pipelineShaders.getEntryPoint(static_cast<ShaderStage>(m_shaderStage));
BuilderBase builder(*m_context);
Instruction *insertPos = &*m_entryPoint->front().getFirstInsertionPt();
builder.SetInsertPoint(insertPos);
// Fill the map of each variable with zeroinitializer and calculate its corresponding offset on LDS
unsigned offset = 0;
for (auto global : workgroupGlobals) {
unsigned varSize = getTypeSizeInDwords(global->getType()->getPointerElementType());
m_globalLdsOffsetMap.insert({global, builder.getInt32(offset)});
offset += varSize;
}
// The new LDS is an i32 array
const unsigned ldsSize = offset;
auto ldsTy = ArrayType::get(builder.getInt32Ty(), ldsSize);
auto lds = new GlobalVariable(module, ldsTy, false, GlobalValue::ExternalLinkage, nullptr, "lds", nullptr,
GlobalValue::NotThreadLocal, ADDR_SPACE_LOCAL);
lds->setAlignment(MaybeAlign(16));
// Replace the original LDS variables with the new LDS variable
for (auto globalOffsetPair : m_globalLdsOffsetMap) {
GlobalVariable *global = globalOffsetPair.first;
Value *offset = globalOffsetPair.second;
Value *pointer = builder.CreateGEP(lds->getType()->getPointerElementType(), lds, {builder.getInt32(0), offset});
pointer = builder.CreateBitCast(pointer, global->getType());
global->replaceAllUsesWith(pointer);
global->eraseFromParent();
}
initializeWithZero(lds, builder);
return true;
}
// =====================================================================================================================
// Initialize the given LDS variable with zero.
//
// @param lds : The LDS variable to be initialized
// @param builder : BuilderBase to use for instruction constructing
void PatchInitializeWorkgroupMemory::initializeWithZero(GlobalVariable *lds, BuilderBase &builder) {
auto entryInsertPos = &*m_entryPoint->front().getFirstInsertionPt();
auto originBlock = entryInsertPos->getParent();
auto endInitBlock = originBlock->splitBasicBlock(entryInsertPos);
endInitBlock->setName(".endInit");
auto initBlock = BasicBlock::Create(*m_context, ".init", originBlock->getParent(), endInitBlock);
auto bodyBlock = BasicBlock::Create(*m_context, ".body", originBlock->getParent(), initBlock);
auto forHeaderBlock = BasicBlock::Create(*m_context, ".for.header", originBlock->getParent(), bodyBlock);
builder.SetInsertPoint(originBlock->getTerminator());
// Get thread info
auto &shaderMode = m_pipelineState->getShaderModes()->getComputeShaderMode();
const auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(m_shaderStage)->entryArgIdxs;
Value *localInvocationId = getFunctionArgument(m_entryPoint, entryArgIdxs.cs.localInvocationId);
const unsigned actualNumThreads = shaderMode.workgroupSizeX * shaderMode.workgroupSizeY * shaderMode.workgroupSizeZ;
Value *threadId = builder.CreateExtractElement(localInvocationId, uint64_t(0));
if (shaderMode.workgroupSizeY > 1) {
Value *stride = builder.CreateMul(builder.getInt32(shaderMode.workgroupSizeX),
builder.CreateExtractElement(localInvocationId, 1));
threadId = builder.CreateAdd(threadId, stride);
}
if (shaderMode.workgroupSizeZ > 1) {
Value *stride = builder.CreateMul(builder.getInt32(shaderMode.workgroupSizeX * shaderMode.workgroupSizeY),
builder.CreateExtractElement(localInvocationId, 2));
threadId = builder.CreateAdd(threadId, stride);
}
originBlock->getTerminator()->replaceUsesOfWith(endInitBlock, forHeaderBlock);
// Each thread stores a zero to the continues LDS
// for (int loopIdx = 0; loopIdx < loopCount; ++loopIdx) {
// if (threadId * loopCount + loopIdx < requiredNumThreads) {
// unsigned ldsOffset = (threadId * loopCount) + loopIdx;
// CreateStore(zero, ldsOffset);
// }
// }
PHINode *loopIdxPhi = nullptr;
const unsigned requiredNumThreads = lds->getType()->getPointerElementType()->getArrayNumElements();
Value *loopCount = builder.getInt32((requiredNumThreads + actualNumThreads - 1) / actualNumThreads);
// Construct ".for.Header" block
{
builder.SetInsertPoint(forHeaderBlock);
loopIdxPhi = builder.CreatePHI(builder.getInt32Ty(), 2);
loopIdxPhi->addIncoming(builder.getInt32(0), originBlock);
Value *isInLoop = builder.CreateICmpULT(loopIdxPhi, loopCount);
builder.CreateCondBr(isInLoop, bodyBlock, endInitBlock);
}
// Construct ".body" block
{
builder.SetInsertPoint(bodyBlock);
// The active thread is : threadId x loopCount + loopIdx < requiredNumThreads
Value *index = builder.CreateMul(threadId, loopCount);
index = builder.CreateAdd(index, loopIdxPhi);
Value *isActiveThread = builder.CreateICmpULT(index, builder.getInt32(requiredNumThreads));
builder.CreateCondBr(isActiveThread, initBlock, endInitBlock);
// Construct ".init" block
{
builder.SetInsertPoint(initBlock);
// ldsOffset = (threadId * loopCount) + loopIdx
Value *ldsOffset = builder.CreateMul(threadId, loopCount);
ldsOffset = builder.CreateAdd(ldsOffset, loopIdxPhi);
Value *writePtr =
builder.CreateGEP(lds->getType()->getPointerElementType(), lds, {builder.getInt32(0), ldsOffset});
builder.CreateAlignedStore(builder.getInt32(0), writePtr, Align(4));
// Update loop index
Value *loopNext = builder.CreateAdd(loopIdxPhi, builder.getInt32(1));
loopIdxPhi->addIncoming(loopNext, initBlock);
builder.CreateBr(forHeaderBlock);
}
}
{
// Set barrier after writing LDS
builder.SetInsertPoint(&*endInitBlock->getFirstInsertionPt());
builder.CreateIntrinsic(Intrinsic::amdgcn_s_barrier, {}, {});
}
}
// =====================================================================================================================
// Return the size in dwords of a variable type
//
// @param inputTy : The type to be calculated
unsigned PatchInitializeWorkgroupMemory::getTypeSizeInDwords(Type *inputTy) {
if (inputTy->isSingleValueType()) {
// Variable in LDS is stored in dwords and padded as 4 dwords
unsigned dwordCount = 4;
unsigned elemCount = inputTy->isVectorTy() ? cast<FixedVectorType>(inputTy)->getNumElements() : 1;
if (inputTy->getScalarSizeInBits() == 64 && elemCount > 1)
dwordCount = 8;
return dwordCount;
}
if (inputTy->isArrayTy()) {
const unsigned elemSize = getTypeSizeInDwords(inputTy->getContainedType(0));
return inputTy->getArrayNumElements() * elemSize;
} else {
assert(inputTy->isStructTy());
const unsigned memberCount = inputTy->getStructNumElements();
unsigned memberSize = 0;
for (unsigned idx = 0; idx < memberCount; ++idx)
memberSize += getTypeSizeInDwords(inputTy->getStructElementType(idx));
return memberSize;
}
}
} // namespace lgc
// =====================================================================================================================
// Initializes the pass of initialize workgroup memory with zero.
INITIALIZE_PASS(LegacyPatchInitializeWorkgroupMemory, DEBUG_TYPE, "Patch for initialize workgroup memory", false, false)
| 48.021583 | 120 | 0.65161 | flygod1159 |
cd1dd4cfa212c487e4f213d8ac9c0eb63a3ef0e9 | 1,593 | cpp | C++ | 01_sensor/06_grey_MPU9250/src/main.cpp | satoruosawa/samples-for-m5stack | ccc003bda296f769c8e20bfed757bed0d6419ce7 | [
"MIT"
] | null | null | null | 01_sensor/06_grey_MPU9250/src/main.cpp | satoruosawa/samples-for-m5stack | ccc003bda296f769c8e20bfed757bed0d6419ce7 | [
"MIT"
] | null | null | null | 01_sensor/06_grey_MPU9250/src/main.cpp | satoruosawa/samples-for-m5stack | ccc003bda296f769c8e20bfed757bed0d6419ce7 | [
"MIT"
] | null | null | null | // define must ahead #include <M5Stack.h>
// #define M5STACK_MPU6886
#define M5STACK_MPU9250
// #define M5STACK_MPU6050
// #define M5STACK_200Q
#include <M5Stack.h>
float accX = 0.0F;
float accY = 0.0F;
float accZ = 0.0F;
float gyroX = 0.0F;
float gyroY = 0.0F;
float gyroZ = 0.0F;
float pitch = 0.0F;
float roll = 0.0F;
float yaw = 0.0F;
float temp = 0.0F;
// the setup routine runs once when M5Stack starts up
void setup() {
// Initialize the M5Stack object
M5.begin();
/*
Power chip connected to gpio21, gpio22, I2C device
Set battery charging voltage and current
If used battery, please call this function in your project
*/
M5.Power.begin();
M5.IMU.Init();
M5.Lcd.fillScreen(BLACK);
M5.Lcd.setTextColor(GREEN, BLACK);
M5.Lcd.setTextSize(2);
}
// the loop routine runs over and over again forever
void loop() {
// put your main code here, to run repeatedly:
M5.IMU.getGyroData(&gyroX, &gyroY, &gyroZ);
M5.IMU.getAccelData(&accX, &accY, &accZ);
M5.IMU.getAhrsData(&pitch, &roll, &yaw);
M5.IMU.getTempData(&temp);
M5.Lcd.setCursor(0, 20);
M5.Lcd.printf("%6.2f %6.2f %6.2f ", gyroX, gyroY, gyroZ);
M5.Lcd.setCursor(220, 42);
M5.Lcd.print(" o/s");
M5.Lcd.setCursor(0, 65);
M5.Lcd.printf(" %5.2f %5.2f %5.2f ", accX, accY, accZ);
M5.Lcd.setCursor(220, 87);
M5.Lcd.print(" G");
M5.Lcd.setCursor(0, 110);
M5.Lcd.printf(" %5.2f %5.2f %5.2f ", pitch, roll, yaw);
M5.Lcd.setCursor(220, 132);
M5.Lcd.print(" degree");
M5.Lcd.setCursor(0, 155);
M5.Lcd.printf("Temperature : %.2f C", temp);
delay(1);
} | 24.507692 | 66 | 0.64909 | satoruosawa |
cd1fbb632f3b5d2c4c1cfc7fda4abefe73307c2b | 3,813 | cpp | C++ | 3rdparty/spirv-tools/source/opt/strip_nonsemantic_info_pass.cpp | amrezzd/bgfx | 560669f6c0e19daf8f29e1f085599f0765e4ee35 | [
"BSD-2-Clause"
] | 188 | 2021-08-11T07:42:41.000Z | 2022-03-31T09:58:09.000Z | 3rdparty/spirv-tools/source/opt/strip_nonsemantic_info_pass.cpp | amrezzd/bgfx | 560669f6c0e19daf8f29e1f085599f0765e4ee35 | [
"BSD-2-Clause"
] | 2 | 2021-09-25T16:51:34.000Z | 2021-11-21T15:59:11.000Z | 3rdparty/spirv-tools/source/opt/strip_nonsemantic_info_pass.cpp | amrezzd/bgfx | 560669f6c0e19daf8f29e1f085599f0765e4ee35 | [
"BSD-2-Clause"
] | 16 | 2021-09-02T08:37:25.000Z | 2022-03-30T16:53:26.000Z | // Copyright (c) 2018 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 "source/opt/strip_nonsemantic_info_pass.h"
#include <cstring>
#include <vector>
#include "source/opt/instruction.h"
#include "source/opt/ir_context.h"
#include "source/util/string_utils.h"
namespace spvtools {
namespace opt {
Pass::Status StripNonSemanticInfoPass::Process() {
bool modified = false;
std::vector<Instruction*> to_remove;
bool other_uses_for_decorate_string = false;
for (auto& inst : context()->module()->annotations()) {
switch (inst.opcode()) {
case SpvOpDecorateStringGOOGLE:
if (inst.GetSingleWordInOperand(1) == SpvDecorationHlslSemanticGOOGLE ||
inst.GetSingleWordInOperand(1) == SpvDecorationUserTypeGOOGLE) {
to_remove.push_back(&inst);
} else {
other_uses_for_decorate_string = true;
}
break;
case SpvOpMemberDecorateStringGOOGLE:
if (inst.GetSingleWordInOperand(2) == SpvDecorationHlslSemanticGOOGLE ||
inst.GetSingleWordInOperand(2) == SpvDecorationUserTypeGOOGLE) {
to_remove.push_back(&inst);
} else {
other_uses_for_decorate_string = true;
}
break;
case SpvOpDecorateId:
if (inst.GetSingleWordInOperand(1) ==
SpvDecorationHlslCounterBufferGOOGLE) {
to_remove.push_back(&inst);
}
break;
default:
break;
}
}
for (auto& inst : context()->module()->extensions()) {
const std::string ext_name = inst.GetInOperand(0).AsString();
if (ext_name == "SPV_GOOGLE_hlsl_functionality1") {
to_remove.push_back(&inst);
} else if (ext_name == "SPV_GOOGLE_user_type") {
to_remove.push_back(&inst);
} else if (!other_uses_for_decorate_string &&
ext_name == "SPV_GOOGLE_decorate_string") {
to_remove.push_back(&inst);
} else if (ext_name == "SPV_KHR_non_semantic_info") {
to_remove.push_back(&inst);
}
}
// remove any extended inst imports that are non semantic
std::unordered_set<uint32_t> non_semantic_sets;
for (auto& inst : context()->module()->ext_inst_imports()) {
assert(inst.opcode() == SpvOpExtInstImport &&
"Expecting an import of an extension's instruction set.");
const std::string extension_name = inst.GetInOperand(0).AsString();
if (spvtools::utils::starts_with(extension_name, "NonSemantic.")) {
non_semantic_sets.insert(inst.result_id());
to_remove.push_back(&inst);
}
}
// if we removed some non-semantic sets, then iterate over the instructions in
// the module to remove any OpExtInst that referenced those sets
if (!non_semantic_sets.empty()) {
context()->module()->ForEachInst(
[&non_semantic_sets, &to_remove](Instruction* inst) {
if (inst->opcode() == SpvOpExtInst) {
if (non_semantic_sets.find(inst->GetSingleWordInOperand(0)) !=
non_semantic_sets.end()) {
to_remove.push_back(inst);
}
}
},
true);
}
for (auto* inst : to_remove) {
modified = true;
context()->KillInst(inst);
}
return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
}
} // namespace opt
} // namespace spvtools
| 32.87069 | 80 | 0.664044 | amrezzd |
cd1ffc92ab570432a5a298c529e1c74373753446 | 874 | cpp | C++ | PhantomEngine/PhantomAction.cpp | DexianZhao/PhantomGameEngine | cf8e341d21e3973856d9f23ad0b1af9db831bac7 | [
"MIT"
] | 4 | 2019-11-08T00:15:13.000Z | 2021-03-26T13:34:50.000Z | src/PhantomEngine/PhantomAction.cpp | DexianZhao/PhantomEngineV2 | cc3bf02ca1d442713d471ca8835ca026bb32e841 | [
"MIT"
] | 4 | 2021-03-13T10:26:09.000Z | 2021-03-13T10:45:35.000Z | src/PhantomEngine/PhantomAction.cpp | DexianZhao/PhantomEngineV2 | cc3bf02ca1d442713d471ca8835ca026bb32e841 | [
"MIT"
] | 3 | 2020-06-01T01:53:05.000Z | 2021-03-21T03:51:33.000Z | //////////////////////////////////////////////////////////////////////////////////////////////////////
/*
文件 : PhantomAction.cpp
幻影游戏引擎, 2009-2016, Phantom Game Engine, http://www.aixspace.com
Design Writer : 赵德贤 Dexian Zhao
Email: yuzhou_995@hotmail.com
Copyright 2009-2016 Zhao Dexian
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////
#include "PhantomUIDialog.h"
#include "PhantomManager.h"
#include "PhantomAction.h"
namespace Phantom{
ActionBase::ActionBase()
{
m_context = 0;
m_bBegin = true;
m_next = 0;
m_current = this;
}
ActionBase::~ActionBase()
{
safe_release(m_next);
}
};
| 23.621622 | 103 | 0.372998 | DexianZhao |
cd229ade02b635fa8b562ca56a06c88e6bf80d38 | 1,772 | hpp | C++ | src/common/StringFormer.hpp | zhaldak/signature | f4c8eafd2d2af6b60f0b1380d5d4b01d33f35b74 | [
"MIT"
] | null | null | null | src/common/StringFormer.hpp | zhaldak/signature | f4c8eafd2d2af6b60f0b1380d5d4b01d33f35b74 | [
"MIT"
] | null | null | null | src/common/StringFormer.hpp | zhaldak/signature | f4c8eafd2d2af6b60f0b1380d5d4b01d33f35b74 | [
"MIT"
] | 1 | 2020-02-01T11:41:39.000Z | 2020-02-01T11:41:39.000Z | #pragma once
#include <algorithm>
#include <string_view>
#include <cstdio>
#include <cstdint>
#include <cstdarg>
class StringFormer
{
public:
StringFormer(StringFormer&&) = delete;
StringFormer(StringFormer const&) = delete;
StringFormer& operator=(StringFormer&&) = delete;
StringFormer& operator=(StringFormer const&) = delete;
~StringFormer() = default;
StringFormer(char* buffer, size_t size)
: m_start(buffer)
, m_end(buffer + size)
, m_free(buffer)
{
if (0 != size) { buffer[0] = '\0'; }
}
StringFormer& operator() (char const* format, ...)
{
va_list args;
va_start(args, format);
append(format, args);
va_end(args);
return *this;
}
int append(char const* format, ...)
{
va_list args;
va_start(args, format);
int res = append(format, args);
va_end(args);
return res;
}
int append(char const* format, va_list vlist)
{
if (not format || free_size() == 0) { return 0; }
int printed = vsnprintf(m_free, free_size(), format, vlist);
int res = std::min(printed, free_size());
m_free += res;
return res - (is_full() ? 1 : 0);
}
std::string_view sv() const noexcept { return {m_start, size()}; }
char const* c_str() const noexcept { return m_start; }
size_t size() const noexcept { return m_free - m_start - (is_full() ? 1 : 0); }
size_t capacity() const noexcept { return m_end - m_start; }
int free_size() const noexcept { return m_end - m_free; }
bool is_full() const noexcept { return m_free == m_end; }
bool empty() const noexcept { return m_free == m_start; }
void reset() noexcept { m_free = m_start; }
private:
char* m_start;
char* const m_end;
char* m_free;
};
| 24.273973 | 88 | 0.61851 | zhaldak |
cd232a6bc8d430afe3bf2d8375c894eff92b5662 | 34,676 | cpp | C++ | TerrainApps/CManager/frame.cpp | nakijun/vtp | 7bd2b2abd3a3f778a32ba30be099cfba9b892922 | [
"MIT"
] | 4 | 2019-02-08T13:51:26.000Z | 2021-12-07T13:11:06.000Z | TerrainApps/CManager/frame.cpp | nakijun/vtp | 7bd2b2abd3a3f778a32ba30be099cfba9b892922 | [
"MIT"
] | null | null | null | TerrainApps/CManager/frame.cpp | nakijun/vtp | 7bd2b2abd3a3f778a32ba30be099cfba9b892922 | [
"MIT"
] | 7 | 2017-12-03T10:13:17.000Z | 2022-03-29T09:51:18.000Z | //
// Name: frame.cpp
// Purpose: The frame class for the Content Manager.
//
// Copyright (c) 2001-2011 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <wx/stdpaths.h>
#include "vtlib/vtlib.h"
#include "vtlib/core/NavEngines.h"
#include "vtdata/FileFilters.h"
#include "vtdata/vtLog.h"
#include "vtdata/DataPath.h"
#include "vtdata/Version.h"
#include "vtui/Helper.h" // for ProgressDialog and AddType
#include "xmlhelper/easyxml.hpp"
#include "app.h"
#include "frame.h"
#include "canvas.h"
#include "menu_id.h"
#include "TreeView.h"
#include "ItemGroup.h"
// dialogs
#include "PropDlg.h"
#include "ModelDlg.h"
#include "LightDlg.h"
#include "wxosg/SceneGraphDlg.h"
#include "osgUtil/SmoothingVisitor"
#ifndef __WXMSW__
# include "icons/cmanager.xpm"
# include "bitmaps/axes.xpm"
# include "bitmaps/contents_open.xpm"
# include "bitmaps/item_new.xpm"
# include "bitmaps/item_remove.xpm"
# include "bitmaps/model_add.xpm"
# include "bitmaps/model_remove.xpm"
# include "bitmaps/properties.xpm"
# include "bitmaps/rulers.xpm"
# include "bitmaps/wireframe.xpm"
# include "bitmaps/stats.xpm"
#endif
DECLARE_APP(vtApp)
//
// Blank window class to use in bottom half of splitter2
//
class Blank: public wxWindow
{
public:
Blank(wxWindow *parent) : wxWindow(parent, -1) {}
void OnPaint( wxPaintEvent &event ) { wxPaintDC dc(this); }
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(Blank,wxWindow)
EVT_PAINT( Blank::OnPaint )
END_EVENT_TABLE()
//////////////////////////////////////////////////////////////////////////
// vtFrame class implementation
//
BEGIN_EVENT_TABLE(vtFrame, wxFrame)
EVT_CHAR(vtFrame::OnChar)
EVT_CLOSE(vtFrame::OnClose)
EVT_IDLE(vtFrame::OnIdle)
EVT_MENU(wxID_OPEN, vtFrame::OnOpen)
EVT_MENU(wxID_SAVE, vtFrame::OnSave)
EVT_MENU(wxID_EXIT, vtFrame::OnExit)
EVT_MENU(ID_SCENE_SCENEGRAPH, vtFrame::OnSceneGraph)
EVT_MENU(ID_TEST_XML, vtFrame::OnTestXML)
EVT_MENU(ID_ITEM_NEW, vtFrame::OnItemNew)
EVT_MENU(ID_ITEM_DEL, vtFrame::OnItemDelete)
EVT_MENU(ID_ITEM_ADDMODEL, vtFrame::OnItemAddModel)
EVT_UPDATE_UI(ID_ITEM_ADDMODEL, vtFrame::OnUpdateItemAddModel)
EVT_MENU(ID_ITEM_REMOVEMODEL, vtFrame::OnItemRemoveModel)
EVT_UPDATE_UI(ID_ITEM_REMOVEMODEL, vtFrame::OnUpdateItemModelExists)
EVT_MENU(ID_ITEM_MODELPROPS, vtFrame::OnItemModelProps)
EVT_UPDATE_UI(ID_ITEM_MODELPROPS, vtFrame::OnUpdateItemModelExists)
EVT_MENU(ID_ITEM_ROTMODEL, vtFrame::OnItemRotModel)
EVT_UPDATE_UI(ID_ITEM_ROTMODEL, vtFrame::OnUpdateItemModelExists)
EVT_MENU(ID_ITEM_SET_AMBIENT, vtFrame::OnItemSetAmbient)
EVT_UPDATE_UI(ID_ITEM_SET_AMBIENT, vtFrame::OnUpdateItemModelExists)
EVT_MENU(ID_ITEM_SMOOTHING, vtFrame::OnItemSmoothing)
EVT_UPDATE_UI(ID_ITEM_SMOOTHING, vtFrame::OnUpdateItemModelExists)
EVT_MENU(ID_ITEM_SAVE, vtFrame::OnItemSave)
EVT_MENU(ID_VIEW_ORIGIN, vtFrame::OnViewOrigin)
EVT_UPDATE_UI(ID_VIEW_ORIGIN, vtFrame::OnUpdateViewOrigin)
EVT_MENU(ID_VIEW_RULERS, vtFrame::OnViewRulers)
EVT_UPDATE_UI(ID_VIEW_RULERS, vtFrame::OnUpdateViewRulers)
EVT_MENU(ID_VIEW_WIREFRAME, vtFrame::OnViewWireframe)
EVT_UPDATE_UI(ID_VIEW_WIREFRAME, vtFrame::OnUpdateViewWireframe)
EVT_MENU(ID_VIEW_STATS, vtFrame::OnViewStats)
EVT_MENU(ID_VIEW_LIGHTS, vtFrame::OnViewLights)
EVT_MENU(ID_HELP_ABOUT, vtFrame::OnHelpAbout)
END_EVENT_TABLE()
vtFrame *GetMainFrame()
{
return (vtFrame *) wxGetApp().GetTopWindow();
}
// My frame constructor
vtFrame::vtFrame(wxFrame *parent, const wxString& title, const wxPoint& pos,
const wxSize& size, long style) :
wxFrame(parent, wxID_ANY, title, pos, size, style)
{
VTLOG(" constructing Frame (%x, title, pos, size, %x)\n", parent, style);
m_bCloseOnIdle = false;
#if WIN32
// Give it an icon
SetIcon(wxIcon(_T("cmanager")));
#endif
ReadDataPath();
VTLOG("Using Datapaths:\n");
int i, n = vtGetDataPath().size();
if (n == 0)
VTLOG(" none.\n");
for (i = 0; i < n; i++)
VTLOG(" %s\n", (const char *) vtGetDataPath()[i]);
m_pCurrentModel = NULL;
m_pCurrentItem = NULL;
m_bShowOrigin = true;
m_bShowRulers = false;
m_bWireframe = false;
CreateMenus();
CreateToolbar();
CreateStatusBar();
SetDropTarget(new DnDFile);
// frame icon
SetIcon(wxICON(cmanager));
VTLOG(" creating component windows\n");
// splitters
m_splitter = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition,
wxDefaultSize, wxSP_3D /*| wxSP_LIVE_UPDATE*/);
m_splitter2 = new wxSplitterWindow(m_splitter, wxID_ANY, wxDefaultPosition,
wxDefaultSize, wxSP_3D | wxSP_LIVE_UPDATE);
m_blank = new Blank(m_splitter2); // (wxWindowID) -1, _T("blank"), wxDefaultPosition);
m_pTree = new MyTreeCtrl(m_splitter2, ID_TREECTRL,
wxPoint(0, 0), wxSize(200, 400),
// wxTR_HAS_BUTTONS |
wxTR_EDIT_LABELS |
wxNO_BORDER);
m_pTree->SetBackgroundColour(*wxLIGHT_GREY);
// We definitely want full color and a 24-bit Z-buffer!
int gl_attrib[8] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER,
WX_GL_BUFFER_SIZE, 24, WX_GL_DEPTH_SIZE, 24, 0, 0 };
// Make a vtGLCanvas
VTLOG1(" creating canvas\n");
m_canvas = new CManagerCanvas(m_splitter, wxID_ANY, wxPoint(0, 0), wxSize(-1, -1),
0, _T("CManagerCanvas"), gl_attrib);
VTLOG(" creating scenegraphdialog\n");
m_pSceneGraphDlg = new SceneGraphDlg(this, wxID_ANY, _T("Scene Graph"),
wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
m_pSceneGraphDlg->SetSize(250, 350);
m_pPropDlg = new PropPanel(m_splitter2, wxID_ANY,
wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE);
m_pModelDlg = new ModelPanel(m_splitter2, wxID_ANY,
wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE);
m_pModelDlg->Show(false);
m_pModelDlg->InitDialog();
m_pLightDlg = new LightDlg(this, -1, _T("Lights"));
m_splitter->Initialize(m_splitter2);
////////////////////////
m_pTree->Show(true);
m_canvas->Show(true);
m_splitter->SplitVertically( m_splitter2, m_canvas, 260);
m_splitter2->SplitHorizontally( m_pTree, m_blank, 200);
m_pPropDlg->Show(true);
m_pPropDlg->InitDialog();
// Show the frame
Show(true);
// Load the font
vtString fontfile = "Arial.ttf";
m_pFont = osgText::readFontFile((const char *)fontfile);
if (!m_pFont.valid())
{
vtString fontname = "Fonts/" + fontfile;
vtString font_path = FindFileOnPaths(vtGetDataPath(), fontname);
if (font_path != "")
m_pFont = osgText::readFontFile((const char *)font_path);
if (!m_pFont.valid())
{
VTLOG("Couldn't find or read font from file '%s'\n",
(const char *) fontname);
}
}
#if 0
// TEST CODE
osg::Node *node = osgDB::readNodeFile("in.obj");
osgDB::Registry::instance()->writeNode(*node, "out.osg");
#endif
SetCurrentItemAndModel(NULL, NULL);
m_pTree->RefreshTreeItems(this);
}
vtFrame::~vtFrame()
{
VTLOG(" destructing Frame\n");
FreeContents();
delete m_canvas;
delete m_pSceneGraphDlg;
delete m_pLightDlg;
}
void vtFrame::UseLight(vtTransform *pLight)
{
m_pLightDlg->UseLight(pLight);
}
//////////////////////////////
using namespace std;
void vtFrame::ReadDataPath()
{
// Look these up, we might need them
wxString Dir1 = wxStandardPaths::Get().GetUserConfigDir();
wxString Dir2 = wxStandardPaths::Get().GetConfigDir();
vtString AppDataUser = (const char *) Dir1.mb_str(wxConvUTF8);
vtString AppDataCommon = (const char *) Dir2.mb_str(wxConvUTF8);
// Read the vt datapaths
vtLoadDataPath(AppDataUser, AppDataCommon);
vtStringArray &dp = vtGetDataPath();
// Supply the special symbols {appdata} and {appdatacommon}
for (uint i = 0; i < dp.size(); i++)
{
dp[i].Replace("{appdata}", AppDataUser);
dp[i].Replace("{appdatacommon}", AppDataCommon);
}
}
void vtFrame::CreateMenus()
{
// Make menus
wxMenu *fileMenu = new wxMenu;
fileMenu->Append(wxID_OPEN, _T("Open Content File"), _T("Open"));
fileMenu->Append(wxID_SAVE, _T("&Save Content File"));
fileMenu->AppendSeparator();
fileMenu->Append(ID_SCENE_SCENEGRAPH, _T("Scene Graph"));
fileMenu->AppendSeparator();
fileMenu->Append(ID_TEST_XML, _T("Test XML"));
fileMenu->AppendSeparator();
fileMenu->Append(ID_SET_DATA_PATH, _T("Set Data Path"));
fileMenu->AppendSeparator();
fileMenu->Append(wxID_EXIT, _T("E&xit\tEsc"), _T("Exit"));
wxMenu *itemMenu = new wxMenu;
itemMenu->Append(ID_ITEM_NEW, _T("New Item"));
itemMenu->Append(ID_ITEM_DEL, _T("Delete Item"));
itemMenu->AppendSeparator();
itemMenu->Append(ID_ITEM_ADDMODEL, _T("Add Model"));
itemMenu->Append(ID_ITEM_REMOVEMODEL, _T("Remove Model"));
itemMenu->Append(ID_ITEM_MODELPROPS, _T("Model Properties"));
itemMenu->AppendSeparator();
itemMenu->Append(ID_ITEM_ROTMODEL, _T("Rotate Model Around X Axis"));
itemMenu->Append(ID_ITEM_SET_AMBIENT, _T("Set materials' ambient from diffuse"));
itemMenu->Append(ID_ITEM_SMOOTHING, _T("Fix normals (apply smoothing)"));
itemMenu->AppendSeparator();
itemMenu->Append(ID_ITEM_SAVE, _T("Save Model"));
wxMenu *viewMenu = new wxMenu;
viewMenu->AppendCheckItem(ID_VIEW_ORIGIN, _T("Show Local Origin"));
viewMenu->AppendCheckItem(ID_VIEW_RULERS, _T("Show Rulers"));
viewMenu->AppendCheckItem(ID_VIEW_WIREFRAME, _T("&Wireframe\tCtrl+W"));
viewMenu->Append(ID_VIEW_STATS, _T("Statistics (cycle)\tx"));
viewMenu->Append(ID_VIEW_LIGHTS, _T("Lights"));
wxMenu *helpMenu = new wxMenu;
helpMenu->Append(ID_HELP_ABOUT, _T("About VTP Content Manager..."));
wxMenuBar *menuBar = new wxMenuBar;
menuBar->Append(fileMenu, _T("&File"));
menuBar->Append(itemMenu, _T("&Item"));
menuBar->Append(viewMenu, _T("&View"));
menuBar->Append(helpMenu, _T("&Help"));
SetMenuBar(menuBar);
}
void vtFrame::CreateToolbar()
{
// tool bar
m_pToolbar = CreateToolBar(wxTB_HORIZONTAL | wxNO_BORDER | wxTB_DOCKABLE);
m_pToolbar->SetMargins(2, 2);
m_pToolbar->SetToolBitmapSize(wxSize(20, 20));
AddTool(wxID_OPEN, wxBITMAP(contents_open), _("Open Contents File"), false);
m_pToolbar->AddSeparator();
AddTool(ID_ITEM_NEW, wxBITMAP(item_new), _("New Item"), false);
AddTool(ID_ITEM_DEL, wxBITMAP(item_remove), _("Delete Item"), false);
m_pToolbar->AddSeparator();
AddTool(ID_ITEM_ADDMODEL, wxBITMAP(model_add), _("Add Model"), false);
AddTool(ID_ITEM_REMOVEMODEL, wxBITMAP(model_remove), _("Remove Model"), false);
AddTool(ID_ITEM_MODELPROPS, wxBITMAP(properties), _("Model Properties"), false);
m_pToolbar->AddSeparator();
AddTool(ID_VIEW_ORIGIN, wxBITMAP(axes), _("Show Axes"), true);
AddTool(ID_VIEW_RULERS, wxBITMAP(rulers), _("Show Rulers"), true);
AddTool(ID_VIEW_WIREFRAME, wxBITMAP(wireframe), _("Wireframe"), true);
m_pToolbar->AddSeparator();
AddTool(ID_VIEW_STATS, wxBITMAP(stats), _("Statistics (cycle)"), false);
m_pToolbar->Realize();
}
//
// Utility methods
//
void vtFrame::OnChar(wxKeyEvent& event)
{
long key = event.GetKeyCode();
if (key == 27)
{
// Esc: exit application
// It's not safe to close immediately, as that will kill the canvas,
// and it might some Canvas event that caused us to close. So,
// simply stop rendering, and delay closing until the next Idle event.
m_canvas->m_bRunning = false;
m_bCloseOnIdle = true;
}
}
void vtFrame::OnClose(wxCloseEvent &event)
{
VTLOG("Frame OnClose\n");
if (m_canvas)
{
m_canvas->m_bRunning = false;
m_bCloseOnIdle = true;
}
event.Skip();
}
void vtFrame::OnIdle(wxIdleEvent& event)
{
// Check if we were requested to close on the next Idle event.
if (m_bCloseOnIdle)
{
VTLOG("CloseOnIdle, calling Close()\n");
Close();
}
else
event.Skip();
}
//
// Intercept menu commands
//
void vtFrame::OnOpen(wxCommandEvent& event)
{
m_canvas->m_bRunning = false;
wxFileDialog loadFile(NULL, _T("Load Content File"), _T(""), _T(""),
FSTRING_VTCO, wxFD_OPEN);
loadFile.SetFilterIndex(1);
if (loadFile.ShowModal() == wxID_OK)
LoadContentsFile(loadFile.GetPath());
m_canvas->m_bRunning = true;
}
void vtFrame::OnSave(wxCommandEvent& event)
{
m_canvas->m_bRunning = false;
wxFileDialog loadFile(NULL, _T("Save Content File"), _T(""), _T(""),
FSTRING_VTCO, wxFD_SAVE);
loadFile.SetFilterIndex(1);
if (loadFile.ShowModal() == wxID_OK)
SaveContentsFile(loadFile.GetPath());
m_canvas->m_bRunning = true;
}
void vtFrame::LoadContentsFile(const wxString &fname)
{
VTLOG("LoadContentsFile '%s'\n", (const char *) fname.mb_str(wxConvUTF8));
FreeContents();
try
{
m_Man.ReadXML(fname.mb_str(wxConvUTF8));
}
catch (xh_io_exception &e)
{
string str = e.getFormattedMessage();
DisplayMessageBox(wxString(str.c_str(), wxConvUTF8));
return;
}
SetCurrentItem(NULL);
SetCurrentModel(NULL);
m_pTree->RefreshTreeItems(this);
}
void vtFrame::FreeContents()
{
VTLOG("FreeContents\n");
for (uint i = 0; i < m_Man.NumItems(); i++)
{
vtItem *item = m_Man.GetItem(i);
ItemGroup *ig = m_itemmap[item];
delete ig;
}
m_itemmap.clear();
m_nodemap.clear();
m_Man.Clear();
m_pCurrentItem = NULL;
m_pCurrentModel = NULL;
}
void vtFrame::SaveContentsFile(const wxString &fname)
{
VTLOG("SaveContentsFile '%s'\n", (const char *) fname.mb_str(wxConvUTF8));
try
{
m_Man.WriteXML(fname.mb_str(wxConvUTF8));
}
catch (xh_io_exception &e)
{
string str = e.getFormattedMessage();
DisplayMessageBox(wxString(str.c_str(), wxConvUTF8));
}
}
/// String comparison which considers '/' and '\' equivalent
bool SamePath(const vtString &s1, const vtString &s2)
{
int i, n = s1.GetLength();
for (i = 0; i < n; i++)
{
if (s1[i] != s2[i] &&
!(s1[i] == '/' && s2[i] == '\\') &&
!(s1[i] == '\\' && s2[i] == '/'))
break;
}
return i == n;
}
void vtFrame::AddModelFromFile(const wxString &fname1)
{
vtString fname = (const char *) fname1.mb_str();
VTLOG("AddModelFromFile '%s'\n", (const char *) fname);
// Change backslashes to slashes.
fname.Replace('\\', '/');
// Check if its on the known data path.
vtStringArray &paths = vtGetDataPath();
for (uint i = 0; i < paths.size(); i++)
{
int n = paths[i].GetLength();
if (SamePath(paths[i], fname.Left(n)))
{
// found it
fname = fname.Right(fname.GetLength() - n);
break;
}
}
vtModel *nm = AddModel(wxString(fname, *wxConvCurrent));
if (nm)
SetCurrentItemAndModel(m_pCurrentItem, nm);
}
void vtFrame::ModelNameChanged(vtModel *model)
{
vtTransform *trans = m_nodemap[model];
if (trans)
m_nodemap[model] = NULL;
model->m_attempted_load = false;
DisplayCurrentModel();
// update tree view
m_pTree->RefreshTreeItems(this);
// update 3d scene graph
UpdateItemGroup(m_pCurrentItem);
}
int vtFrame::GetModelTriCount(vtModel *model)
{
vtTransform *trans = m_nodemap[model];
if (!trans)
return 0;
return 0;
}
void vtFrame::OnExit(wxCommandEvent& event)
{
VTLOG("Got Exit event, shutting down.\n");
if (m_canvas)
{
m_canvas->m_bRunning = false;
delete m_canvas;
m_canvas = NULL;
}
Destroy();
}
void vtFrame::OnSceneGraph(wxCommandEvent& event)
{
m_pSceneGraphDlg->Show(true);
}
void vtFrame::OnItemNew(wxCommandEvent& event)
{
AddNewItem();
m_pTree->RefreshTreeItems(this);
}
void vtFrame::OnItemDelete(wxCommandEvent& event)
{
if (!m_pCurrentItem)
return;
m_Man.RemoveItem(m_pCurrentItem);
SetCurrentItemAndModel(NULL, NULL);
m_pTree->RefreshTreeItems(this);
}
void vtFrame::OnItemAddModel(wxCommandEvent& event)
{
wxString filter= _("3D Model Files|");
AddType(filter, FSTRING_3DS);
AddType(filter, FSTRING_DAE);
AddType(filter, FSTRING_FLT);
AddType(filter, FSTRING_LWO);
AddType(filter, FSTRING_OBJ);
AddType(filter, FSTRING_IVE);
AddType(filter, FSTRING_OSG);
filter += _T("|");
filter += FSTRING_ALL;
wxFileDialog loadFile(NULL, _T("Load 3d Model"), _T(""), _T(""), filter, wxFD_OPEN);
loadFile.SetFilterIndex(0);
if (loadFile.ShowModal() != wxID_OK)
return;
AddModelFromFile(loadFile.GetPath());
}
void vtFrame::OnUpdateItemAddModel(wxUpdateUIEvent& event)
{
event.Enable(m_pCurrentItem != NULL);
}
void vtFrame::OnItemRemoveModel(wxCommandEvent& event)
{
vtModel *previous = m_pCurrentModel;
m_pCurrentItem->RemoveModel(m_pCurrentModel);
SetCurrentItemAndModel(m_pCurrentItem, NULL);
// update tree view
m_pTree->RefreshTreeItems(this);
// update 3d scene graph
UpdateItemGroup(m_pCurrentItem);
// free memory
m_nodemap.erase(previous);
}
void vtFrame::OnItemModelProps(wxCommandEvent& event)
{
vtModel *mod = m_pCurrentModel;
osg::Node *node = m_nodemap[mod];
if (!node)
return;
FBox3 box;
GetNodeBoundBox(node, box);
wxString str, s;
s.Printf(_T("Extents:\n %f %f (width %f)\n %f %f (height %f)\n %f %f (depth %f)\n"),
box.min.x, box.max.x, box.max.x - box.min.x,
box.min.y, box.max.y, box.max.y - box.min.y,
box.min.z, box.max.z, box.max.z - box.min.z);
str += s;
vtPrimInfo info;
GetNodePrimCounts(node, info);
s.Printf(_T("\nPrimitives:\n"));
str += s;
s.Printf(_T(" Vertices: %d\n"), info.MemVertices);
str += s;
s.Printf(_T(" Vertices Drawn: %d\n"), info.Vertices);
if (info.Vertices != info.MemVertices) str += s;
s.Printf(_T(" Primitives: %d\n"), info.Primitives);
str += s;
s.Printf(_T(" Points: %d\n"), info.Points);
if (info.Points) str += s;
s.Printf(_T(" TriStrips: %d\n"), info.TriStrips);
if (info.TriStrips) str += s;
s.Printf(_T(" TriFans: %d\n"), info.TriFans);
if (info.TriFans) str += s;
s.Printf(_T(" Triangles: %d\n"), info.Triangles);
if (info.Triangles) str += s;
s.Printf(_T(" Quads: %d\n"), info.Quads);
if (info.Quads) str += s;
s.Printf(_T(" QuadStrips: %d\n"), info.QuadStrips);
if (info.QuadStrips) str += s;
s.Printf(_T(" Polygons: %d\n"), info.Polygons);
if (info.Polygons) str += s;
s.Printf(_T(" LineStrips: %d\n"), info.LineStrips);
if (info.LineStrips) str += s;
s.Printf(_T(" LineSegments: %d\n"), info.LineSegments);
if (info.LineSegments) str += s;
wxMessageBox(str, _T("Model Properties"));
}
void vtFrame::OnUpdateItemModelExists(wxUpdateUIEvent& event)
{
event.Enable(m_pCurrentItem && m_pCurrentModel);
}
// Walk an OSG scenegraph looking for geodes with statesets, change the ambient
// component of any materials found.
class SetAmbientVisitor : public osg::NodeVisitor
{
public:
SetAmbientVisitor() : NodeVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
virtual void apply(osg::Geode& geode)
{
osg::StateSet *ss1 = geode.getStateSet();
if (ss1)
SetAmbient(ss1);
for (unsigned i=0; i<geode.getNumDrawables(); ++i)
{
osg::StateSet *ss2 = geode.getDrawable(i)->getStateSet();
if (ss2)
SetAmbient(ss2);
}
osg::NodeVisitor::apply(geode);
}
void SetAmbient(osg::StateSet *ss)
{
osg::StateAttribute *state = ss->getAttribute(osg::StateAttribute::MATERIAL);
if (!state) return;
osg::Material *mat = dynamic_cast<osg::Material *>(state);
if (!mat) return;
osg::Vec4 amb = mat->getAmbient(FAB);
osg::Vec4 d = mat->getDiffuse(FAB);
VTLOG("oldamb %f %f %f, ", amb.r(), amb.g(), amb.b(), amb.a());
osg::Material *newmat = (osg::Material *)mat->clone(osg::CopyOp::DEEP_COPY_ALL);
newmat->setAmbient(FAB, osg::Vec4(d.r()*ratio,d.g()*ratio,d.b()*ratio,1));
amb = newmat->getAmbient(FAB);
VTLOG("newamb %f %f %f\n", amb.r(), amb.g(), amb.b(), amb.a());
ss->setAttribute(newmat);
}
float ratio;
};
void vtFrame::OnItemRotModel(wxCommandEvent& event)
{
vtModel *mod = m_pCurrentModel;
osg::Node *node = m_nodemap[mod];
// this node is actually the scaling transform; we want its child
vtTransform *transform = dynamic_cast<vtTransform*>(node);
if (!transform)
return;
osg::Node *node2 = transform->getChild(0);
ApplyVertexRotation(node2, FPoint3(1,0,0), -PID2f);
}
void vtFrame::OnItemSetAmbient(wxCommandEvent& event)
{
vtModel *mod = m_pCurrentModel;
osg::Node *node = m_nodemap[mod];
SetAmbientVisitor sav;
sav.ratio = 0.4f;
node->accept(sav);
}
void vtFrame::OnItemSmoothing(wxCommandEvent& event)
{
vtModel *mod = m_pCurrentModel;
osg::Node *node = m_nodemap[mod];
osgUtil::SmoothingVisitor smoother;
node->accept(smoother);
}
void vtFrame::OnItemSave(wxCommandEvent& event)
{
vtTransform *trans = m_nodemap[m_pCurrentModel];
if (!trans)
return;
NodePtr node = trans->getChild(0);
if (!node.valid())
return;
#if 0
// To be elegant, we could ask OSG for all formats that it knows how to write.
// This code does that, but it isn't reliable because osgDB::queryPlugin
// only works if the plugin wasn't already loaded.
// This also needs the headers osgDB/ReaderWriter and osgDB/PluginQuery.
osgDB::FileNameList plugins = osgDB::listAllAvailablePlugins();
int count = 0;
for (osgDB::FileNameList::iterator itr = plugins.begin();
itr != plugins.end(); ++itr)
{
count++;
const std::string& fileName = *itr;
osgDB::ReaderWriterInfoList infoList;
if (osgDB::queryPlugin(fileName, infoList))
{
VTLOG("Got query of: %s, %d entries\n", fileName.c_str(), infoList.size());
for(osgDB::ReaderWriterInfoList::iterator rwi_itr = infoList.begin();
rwi_itr != infoList.end(); ++rwi_itr)
{
// Each ReaderWrite has one or more features (like readNode, writeObject)
// and one or more extensions (like .png, .osgb)
osgDB::ReaderWriterInfo& info = *(*rwi_itr);
// Features:
if (info.features & osgDB::ReaderWriter::FEATURE_WRITE_NODE)
{
osgDB::ReaderWriter::FormatDescriptionMap::iterator fdm_itr;
for (fdm_itr = info.extensions.begin();
fdm_itr != info.extensions.end();
++fdm_itr)
{
VTLOG("%s (%s) " fdm_itr->first.c_str(), fdm_itr->second.c_str());
}
VTLOG1("\n");
}
}
}
}
VTLOG("Total plugins: %d\n", count);
#else
// Just hard-code the formats we expect to be writable with OSG 3.x
wxString filter = _("All Files|*.*");
AddType(filter, _("OpenSceneGraph Ascii file format (*.osg)|*.osg"));
AddType(filter, _("OpenSceneGraph native binary format (*.ive)|*.ive"));
AddType(filter, _("OpenSceneGraph extendable binary format (*.osgb)|*.osgb"));
AddType(filter, _("OpenSceneGraph extendable Ascii format (*.osgt)|*.osgt"));
AddType(filter, _("OpenSceneGraph extendable XML format (*.osgx)|*.osgx"));
AddType(filter, _("3D Studio model format (*.3ds)|*.3ds"));
AddType(filter, _("Alias Wavefront OBJ format (*.obj)|*.obj"));
AddType(filter, _("OpenFlight format (*.flt)|*.flt"));
AddType(filter, _("STL ASCII format (*.sta)|*.sta"));
AddType(filter, _("STL binary format (*.stl)|*.stl"));
#endif
// ask the user for a filename
wxFileDialog saveFile(NULL, _("Export"), _T(""), _T(""),
filter, wxFD_SAVE);
saveFile.SetFilterIndex(1);
if (saveFile.ShowModal() != wxID_OK)
return;
wxString path = saveFile.GetPath();
vtString fname = (const char *) path.mb_str(wxConvUTF8);
if (fname == "")
return;
OpenProgressDialog(_T("Writing file"), path, false, this);
// OSG/IVE has a different axis convention that VTLIB does (Z up, not Y up)
// So we must rotate before saving, then rotate back again
ApplyVertexRotation(node, FPoint3(1,0,0), PID2f);
bool success = vtSaveModel(node, fname);
// Rotate back again
ApplyVertexRotation(node, FPoint3(1,0,0), -PID2f);
CloseProgressDialog();
if (success)
wxMessageBox(_("File saved.\n"));
else
wxMessageBox(_("Error in writing file.\n"));
}
void vtFrame::UpdateWidgets()
{
if (!m_pCurrentItem)
return;
ItemGroup *ig = m_itemmap[m_pCurrentItem];
if (ig)
{
ig->ShowOrigin(m_bShowOrigin);
ig->ShowRulers(m_bShowRulers);
}
}
void vtFrame::OnViewOrigin(wxCommandEvent& event)
{
m_bShowOrigin = !m_bShowOrigin;
if (m_bShowOrigin)
m_bShowRulers = false;
UpdateWidgets();
m_canvas->Refresh(false);
}
void vtFrame::OnUpdateViewOrigin(wxUpdateUIEvent& event)
{
event.Check(m_bShowOrigin);
}
void vtFrame::OnViewRulers(wxCommandEvent& event)
{
m_bShowRulers = !m_bShowRulers;
if (m_bShowRulers)
m_bShowOrigin = false;
UpdateWidgets();
m_canvas->Refresh(false);
}
void vtFrame::OnUpdateViewRulers(wxUpdateUIEvent& event)
{
event.Check(m_bShowRulers);
}
void vtFrame::OnViewWireframe(wxCommandEvent& event)
{
m_bWireframe = !m_bWireframe;
vtGetScene()->SetGlobalWireframe(m_bWireframe);
m_canvas->Refresh(false);
}
void vtFrame::OnUpdateViewWireframe(wxUpdateUIEvent& event)
{
event.Check(m_bWireframe);
}
void vtFrame::OnViewStats(wxCommandEvent& event)
{
#ifdef VTP_USE_OSG_STATS
// Yes, this is a hack, but it doesn't seem that StatsHandler can be cycled
// any other way than by key event.
osgViewer::GraphicsWindow *pGW = vtGetScene()->GetGraphicsWindow();
if ((NULL != pGW) && pGW->valid())
pGW->getEventQueue()->keyPress('x');
#endif
}
void vtFrame::OnViewLights(wxCommandEvent& event)
{
m_pLightDlg->Show(true);
}
void vtFrame::OnHelpAbout(wxCommandEvent& event)
{
m_canvas->m_bRunning = false; // stop rendering
wxString str = _T("VTP Content Manager\n\n");
str += _T("Manages sources of 3d models for the Virtual Terrain Project software.\n\n");
str += _T("Please read the HTML documentation and license.\n");
str += _T("Send feedback to: ben@vterrain.org\n");
str += _T("\nVersion: ");
str += _T(VTP_VERSION);
str += _T("\n");
str += _T("Build date: ");
str += _T(__DATE__);
wxMessageBox(str, _T("About CManager"));
m_canvas->m_bRunning = true; // start rendering again
m_canvas->Refresh(false);
}
//////////////////////////////////////////////////////////////////////////
void vtFrame::AddNewItem()
{
VTLOG("Creating new Item\n");
vtItem *pItem = new vtItem;
pItem->m_name = "untitled";
m_Man.AddItem(pItem);
SetCurrentItemAndModel(pItem, NULL);
}
vtModel *vtFrame::AddModel(const wxString &fname_in)
{
VTLOG("AddModel %s\n", (const char *) fname_in.mb_str());
#if 0
const char *fname = StartOfFilename(fname_in.mb_str());
vtString onpath = FindFileOnPaths(vtGetDataPaths(), fname);
if (onpath == "")
{
// Warning! May not be on the data path.
wxString str;
str.Printf(_T("That file:\n%hs\ndoes not appear to be on the data")
_T(" paths:"), fname);
for (int i = 0; i < vtGetDataPaths().GetSize(); i++)
{
vtString *vts = vtGetDataPaths()[i];
const char *cpath = (const char *) *vts;
wxString path = cpath;
str += _T("\n");
str += path;
}
DisplayMessageBox(str);
return NULL;
}
#else
// data path code is too complicated, just store absolute paths
vtString fname = (const char *) fname_in.mb_str();
#endif
// If there is no item, make a new one.
if (!m_pCurrentItem)
AddNewItem();
vtModel *new_model = new vtModel;
new_model->m_filename = fname;
osg::Node *node = AttemptLoad(new_model);
if (!node)
{
delete new_model;
return NULL;
}
// add to current item
m_pCurrentItem->AddModel(new_model);
// update tree view
m_pTree->RefreshTreeItems(this);
// update 3d scene graph
UpdateItemGroup(m_pCurrentItem);
return new_model;
}
vtTransform *vtFrame::AttemptLoad(vtModel *model)
{
VTLOG("AttemptLoad '%s'\n", (const char *) model->m_filename);
model->m_attempted_load = true;
// stop rendering while progress dialog is open
m_canvas->m_bRunning = false;
wxString str(model->m_filename, wxConvUTF8);
OpenProgressDialog(_T("Reading file"), str, false, this);
NodePtr pNode;
vtString fullpath = FindFileOnPaths(vtGetDataPath(), model->m_filename);
if (fullpath != "")
{
UpdateProgressDialog(5, str);
pNode = vtLoadModel(fullpath);
}
CloseProgressDialog();
// resume rendering after progress dialog is closed
m_canvas->m_bRunning = true;
if (!pNode.valid())
{
str.Printf(_T("Sorry, couldn't load model from %hs"), (const char *) model->m_filename);
VTLOG1(str.mb_str(wxConvUTF8));
DisplayMessageBox(str);
return NULL;
}
else
VTLOG(" Loaded OK.\n");
// check
FSphere sphere;
s2v(pNode->getBound(), sphere);
// Wrap in a transform node so that we can scale/rotate the node
vtTransform *pTrans = new vtTransform;
pTrans->setName("Scaling Transform");
pTrans->addChild(pNode);
// Add to map of model -> nodes
m_nodemap[model] = pTrans;
UpdateTransform(model);
return pTrans;
}
void vtFrame::SetCurrentItemAndModel(vtItem *item, vtModel *model)
{
m_blank->Show(item == NULL && model == NULL);
m_pModelDlg->Show(item != NULL && model != NULL);
m_pPropDlg->Show(item != NULL && model == NULL);
SetCurrentItem(item);
SetCurrentModel(model);
if (item != NULL && model == NULL)
{
DisplayCurrentItem();
m_splitter2->ReplaceWindow(m_splitter2->GetWindow2(), m_pPropDlg);
ZoomToCurrentItem();
}
else if (item != NULL && model != NULL)
m_splitter2->ReplaceWindow(m_splitter2->GetWindow2(), m_pModelDlg);
else
m_splitter2->ReplaceWindow(m_splitter2->GetWindow2(), m_blank);
}
void vtFrame::SetCurrentItem(vtItem *item)
{
VTLOG("SetCurrentItem(%s)\n", item == NULL ? "none" : (const char *) item->m_name);
if (item == m_pCurrentItem)
return;
if (m_pCurrentItem)
GetItemGroup(m_pCurrentItem)->GetTop()->SetEnabled(false);
m_pCurrentItem = item;
m_pCurrentModel = NULL;
if (item)
{
UpdateItemGroup(item);
m_pPropDlg->SetCurrentItem(item);
}
m_pTree->RefreshTreeStatus(this);
if (m_pCurrentItem)
GetItemGroup(m_pCurrentItem)->GetTop()->SetEnabled(true);
}
ItemGroup *vtFrame::GetItemGroup(vtItem *item)
{
ItemGroup *ig = m_itemmap[item];
if (!ig)
{
ig = new ItemGroup(item);
m_itemmap[item] = ig;
ig->CreateNodes();
vtScene *pScene = vtGetScene();
vtGroup *pRoot = pScene->GetRoot();
pRoot->addChild(ig->GetTop());
}
return ig;
}
void vtFrame::UpdateItemGroup(vtItem *item)
{
ItemGroup *ig = GetItemGroup(item);
ig->AttemptToLoadModels();
ig->AttachModels(m_pFont);
ig->ShowOrigin(m_bShowOrigin);
ig->ShowRulers(m_bShowRulers);
ig->SetRanges();
}
//
// True to show the current item as an LOD'd object
//
void vtFrame::ShowItemGroupLOD(bool bTrue)
{
if (!m_pCurrentItem)
return;
ItemGroup *ig = GetItemGroup(m_pCurrentItem);
if (ig)
ig->ShowLOD(bTrue);
}
void vtFrame::SetCurrentModel(vtModel *model)
{
VTLOG("SetCurrentModel(%s)\n", model == NULL ? "none" : (const char *) model->m_filename);
if (model == m_pCurrentModel)
return;
// 3d scene graph: turn off previous node
if (m_pCurrentModel)
{
vtTransform *trans = m_nodemap[m_pCurrentModel];
if (trans)
trans->SetEnabled(false);
}
m_pCurrentModel = model;
// update properties dialog
m_pModelDlg->SetCurrentModel(model);
// update 3d scene graph
if (model)
{
DisplayCurrentModel();
ZoomToCurrentModel();
}
// update tree view
m_pTree->RefreshTreeStatus(this);
}
//
// Update 3d scene graph and 3d view
// also attempt to load any models which have not yet been loaded, and put
// the status to the properties dialog
//
void vtFrame::DisplayCurrentModel()
{
// show this individual model, not the LOD'd item
ShowItemGroupLOD(false);
vtTransform *trans = m_nodemap[m_pCurrentModel];
if (!trans && !m_pCurrentModel->m_attempted_load)
{
trans = AttemptLoad(m_pCurrentModel);
}
if (trans)
{
trans->SetEnabled(true);
m_pModelDlg->SetModelStatus("Good");
}
else
{
m_pModelDlg->SetModelStatus("Failed to load.");
}
}
void vtFrame::ZoomToCurrentModel()
{
ZoomToModel(m_pCurrentModel);
}
void vtFrame::ZoomToModel(vtModel *model)
{
vtTransform *trans = m_nodemap[model];
if (!trans)
return;
vtCamera *pCamera = vtGetScene()->GetCamera();
float fYon = pCamera->GetFOV();
FSphere sph;
trans->GetBoundSphere(sph);
// consider the origin-center bounding sphere
float origin_centered = sph.center.Length() + sph.radius;
// how far back does the camera have to be to see the whole sphere
float dist = origin_centered / sinf(fYon / 2);
wxGetApp().m_pTrackball->SetRadius(dist);
wxGetApp().m_pTrackball->SetZoomScale(sph.radius);
wxGetApp().m_pTrackball->SetTransScale(sph.radius/2);
wxGetApp().m_pTrackball->SetTrans(FPoint3(0,0,0));
pCamera->SetYon(sph.radius * 100.0f);
}
void vtFrame::DisplayCurrentItem()
{
ShowItemGroupLOD(true);
}
void vtFrame::ZoomToCurrentItem()
{
if (!m_pCurrentItem)
return;
if (m_pCurrentItem->NumModels() < 1)
return;
vtModel *model = m_pCurrentItem->GetModel(0);
if (model)
ZoomToModel(model);
}
void vtFrame::RefreshTreeItems()
{
m_pTree->RefreshTreeItems(this);
}
void vtFrame::SetItemName(vtItem *item, const vtString &name)
{
item->m_name = name;
m_pPropDlg->SetCurrentItem(item);
}
//////////////////////////////////////////////////////////////////////////
bool DnDFile::OnDropFiles(wxCoord, wxCoord, const wxArrayString& filenames)
{
size_t nFiles = filenames.GetCount();
for ( size_t n = 0; n < nFiles; n++ )
{
wxString str = filenames[n];
if (str.Right(4).CmpNoCase(_T("vtco")) == 0)
GetMainFrame()->LoadContentsFile(str);
else
GetMainFrame()->AddModelFromFile(str);
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void vtFrame::OnTestXML(wxCommandEvent& event)
{
#if 0
vtContentManager Man;
try {
Man.ReadXML("content3.vtco");
Man.WriteXML("content4.vtco");
}
catch (xh_io_exception &e)
{
string str = e.getFormattedMessage();
DisplayMessageBox(wxString(str.c_str(), wxConvUTF8));
return;
}
#elif 0
vtImage *image = new vtImage("C:/TEMP/test_transparent.png");
// Compress
osg::ref_ptr<osg::State> state = new osg::State;
// get OpenGL driver to create texture from image.
vtMaterial *mat = new vtMaterial;
mat->SetTexture(image);
mat->m_pTexture->apply(*state);
image->GetOsgImage()->readImageFromCurrentTexture(0,true);
osgDB::ReaderWriter::WriteResult wr;
osgDB::Registry *reg = osgDB::Registry::instance();
wr = reg->writeImage(*(image->GetOsgImage()), "C:/TEMP/test_transparent.dds");
#endif
}
void vtFrame::DisplayMessageBox(const wxString &str)
{
m_canvas->m_bRunning = false;
wxMessageBox(str);
m_canvas->m_bRunning = true;
m_canvas->Refresh(false);
}
void vtFrame::UpdateCurrentModelLOD()
{
// safety
if (!m_pCurrentItem)
return;
ItemGroup *ig = m_itemmap[m_pCurrentItem];
if (!ig)
return;
ig->SetRanges();
}
void vtFrame::UpdateScale(vtModel *model)
{
UpdateTransform(model);
UpdateItemGroup(m_pCurrentItem);
}
void vtFrame::UpdateTransform(vtModel *model)
{
// scale may occasionally be 0 while the user is typing a new value.
if (model->m_scale == 0.0f)
return;
vtTransform *trans = m_nodemap[model];
if (!trans)
return;
trans->Identity();
vtString ext = GetExtension(model->m_filename, false);
trans->Scale(model->m_scale);
}
void vtFrame::RenderingPause()
{
m_canvas->m_bRunning = false;
}
void vtFrame::RenderingResume()
{
m_canvas->m_bRunning = true;
}
void vtFrame::UpdateStatusText()
{
if (!GetStatusBar())
return;
vtScene *scene = vtGetScene();
if (!scene)
return;
// get framerate
float fps = scene->GetFrameRate();
// get camera distance
float dist = 0;
if (NULL != wxGetApp().m_pTrackball)
dist = wxGetApp().m_pTrackball->GetRadius();
wxString str;
str.Printf(_T("fps %.3g, camera distance %.2f meters"), fps, dist);
SetStatusText(str);
}
| 25.385066 | 91 | 0.701061 | nakijun |
cd24d16e13fdef4060d3fde1f6b9d7b22eaba84f | 1,521 | cpp | C++ | Sources/WebApp/AppFramework/SDL2Caches.cpp | kovacsv/VisualScriptEngineWeb | e7eb8089018969d691a4e47a92eea43e75bfb017 | [
"MIT"
] | 19 | 2020-08-01T14:52:21.000Z | 2022-03-27T01:09:59.000Z | Sources/WebApp/AppFramework/SDL2Caches.cpp | kovacsv/VisualScriptEngineWeb | e7eb8089018969d691a4e47a92eea43e75bfb017 | [
"MIT"
] | 17 | 2020-08-14T15:03:07.000Z | 2020-09-24T17:08:52.000Z | Sources/WebApp/AppFramework/SDL2Caches.cpp | kovacsv/VisualScriptEngineWeb | e7eb8089018969d691a4e47a92eea43e75bfb017 | [
"MIT"
] | null | null | null | #include "SDL2Caches.hpp"
#include "NE_StringUtils.hpp"
FontTextureCacheKey::FontTextureCacheKey (const std::wstring& text, const NUIE::ColorCacheKey& color, int size) :
text (text),
color (color),
size (size)
{
}
bool FontTextureCacheKey::operator== (const FontTextureCacheKey& rhs) const
{
return text == rhs.text && color == rhs.color && size == rhs.size;
}
bool FontTextureCacheKey::operator!= (const FontTextureCacheKey& rhs) const
{
return !operator== (rhs);
}
FontController::FontController (const std::string& fontPath) :
FontCache::Controller (),
fontPath (fontPath)
{
}
TTF_Font* FontController::CreateValue (const int& key)
{
return TTF_OpenFont (fontPath.c_str (), key);
}
void FontController::DisposeValue (TTF_Font*& value)
{
TTF_CloseFont (value);
}
FontTextureController::FontTextureController (SDL_Renderer* renderer, FontCache& fontCache) :
FontTextureCache::Controller (),
renderer (renderer),
fontCache (fontCache)
{
}
SDL_Texture* FontTextureController::CreateValue (const FontTextureCacheKey& key)
{
TTF_Font* ttfFont = fontCache.Get (key.size);
std::string textStr = NE::WStringToString (key.text);
SDL_Color sdlColor = { key.color.r, key.color.g, key.color.b, 255 };
SDL_Surface* surface = TTF_RenderUTF8_Blended (ttfFont, textStr.c_str (), sdlColor);
SDL_Texture* texture = SDL_CreateTextureFromSurface (renderer, surface);
SDL_FreeSurface (surface);
return texture;
}
void FontTextureController::DisposeValue (SDL_Texture*& value)
{
SDL_DestroyTexture (value);
}
| 24.532258 | 113 | 0.748849 | kovacsv |
cd26e8480f16b32070d2ad7407364896f7a40aa1 | 2,308 | cpp | C++ | src/AdventOfCode2020/Day23-CrabCups/Day23-CrabCups.cpp | dbartok/advent-of-code-cpp | c8c2df7a21980f8f3e42128f7bc5df8288f18490 | [
"MIT"
] | null | null | null | src/AdventOfCode2020/Day23-CrabCups/Day23-CrabCups.cpp | dbartok/advent-of-code-cpp | c8c2df7a21980f8f3e42128f7bc5df8288f18490 | [
"MIT"
] | null | null | null | src/AdventOfCode2020/Day23-CrabCups/Day23-CrabCups.cpp | dbartok/advent-of-code-cpp | c8c2df7a21980f8f3e42128f7bc5df8288f18490 | [
"MIT"
] | null | null | null | #include "Day23-CrabCups.h"
#include "CupMixer.h"
#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>
__BEGIN_LIBRARIES_DISABLE_WARNINGS
#include <vector>
#include <algorithm>
#include <numeric>
__END_LIBRARIES_DISABLE_WARNINGS
namespace
{
size_t MANY_CUPS_NUMBER = 1'000'000;
}
namespace AdventOfCode
{
namespace Year2020
{
namespace Day23
{
std::vector<size_t> convertStringToDigitwiseVector(const std::string& str)
{
std::vector<size_t> digitwiseVector;
std::transform(str.cbegin(), str.cend(), std::back_inserter(digitwiseVector), [](char c)
{
return c - '0';
});
return digitwiseVector;
}
std::string convertDigitwiseVectorToString(const std::vector<size_t>& digitwiseVector)
{
std::string result;
std::transform(digitwiseVector.cbegin(), digitwiseVector.cend(), std::back_inserter(result), [](size_t digit)
{
return digit + '0';
});
return result;
}
void addPaddingToInitialCups(std::vector<Cup>& cups)
{
const size_t numPaddingCupsRequired = MANY_CUPS_NUMBER - cups.size();
std::vector<Cup> paddingCups(numPaddingCupsRequired);
const size_t firstPaddingCup = cups.size() + 1;
std::iota(paddingCups.begin(), paddingCups.end(), firstPaddingCup);
cups.insert(cups.end(), std::make_move_iterator(paddingCups.cbegin()), std::make_move_iterator(paddingCups.cend()));
}
std::string cupLabelsStartingFromCupOne(const std::string& initialCupLabellingString, size_t numMixes)
{
std::vector<Cup> initialCups = convertStringToDigitwiseVector(initialCupLabellingString);
CupMixer cupMixer{std::move(initialCups)};
cupMixer.mixRepeatedly(numMixes);
std::vector<Cup> labelsOnCupsAfterCupOne = cupMixer.getLabelsOnCupsAfterCupOne();
return convertDigitwiseVectorToString(labelsOnCupsAfterCupOne);
}
int64_t twoCupLabelsAfterCupOneMultipliedManyCups(const std::string& initialCupLabellingString, size_t numMixes)
{
std::vector<Cup> initialCups = convertStringToDigitwiseVector(initialCupLabellingString);
addPaddingToInitialCups(initialCups);
CupMixer cupMixer{std::move(initialCups)};
cupMixer.mixRepeatedly(numMixes);
return cupMixer.getTwoCupLabelsAfterCupOneMultiplied();
}
}
}
}
| 27.807229 | 120 | 0.727903 | dbartok |
cd27753b2c2eb1db41ed81d13b6cccb941eaa480 | 52,967 | cpp | C++ | src/OpenGL/common/Image.cpp | aswimmingfish/swiftshader | dc7759ccc3151a1aefefa9f86610e66f6fe9311c | [
"Apache-2.0"
] | 1 | 2020-09-29T03:14:19.000Z | 2020-09-29T03:14:19.000Z | src/OpenGL/common/Image.cpp | longde123/SwiftShader | 2ddef8858e5015140f374d5c06d1a68b7c78af10 | [
"Apache-2.0"
] | null | null | null | src/OpenGL/common/Image.cpp | longde123/SwiftShader | 2ddef8858e5015140f374d5c06d1a68b7c78af10 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 The SwiftShader 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 "Image.hpp"
#include "Renderer/Blitter.hpp"
#include "../libEGL/Texture.hpp"
#include "../common/debug.h"
#include "Common/Math.hpp"
#include "Common/Thread.hpp"
#include <GLES3/gl3.h>
#include <string.h>
namespace
{
int getNumBlocks(int w, int h, int blockSizeX, int blockSizeY)
{
return ((w + blockSizeX - 1) / blockSizeX) * ((h + blockSizeY - 1) / blockSizeY);
}
enum DataType
{
Bytes_1,
Bytes_2,
Bytes_4,
Bytes_8,
Bytes_16,
ByteRGB,
UByteRGB,
ShortRGB,
UShortRGB,
IntRGB,
UIntRGB,
RGB565,
FloatRGB,
HalfFloatRGB,
RGBA4444,
RGBA5551,
RGB10A2UI,
R11G11B10F,
RGB9E5,
SRGB,
SRGBA,
D16,
D24,
D32,
D32F,
S8,
S24_8,
};
template<DataType dataType>
void LoadImageRow(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
UNIMPLEMENTED();
}
template<>
void LoadImageRow<Bytes_1>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset, source, width);
}
template<>
void LoadImageRow<Bytes_2>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset * 2, source, width * 2);
}
template<>
void LoadImageRow<Bytes_4>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset * 4, source, width * 4);
}
template<>
void LoadImageRow<Bytes_8>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset * 8, source, width * 8);
}
template<>
void LoadImageRow<Bytes_16>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset * 16, source, width * 16);
}
template<>
void LoadImageRow<ByteRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
unsigned char *destB = dest + xoffset * 4;
for(int x = 0; x < width; x++)
{
destB[4 * x + 0] = source[x * 3 + 0];
destB[4 * x + 1] = source[x * 3 + 1];
destB[4 * x + 2] = source[x * 3 + 2];
destB[4 * x + 3] = 0x7F;
}
}
template<>
void LoadImageRow<UByteRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
unsigned char *destB = dest + xoffset * 4;
for(int x = 0; x < width; x++)
{
destB[4 * x + 0] = source[x * 3 + 0];
destB[4 * x + 1] = source[x * 3 + 1];
destB[4 * x + 2] = source[x * 3 + 2];
destB[4 * x + 3] = 0xFF;
}
}
template<>
void LoadImageRow<ShortRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *sourceS = reinterpret_cast<const unsigned short*>(source);
unsigned short *destS = reinterpret_cast<unsigned short*>(dest + xoffset * 8);
for(int x = 0; x < width; x++)
{
destS[4 * x + 0] = sourceS[x * 3 + 0];
destS[4 * x + 1] = sourceS[x * 3 + 1];
destS[4 * x + 2] = sourceS[x * 3 + 2];
destS[4 * x + 3] = 0x7FFF;
}
}
template<>
void LoadImageRow<UShortRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *sourceS = reinterpret_cast<const unsigned short*>(source);
unsigned short *destS = reinterpret_cast<unsigned short*>(dest + xoffset * 8);
for(int x = 0; x < width; x++)
{
destS[4 * x + 0] = sourceS[x * 3 + 0];
destS[4 * x + 1] = sourceS[x * 3 + 1];
destS[4 * x + 2] = sourceS[x * 3 + 2];
destS[4 * x + 3] = 0xFFFF;
}
}
template<>
void LoadImageRow<IntRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *sourceI = reinterpret_cast<const unsigned int*>(source);
unsigned int *destI = reinterpret_cast<unsigned int*>(dest + xoffset * 16);
for(int x = 0; x < width; x++)
{
destI[4 * x + 0] = sourceI[x * 3 + 0];
destI[4 * x + 1] = sourceI[x * 3 + 1];
destI[4 * x + 2] = sourceI[x * 3 + 2];
destI[4 * x + 3] = 0x7FFFFFFF;
}
}
template<>
void LoadImageRow<UIntRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *sourceI = reinterpret_cast<const unsigned int*>(source);
unsigned int *destI = reinterpret_cast<unsigned int*>(dest + xoffset * 16);
for(int x = 0; x < width; x++)
{
destI[4 * x + 0] = sourceI[x * 3 + 0];
destI[4 * x + 1] = sourceI[x * 3 + 1];
destI[4 * x + 2] = sourceI[x * 3 + 2];
destI[4 * x + 3] = 0xFFFFFFFF;
}
}
template<>
void LoadImageRow<RGB565>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset * 2, source, width * 2);
}
template<>
void LoadImageRow<FloatRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const float *sourceF = reinterpret_cast<const float*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 16);
for(int x = 0; x < width; x++)
{
destF[4 * x + 0] = sourceF[x * 3 + 0];
destF[4 * x + 1] = sourceF[x * 3 + 1];
destF[4 * x + 2] = sourceF[x * 3 + 2];
destF[4 * x + 3] = 1.0f;
}
}
template<>
void LoadImageRow<HalfFloatRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *sourceH = reinterpret_cast<const unsigned short*>(source);
unsigned short *destH = reinterpret_cast<unsigned short*>(dest + xoffset * 8);
for(int x = 0; x < width; x++)
{
destH[4 * x + 0] = sourceH[x * 3 + 0];
destH[4 * x + 1] = sourceH[x * 3 + 1];
destH[4 * x + 2] = sourceH[x * 3 + 2];
destH[4 * x + 3] = 0x3C00; // SEEEEEMMMMMMMMMM, S = 0, E = 15, M = 0: 16bit flpt representation of 1
}
}
template<>
void LoadImageRow<RGBA4444>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *source4444 = reinterpret_cast<const unsigned short*>(source);
unsigned char *dest4444 = dest + xoffset * 4;
for(int x = 0; x < width; x++)
{
unsigned short rgba = source4444[x];
dest4444[4 * x + 0] = ((rgba & 0x00F0) << 0) | ((rgba & 0x00F0) >> 4);
dest4444[4 * x + 1] = ((rgba & 0x0F00) >> 4) | ((rgba & 0x0F00) >> 8);
dest4444[4 * x + 2] = ((rgba & 0xF000) >> 8) | ((rgba & 0xF000) >> 12);
dest4444[4 * x + 3] = ((rgba & 0x000F) << 4) | ((rgba & 0x000F) >> 0);
}
}
template<>
void LoadImageRow<RGBA5551>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *source5551 = reinterpret_cast<const unsigned short*>(source);
unsigned char *dest5551 = dest + xoffset * 4;
for(int x = 0; x < width; x++)
{
unsigned short rgba = source5551[x];
dest5551[4 * x + 0] = ((rgba & 0x003E) << 2) | ((rgba & 0x003E) >> 3);
dest5551[4 * x + 1] = ((rgba & 0x07C0) >> 3) | ((rgba & 0x07C0) >> 8);
dest5551[4 * x + 2] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
dest5551[4 * x + 3] = (rgba & 0x0001) ? 0xFF : 0;
}
}
template<>
void LoadImageRow<RGB10A2UI>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *source1010102U = reinterpret_cast<const unsigned int*>(source);
unsigned short *dest16U = reinterpret_cast<unsigned short*>(dest + xoffset * 8);
for(int x = 0; x < width; x++)
{
unsigned int rgba = source1010102U[x];
dest16U[4 * x + 0] = (rgba & 0x00000FFC) >> 2;
dest16U[4 * x + 1] = (rgba & 0x003FF000) >> 12;
dest16U[4 * x + 2] = (rgba & 0xFFC00000) >> 22;
dest16U[4 * x + 3] = (rgba & 0x00000003);
}
}
template<>
void LoadImageRow<R11G11B10F>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const sw::R11G11B10FData *sourceRGB = reinterpret_cast<const sw::R11G11B10FData*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 16);
for(int x = 0; x < width; x++, sourceRGB++, destF+=4)
{
sourceRGB->toRGBFloats(destF);
destF[3] = 1.0f;
}
}
template<>
void LoadImageRow<RGB9E5>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const sw::RGB9E5Data *sourceRGB = reinterpret_cast<const sw::RGB9E5Data*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 16);
for(int x = 0; x < width; x++, sourceRGB++, destF += 4)
{
sourceRGB->toRGBFloats(destF);
destF[3] = 1.0f;
}
}
template<>
void LoadImageRow<SRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
dest += xoffset * 4;
for(int x = 0; x < width; x++)
{
for(int rgb = 0; rgb < 3; ++rgb)
{
*dest++ = sw::sRGB8toLinear8(*source++);
}
*dest++ = 255;
}
}
template<>
void LoadImageRow<SRGBA>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
dest += xoffset * 4;
for(int x = 0; x < width; x++)
{
for(int rgb = 0; rgb < 3; ++rgb)
{
*dest++ = sw::sRGB8toLinear8(*source++);
}
*dest++ = *source++;
}
}
template<>
void LoadImageRow<D16>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *sourceD16 = reinterpret_cast<const unsigned short*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 4);
for(int x = 0; x < width; x++)
{
destF[x] = (float)sourceD16[x] / 0xFFFF;
}
}
template<>
void LoadImageRow<D24>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *sourceD24 = reinterpret_cast<const unsigned int*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 4);
for(int x = 0; x < width; x++)
{
destF[x] = (float)(sourceD24[x] & 0xFFFFFF00) / 0xFFFFFF00;
}
}
template<>
void LoadImageRow<D32>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *sourceD32 = reinterpret_cast<const unsigned int*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 4);
for(int x = 0; x < width; x++)
{
destF[x] = (float)sourceD32[x] / 0xFFFFFFFF;
}
}
template<>
void LoadImageRow<S8>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *sourceI = reinterpret_cast<const unsigned int*>(source);
unsigned char *destI = dest + xoffset;
for(int x = 0; x < width; x++)
{
destI[x] = static_cast<unsigned char>(sourceI[x] & 0x000000FF); // FIXME: Quad layout
}
}
template<>
void LoadImageRow<D32F>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
struct D32FS8 { float depth32f; unsigned int stencil24_8; };
const D32FS8 *sourceD32FS8 = reinterpret_cast<const D32FS8*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 4);
for(int x = 0; x < width; x++)
{
destF[x] = sourceD32FS8[x].depth32f;
}
}
template<>
void LoadImageRow<S24_8>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
struct D32FS8 { float depth32f; unsigned int stencil24_8; };
const D32FS8 *sourceD32FS8 = reinterpret_cast<const D32FS8*>(source);
unsigned char *destI = dest + xoffset;
for(int x = 0; x < width; x++)
{
destI[x] = static_cast<unsigned char>(sourceD32FS8[x].stencil24_8 & 0x000000FF); // FIXME: Quad layout
}
}
template<DataType dataType>
void LoadImageData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, int inputPitch, int inputHeight, int destPitch, GLsizei destHeight, const void *input, void *buffer)
{
for(int z = 0; z < depth; ++z)
{
const unsigned char *inputStart = static_cast<const unsigned char*>(input) + (z * inputPitch * inputHeight);
unsigned char *destStart = static_cast<unsigned char*>(buffer) + ((zoffset + z) * destPitch * destHeight);
for(int y = 0; y < height; ++y)
{
const unsigned char *source = inputStart + y * inputPitch;
unsigned char *dest = destStart + (y + yoffset) * destPitch;
LoadImageRow<dataType>(source, dest, xoffset, width);
}
}
}
}
namespace egl
{
sw::Format ConvertFormatType(GLenum format, GLenum type)
{
switch(format)
{
case GL_LUMINANCE:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_L8;
case GL_HALF_FLOAT: return sw::FORMAT_L16F;
case GL_HALF_FLOAT_OES: return sw::FORMAT_L16F;
case GL_FLOAT: return sw::FORMAT_L32F;
default: UNREACHABLE(type);
}
break;
case GL_LUMINANCE8_EXT:
return sw::FORMAT_L8;
case GL_LUMINANCE16F_EXT:
return sw::FORMAT_L16F;
case GL_LUMINANCE32F_EXT:
return sw::FORMAT_L32F;
case GL_LUMINANCE_ALPHA:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_A8L8;
case GL_HALF_FLOAT: return sw::FORMAT_A16L16F;
case GL_HALF_FLOAT_OES: return sw::FORMAT_A16L16F;
case GL_FLOAT: return sw::FORMAT_A32L32F;
default: UNREACHABLE(type);
}
break;
case GL_LUMINANCE8_ALPHA8_EXT:
return sw::FORMAT_A8L8;
case GL_LUMINANCE_ALPHA16F_EXT:
return sw::FORMAT_A16L16F;
case GL_LUMINANCE_ALPHA32F_EXT:
return sw::FORMAT_A32L32F;
case GL_RGBA:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_A8B8G8R8;
case GL_UNSIGNED_SHORT_4_4_4_4: return sw::FORMAT_R4G4B4A4;
case GL_UNSIGNED_SHORT_5_5_5_1: return sw::FORMAT_R5G5B5A1;
case GL_HALF_FLOAT: return sw::FORMAT_A16B16G16R16F;
case GL_HALF_FLOAT_OES: return sw::FORMAT_A16B16G16R16F;
case GL_FLOAT: return sw::FORMAT_A32B32G32R32F;
default: UNREACHABLE(type);
}
break;
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_A8R8G8B8;
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT: return sw::FORMAT_A4R4G4B4;
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT: return sw::FORMAT_A1R5G5B5;
default: UNREACHABLE(type);
}
break;
case GL_RGB:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_B8G8R8;
case GL_UNSIGNED_SHORT_5_6_5: return sw::FORMAT_R5G6B5;
case GL_HALF_FLOAT: return sw::FORMAT_B16G16R16F;
case GL_HALF_FLOAT_OES: return sw::FORMAT_B16G16R16F;
case GL_FLOAT: return sw::FORMAT_B32G32R32F;
default: UNREACHABLE(type);
}
break;
case GL_ALPHA:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_A8;
case GL_HALF_FLOAT: return sw::FORMAT_A16F;
case GL_HALF_FLOAT_OES: return sw::FORMAT_A16F;
case GL_FLOAT: return sw::FORMAT_A32F;
default: UNREACHABLE(type);
}
break;
case GL_ALPHA8_EXT:
return sw::FORMAT_A8;
case GL_ALPHA16F_EXT:
return sw::FORMAT_A16F;
case GL_ALPHA32F_EXT:
return sw::FORMAT_A32F;
case GL_RED_INTEGER:
switch(type)
{
case GL_INT: return sw::FORMAT_R32I;
case GL_UNSIGNED_INT: return sw::FORMAT_R32UI;
default: UNREACHABLE(type);
}
break;
case GL_RG_INTEGER:
switch(type)
{
case GL_INT: return sw::FORMAT_G32R32I;
case GL_UNSIGNED_INT: return sw::FORMAT_G32R32UI;
default: UNREACHABLE(type);
}
break;
case GL_RGBA_INTEGER:
switch(type)
{
case GL_INT: return sw::FORMAT_A32B32G32R32I;
case GL_UNSIGNED_INT: return sw::FORMAT_A32B32G32R32UI;
default: UNREACHABLE(type);
}
break;
case GL_DEPTH_COMPONENT:
switch(type)
{
case GL_UNSIGNED_SHORT: return sw::FORMAT_D16;
case GL_UNSIGNED_INT_24_8_OES: return sw::FORMAT_D24S8;
case GL_UNSIGNED_INT: return sw::FORMAT_D32;
case GL_FLOAT: return sw::FORMAT_D32F;
default: UNREACHABLE(type);
}
break;
default:
UNREACHABLE(format);
}
return sw::FORMAT_NULL;
}
sw::Format SelectInternalFormat(GLenum format, GLenum type)
{
switch(format)
{
case GL_ETC1_RGB8_OES:
return sw::FORMAT_ETC1;
case GL_COMPRESSED_R11_EAC:
return sw::FORMAT_R11_EAC;
case GL_COMPRESSED_SIGNED_R11_EAC:
return sw::FORMAT_SIGNED_R11_EAC;
case GL_COMPRESSED_RG11_EAC:
return sw::FORMAT_RG11_EAC;
case GL_COMPRESSED_SIGNED_RG11_EAC:
return sw::FORMAT_SIGNED_RG11_EAC;
case GL_COMPRESSED_RGB8_ETC2:
return sw::FORMAT_RGB8_ETC2;
case GL_COMPRESSED_SRGB8_ETC2:
return sw::FORMAT_SRGB8_ETC2;
case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
return sw::FORMAT_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
return sw::FORMAT_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GL_COMPRESSED_RGBA8_ETC2_EAC:
return sw::FORMAT_RGBA8_ETC2_EAC;
case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
return sw::FORMAT_SRGB8_ALPHA8_ETC2_EAC;
case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:
return sw::FORMAT_RGBA_ASTC_4x4_KHR;
case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:
return sw::FORMAT_RGBA_ASTC_5x4_KHR;
case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:
return sw::FORMAT_RGBA_ASTC_5x5_KHR;
case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:
return sw::FORMAT_RGBA_ASTC_6x5_KHR;
case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:
return sw::FORMAT_RGBA_ASTC_6x6_KHR;
case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:
return sw::FORMAT_RGBA_ASTC_8x5_KHR;
case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:
return sw::FORMAT_RGBA_ASTC_8x6_KHR;
case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:
return sw::FORMAT_RGBA_ASTC_8x8_KHR;
case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:
return sw::FORMAT_RGBA_ASTC_10x5_KHR;
case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:
return sw::FORMAT_RGBA_ASTC_10x6_KHR;
case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:
return sw::FORMAT_RGBA_ASTC_10x8_KHR;
case GL_COMPRESSED_RGBA_ASTC_10x10_KHR:
return sw::FORMAT_RGBA_ASTC_10x10_KHR;
case GL_COMPRESSED_RGBA_ASTC_12x10_KHR:
return sw::FORMAT_RGBA_ASTC_12x10_KHR;
case GL_COMPRESSED_RGBA_ASTC_12x12_KHR:
return sw::FORMAT_RGBA_ASTC_12x12_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_4x4_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_5x4_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_5x5_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_6x5_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_6x6_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_8x5_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_8x6_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_8x8_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x5_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x6_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x8_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x10_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_12x10_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_12x12_KHR;
#if S3TC_SUPPORT
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return sw::FORMAT_DXT1;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
return sw::FORMAT_DXT3;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
return sw::FORMAT_DXT5;
#endif
default:
break;
}
switch(type)
{
case GL_FLOAT:
switch(format)
{
case GL_ALPHA:
case GL_ALPHA32F_EXT:
return sw::FORMAT_A32F;
case GL_LUMINANCE:
case GL_LUMINANCE32F_EXT:
return sw::FORMAT_L32F;
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE_ALPHA32F_EXT:
return sw::FORMAT_A32L32F;
case GL_RED:
case GL_R32F:
return sw::FORMAT_R32F;
case GL_RG:
case GL_RG32F:
return sw::FORMAT_G32R32F;
case GL_RGB:
case GL_RGB32F:
return sw::FORMAT_X32B32G32R32F;
case GL_RGBA:
case GL_RGBA32F:
return sw::FORMAT_A32B32G32R32F;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT32F:
return sw::FORMAT_D32F;
default:
UNREACHABLE(format);
}
case GL_HALF_FLOAT:
case GL_HALF_FLOAT_OES:
switch(format)
{
case GL_ALPHA:
case GL_ALPHA16F_EXT:
return sw::FORMAT_A16F;
case GL_LUMINANCE:
case GL_LUMINANCE16F_EXT:
return sw::FORMAT_L16F;
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE_ALPHA16F_EXT:
return sw::FORMAT_A16L16F;
case GL_RED:
case GL_R16F:
return sw::FORMAT_R16F;
case GL_RG:
case GL_RG16F:
return sw::FORMAT_G16R16F;
case GL_RGB:
case GL_RGB16F:
case GL_RGBA:
case GL_RGBA16F:
return sw::FORMAT_A16B16G16R16F;
default:
UNREACHABLE(format);
}
case GL_BYTE:
switch(format)
{
case GL_R8_SNORM:
case GL_R8:
case GL_RED:
return sw::FORMAT_R8I_SNORM;
case GL_R8I:
case GL_RED_INTEGER:
return sw::FORMAT_R8I;
case GL_RG8_SNORM:
case GL_RG8:
case GL_RG:
return sw::FORMAT_G8R8I_SNORM;
case GL_RG8I:
case GL_RG_INTEGER:
return sw::FORMAT_G8R8I;
case GL_RGB8_SNORM:
case GL_RGB8:
case GL_RGB:
return sw::FORMAT_X8B8G8R8I_SNORM;
case GL_RGB8I:
case GL_RGB_INTEGER:
return sw::FORMAT_X8B8G8R8I;
case GL_RGBA8_SNORM:
case GL_RGBA8:
case GL_RGBA:
return sw::FORMAT_A8B8G8R8I_SNORM;
case GL_RGBA8I:
case GL_RGBA_INTEGER:
return sw::FORMAT_A8B8G8R8I;
default:
UNREACHABLE(format);
}
case GL_UNSIGNED_BYTE:
switch(format)
{
case GL_LUMINANCE:
case GL_LUMINANCE8_EXT:
return sw::FORMAT_L8;
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE8_ALPHA8_EXT:
return sw::FORMAT_A8L8;
case GL_R8_SNORM:
case GL_R8:
case GL_RED:
return sw::FORMAT_R8;
case GL_R8UI:
case GL_RED_INTEGER:
return sw::FORMAT_R8UI;
case GL_RG8_SNORM:
case GL_RG8:
case GL_RG:
return sw::FORMAT_G8R8;
case GL_RG8UI:
case GL_RG_INTEGER:
return sw::FORMAT_G8R8UI;
case GL_RGB8_SNORM:
case GL_RGB8:
case GL_RGB:
case GL_SRGB8:
return sw::FORMAT_X8B8G8R8;
case GL_RGB8UI:
case GL_RGB_INTEGER:
return sw::FORMAT_X8B8G8R8UI;
case GL_RGBA8_SNORM:
case GL_RGBA8:
case GL_RGBA:
case GL_SRGB8_ALPHA8:
return sw::FORMAT_A8B8G8R8;
case GL_RGBA8UI:
case GL_RGBA_INTEGER:
return sw::FORMAT_A8B8G8R8UI;
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
return sw::FORMAT_A8R8G8B8;
case GL_ALPHA:
case GL_ALPHA8_EXT:
return sw::FORMAT_A8;
case SW_YV12_BT601:
return sw::FORMAT_YV12_BT601;
case SW_YV12_BT709:
return sw::FORMAT_YV12_BT709;
case SW_YV12_JFIF:
return sw::FORMAT_YV12_JFIF;
default:
UNREACHABLE(format);
}
case GL_SHORT:
switch(format)
{
case GL_R16I:
case GL_RED_INTEGER:
return sw::FORMAT_R16I;
case GL_RG16I:
case GL_RG_INTEGER:
return sw::FORMAT_G16R16I;
case GL_RGB16I:
case GL_RGB_INTEGER:
return sw::FORMAT_X16B16G16R16I;
case GL_RGBA16I:
case GL_RGBA_INTEGER:
return sw::FORMAT_A16B16G16R16I;
default:
UNREACHABLE(format);
}
case GL_UNSIGNED_SHORT:
switch(format)
{
case GL_R16UI:
case GL_RED_INTEGER:
return sw::FORMAT_R16UI;
case GL_RG16UI:
case GL_RG_INTEGER:
return sw::FORMAT_G16R16UI;
case GL_RGB16UI:
case GL_RGB_INTEGER:
return sw::FORMAT_X16B16G16R16UI;
case GL_RGBA16UI:
case GL_RGBA_INTEGER:
return sw::FORMAT_A16B16G16R16UI;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT16:
return sw::FORMAT_D32FS8_TEXTURE;
default:
UNREACHABLE(format);
}
case GL_INT:
switch(format)
{
case GL_RED_INTEGER:
case GL_R32I:
return sw::FORMAT_R32I;
case GL_RG_INTEGER:
case GL_RG32I:
return sw::FORMAT_G32R32I;
case GL_RGB_INTEGER:
case GL_RGB32I:
return sw::FORMAT_X32B32G32R32I;
case GL_RGBA_INTEGER:
case GL_RGBA32I:
return sw::FORMAT_A32B32G32R32I;
default:
UNREACHABLE(format);
}
case GL_UNSIGNED_INT:
switch(format)
{
case GL_RED_INTEGER:
case GL_R32UI:
return sw::FORMAT_R32UI;
case GL_RG_INTEGER:
case GL_RG32UI:
return sw::FORMAT_G32R32UI;
case GL_RGB_INTEGER:
case GL_RGB32UI:
return sw::FORMAT_X32B32G32R32UI;
case GL_RGBA_INTEGER:
case GL_RGBA32UI:
return sw::FORMAT_A32B32G32R32UI;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32_OES:
return sw::FORMAT_D32FS8_TEXTURE;
default:
UNREACHABLE(format);
}
case GL_UNSIGNED_INT_24_8_OES:
if(format == GL_DEPTH_STENCIL || format == GL_DEPTH24_STENCIL8)
{
return sw::FORMAT_D32FS8_TEXTURE;
}
else UNREACHABLE(format);
case GL_FLOAT_32_UNSIGNED_INT_24_8_REV:
if(format == GL_DEPTH_STENCIL || format == GL_DEPTH32F_STENCIL8)
{
return sw::FORMAT_D32FS8_TEXTURE;
}
else UNREACHABLE(format);
case GL_UNSIGNED_SHORT_4_4_4_4:
return sw::FORMAT_A8R8G8B8;
case GL_UNSIGNED_SHORT_5_5_5_1:
return sw::FORMAT_A8R8G8B8;
case GL_UNSIGNED_SHORT_5_6_5:
return sw::FORMAT_R5G6B5;
case GL_UNSIGNED_INT_2_10_10_10_REV:
if(format == GL_RGB10_A2UI)
{
return sw::FORMAT_A16B16G16R16UI;
}
else
{
return sw::FORMAT_A2B10G10R10;
}
case GL_UNSIGNED_INT_10F_11F_11F_REV:
case GL_UNSIGNED_INT_5_9_9_9_REV:
return sw::FORMAT_A32B32G32R32F;
default:
UNREACHABLE(type);
}
return sw::FORMAT_NULL;
}
// Returns the size, in bytes, of a single texel in an Image
static int ComputePixelSize(GLenum format, GLenum type)
{
switch(type)
{
case GL_BYTE:
switch(format)
{
case GL_R8:
case GL_R8I:
case GL_R8_SNORM:
case GL_RED: return sizeof(char);
case GL_RED_INTEGER: return sizeof(char);
case GL_RG8:
case GL_RG8I:
case GL_RG8_SNORM:
case GL_RG: return sizeof(char) * 2;
case GL_RG_INTEGER: return sizeof(char) * 2;
case GL_RGB8:
case GL_RGB8I:
case GL_RGB8_SNORM:
case GL_RGB: return sizeof(char) * 3;
case GL_RGB_INTEGER: return sizeof(char) * 3;
case GL_RGBA8:
case GL_RGBA8I:
case GL_RGBA8_SNORM:
case GL_RGBA: return sizeof(char) * 4;
case GL_RGBA_INTEGER: return sizeof(char) * 4;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_BYTE:
switch(format)
{
case GL_R8:
case GL_R8UI:
case GL_RED: return sizeof(unsigned char);
case GL_RED_INTEGER: return sizeof(unsigned char);
case GL_ALPHA8_EXT:
case GL_ALPHA: return sizeof(unsigned char);
case GL_LUMINANCE8_EXT:
case GL_LUMINANCE: return sizeof(unsigned char);
case GL_LUMINANCE8_ALPHA8_EXT:
case GL_LUMINANCE_ALPHA: return sizeof(unsigned char) * 2;
case GL_RG8:
case GL_RG8UI:
case GL_RG: return sizeof(unsigned char) * 2;
case GL_RG_INTEGER: return sizeof(unsigned char) * 2;
case GL_RGB8:
case GL_RGB8UI:
case GL_SRGB8:
case GL_RGB: return sizeof(unsigned char) * 3;
case GL_RGB_INTEGER: return sizeof(unsigned char) * 3;
case GL_RGBA8:
case GL_RGBA8UI:
case GL_SRGB8_ALPHA8:
case GL_RGBA: return sizeof(unsigned char) * 4;
case GL_RGBA_INTEGER: return sizeof(unsigned char) * 4;
case GL_BGRA_EXT:
case GL_BGRA8_EXT: return sizeof(unsigned char)* 4;
default: UNREACHABLE(format);
}
break;
case GL_SHORT:
switch(format)
{
case GL_R16I:
case GL_RED_INTEGER: return sizeof(short);
case GL_RG16I:
case GL_RG_INTEGER: return sizeof(short) * 2;
case GL_RGB16I:
case GL_RGB_INTEGER: return sizeof(short) * 3;
case GL_RGBA16I:
case GL_RGBA_INTEGER: return sizeof(short) * 4;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT:
switch(format)
{
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT: return sizeof(unsigned short);
case GL_R16UI:
case GL_RED_INTEGER: return sizeof(unsigned short);
case GL_RG16UI:
case GL_RG_INTEGER: return sizeof(unsigned short) * 2;
case GL_RGB16UI:
case GL_RGB_INTEGER: return sizeof(unsigned short) * 3;
case GL_RGBA16UI:
case GL_RGBA_INTEGER: return sizeof(unsigned short) * 4;
default: UNREACHABLE(format);
}
break;
case GL_INT:
switch(format)
{
case GL_R32I:
case GL_RED_INTEGER: return sizeof(int);
case GL_RG32I:
case GL_RG_INTEGER: return sizeof(int) * 2;
case GL_RGB32I:
case GL_RGB_INTEGER: return sizeof(int) * 3;
case GL_RGBA32I:
case GL_RGBA_INTEGER: return sizeof(int) * 4;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT:
switch(format)
{
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32_OES:
case GL_DEPTH_COMPONENT: return sizeof(unsigned int);
case GL_R32UI:
case GL_RED_INTEGER: return sizeof(unsigned int);
case GL_RG32UI:
case GL_RG_INTEGER: return sizeof(unsigned int) * 2;
case GL_RGB32UI:
case GL_RGB_INTEGER: return sizeof(unsigned int) * 3;
case GL_RGBA32UI:
case GL_RGBA_INTEGER: return sizeof(unsigned int) * 4;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
case GL_UNSIGNED_SHORT_5_6_5:
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
return sizeof(unsigned short);
case GL_UNSIGNED_INT_10F_11F_11F_REV:
case GL_UNSIGNED_INT_5_9_9_9_REV:
case GL_UNSIGNED_INT_2_10_10_10_REV:
case GL_UNSIGNED_INT_24_8_OES:
return sizeof(unsigned int);
case GL_FLOAT_32_UNSIGNED_INT_24_8_REV:
return sizeof(float) + sizeof(unsigned int);
case GL_FLOAT:
switch(format)
{
case GL_DEPTH_COMPONENT32F:
case GL_DEPTH_COMPONENT: return sizeof(float);
case GL_ALPHA32F_EXT:
case GL_ALPHA: return sizeof(float);
case GL_LUMINANCE32F_EXT:
case GL_LUMINANCE: return sizeof(float);
case GL_LUMINANCE_ALPHA32F_EXT:
case GL_LUMINANCE_ALPHA: return sizeof(float) * 2;
case GL_RED: return sizeof(float);
case GL_R32F: return sizeof(float);
case GL_RG: return sizeof(float) * 2;
case GL_RG32F: return sizeof(float) * 2;
case GL_RGB: return sizeof(float) * 3;
case GL_RGB32F: return sizeof(float) * 3;
case GL_RGBA: return sizeof(float) * 4;
case GL_RGBA32F: return sizeof(float) * 4;
default: UNREACHABLE(format);
}
break;
case GL_HALF_FLOAT:
case GL_HALF_FLOAT_OES:
switch(format)
{
case GL_ALPHA16F_EXT:
case GL_ALPHA: return sizeof(unsigned short);
case GL_LUMINANCE16F_EXT:
case GL_LUMINANCE: return sizeof(unsigned short);
case GL_LUMINANCE_ALPHA16F_EXT:
case GL_LUMINANCE_ALPHA: return sizeof(unsigned short) * 2;
case GL_RED: return sizeof(unsigned short);
case GL_R16F: return sizeof(unsigned short);
case GL_RG: return sizeof(unsigned short) * 2;
case GL_RG16F: return sizeof(unsigned short) * 2;
case GL_RGB: return sizeof(unsigned short) * 3;
case GL_RGB16F: return sizeof(unsigned short) * 3;
case GL_RGBA: return sizeof(unsigned short) * 4;
case GL_RGBA16F: return sizeof(unsigned short) * 4;
default: UNREACHABLE(format);
}
break;
default: UNREACHABLE(type);
}
return 0;
}
GLsizei ComputePitch(GLsizei width, GLenum format, GLenum type, GLint alignment)
{
ASSERT(alignment > 0 && sw::isPow2(alignment));
GLsizei rawPitch = ComputePixelSize(format, type) * width;
return (rawPitch + alignment - 1) & ~(alignment - 1);
}
size_t ComputePackingOffset(GLenum format, GLenum type, GLsizei width, GLsizei height, GLint alignment, GLint skipImages, GLint skipRows, GLint skipPixels)
{
GLsizei pitchB = ComputePitch(width, format, type, alignment);
return (skipImages * height + skipRows) * pitchB + skipPixels * ComputePixelSize(format, type);
}
inline GLsizei ComputeCompressedPitch(GLsizei width, GLenum format)
{
return ComputeCompressedSize(width, 1, format);
}
GLsizei ComputeCompressedSize(GLsizei width, GLsizei height, GLenum format)
{
switch(format)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_ETC1_RGB8_OES:
case GL_COMPRESSED_R11_EAC:
case GL_COMPRESSED_SIGNED_R11_EAC:
case GL_COMPRESSED_RGB8_ETC2:
case GL_COMPRESSED_SRGB8_ETC2:
case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
case GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
return 8 * getNumBlocks(width, height, 4, 4);
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
case GL_COMPRESSED_RG11_EAC:
case GL_COMPRESSED_SIGNED_RG11_EAC:
case GL_COMPRESSED_RGBA8_ETC2_EAC:
case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
return 16 * getNumBlocks(width, height, 4, 4);
case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
return 16 * getNumBlocks(width, height, 5, 4);
case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
return 16 * getNumBlocks(width, height, 5, 5);
case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
return 16 * getNumBlocks(width, height, 6, 5);
case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
return 16 * getNumBlocks(width, height, 6, 6);
case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
return 16 * getNumBlocks(width, height, 8, 5);
case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
return 16 * getNumBlocks(width, height, 8, 6);
case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
return 16 * getNumBlocks(width, height, 8, 8);
case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
return 16 * getNumBlocks(width, height, 10, 5);
case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
return 16 * getNumBlocks(width, height, 10, 6);
case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
return 16 * getNumBlocks(width, height, 10, 8);
case GL_COMPRESSED_RGBA_ASTC_10x10_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
return 16 * getNumBlocks(width, height, 10, 10);
case GL_COMPRESSED_RGBA_ASTC_12x10_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
return 16 * getNumBlocks(width, height, 12, 10);
case GL_COMPRESSED_RGBA_ASTC_12x12_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
return 16 * getNumBlocks(width, height, 12, 12);
default:
return 0;
}
}
void Image::typeinfo() {}
Image::~Image()
{
if(parentTexture)
{
parentTexture->release();
}
ASSERT(!shared);
}
void Image::release()
{
int refs = dereference();
if(refs > 0)
{
if(parentTexture)
{
parentTexture->sweep();
}
}
else
{
delete this;
}
}
void Image::unbind(const egl::Texture *parent)
{
if(parentTexture == parent)
{
parentTexture = nullptr;
}
release();
}
bool Image::isChildOf(const egl::Texture *parent) const
{
return parentTexture == parent;
}
void Image::loadImageData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const UnpackInfo& unpackInfo, const void *input)
{
GLsizei inputWidth = (unpackInfo.rowLength == 0) ? width : unpackInfo.rowLength;
GLsizei inputPitch = ComputePitch(inputWidth, format, type, unpackInfo.alignment);
GLsizei inputHeight = (unpackInfo.imageHeight == 0) ? height : unpackInfo.imageHeight;
input = ((char*)input) + ComputePackingOffset(format, type, inputWidth, inputHeight, unpackInfo.alignment, unpackInfo.skipImages, unpackInfo.skipRows, unpackInfo.skipPixels);
sw::Format selectedInternalFormat = SelectInternalFormat(format, type);
if(selectedInternalFormat == sw::FORMAT_NULL)
{
return;
}
if(selectedInternalFormat == internalFormat)
{
void *buffer = lock(0, 0, sw::LOCK_WRITEONLY);
if(buffer)
{
switch(type)
{
case GL_BYTE:
switch(format)
{
case GL_R8:
case GL_R8I:
case GL_R8_SNORM:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_ALPHA8_EXT:
case GL_LUMINANCE:
case GL_LUMINANCE8_EXT:
LoadImageData<Bytes_1>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG8:
case GL_RG8I:
case GL_RG8_SNORM:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE8_ALPHA8_EXT:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB8:
case GL_RGB8I:
case GL_RGB8_SNORM:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<ByteRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA8:
case GL_RGBA8I:
case GL_RGBA8_SNORM:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_BYTE:
switch(format)
{
case GL_R8:
case GL_R8UI:
case GL_R8_SNORM:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_ALPHA8_EXT:
case GL_LUMINANCE:
case GL_LUMINANCE8_EXT:
LoadImageData<Bytes_1>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG8:
case GL_RG8UI:
case GL_RG8_SNORM:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE8_ALPHA8_EXT:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB8:
case GL_RGB8UI:
case GL_RGB8_SNORM:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<UByteRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA8:
case GL_RGBA8UI:
case GL_RGBA8_SNORM:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_SRGB8:
LoadImageData<SRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_SRGB8_ALPHA8:
LoadImageData<SRGBA>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT_5_6_5:
switch(format)
{
case GL_RGB565:
case GL_RGB:
LoadImageData<RGB565>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT_4_4_4_4:
switch(format)
{
case GL_RGBA4:
case GL_RGBA:
LoadImageData<RGBA4444>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT_5_5_5_1:
switch(format)
{
case GL_RGB5_A1:
case GL_RGBA:
LoadImageData<RGBA5551>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT_10F_11F_11F_REV:
switch(format)
{
case GL_R11F_G11F_B10F:
case GL_RGB:
LoadImageData<R11G11B10F>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT_5_9_9_9_REV:
switch(format)
{
case GL_RGB9_E5:
case GL_RGB:
LoadImageData<RGB9E5>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT_2_10_10_10_REV:
switch(format)
{
case GL_RGB10_A2UI:
LoadImageData<RGB10A2UI>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB10_A2:
case GL_RGBA:
case GL_RGBA_INTEGER:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_FLOAT:
switch(format)
{
// float textures are converted to RGBA, not BGRA
case GL_ALPHA:
case GL_ALPHA32F_EXT:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_LUMINANCE:
case GL_LUMINANCE32F_EXT:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE_ALPHA32F_EXT:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RED:
case GL_R32F:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG:
case GL_RG32F:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB:
case GL_RGB32F:
LoadImageData<FloatRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA:
case GL_RGBA32F:
LoadImageData<Bytes_16>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT32F:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_HALF_FLOAT:
case GL_HALF_FLOAT_OES:
switch(format)
{
case GL_ALPHA:
case GL_ALPHA16F_EXT:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_LUMINANCE:
case GL_LUMINANCE16F_EXT:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE_ALPHA16F_EXT:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RED:
case GL_R16F:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG:
case GL_RG16F:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB:
case GL_RGB16F:
LoadImageData<HalfFloatRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA:
case GL_RGBA16F:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_SHORT:
switch(format)
{
case GL_R16I:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_LUMINANCE:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG16I:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB16I:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<ShortRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA16I:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT:
switch(format)
{
case GL_R16UI:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_LUMINANCE:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG16UI:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB16UI:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<UShortRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA16UI:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT16:
LoadImageData<D16>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_INT:
switch(format)
{
case GL_R32I:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_LUMINANCE:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG32I:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB32I:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<IntRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA32I:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_16>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT:
switch(format)
{
case GL_R32UI:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_LUMINANCE:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG32UI:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB32UI:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<UIntRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA32UI:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_16>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32_OES:
case GL_DEPTH_COMPONENT:
LoadImageData<D32>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT_24_8_OES:
loadD24S8ImageData(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, input, buffer);
break;
case GL_FLOAT_32_UNSIGNED_INT_24_8_REV:
loadD32FS8ImageData(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, input, buffer);
break;
default: UNREACHABLE(type);
}
}
unlock();
}
else
{
sw::Surface source(width, height, depth, ConvertFormatType(format, type), const_cast<void*>(input), inputPitch, inputPitch * inputHeight);
sw::Rect sourceRect(0, 0, width, height);
sw::Rect destRect(xoffset, yoffset, xoffset + width, yoffset + height);
sw::blitter.blit(&source, sourceRect, this, destRect, false);
}
}
void Image::loadD24S8ImageData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, int inputPitch, int inputHeight, const void *input, void *buffer)
{
LoadImageData<D24>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
unsigned char *stencil = reinterpret_cast<unsigned char*>(lockStencil(0, 0, 0, sw::PUBLIC));
if(stencil)
{
LoadImageData<S8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getStencilPitchB(), getHeight(), input, stencil);
unlockStencil();
}
}
void Image::loadD32FS8ImageData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, int inputPitch, int inputHeight, const void *input, void *buffer)
{
LoadImageData<D32F>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
unsigned char *stencil = reinterpret_cast<unsigned char*>(lockStencil(0, 0, 0, sw::PUBLIC));
if(stencil)
{
LoadImageData<S24_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getStencilPitchB(), getHeight(), input, stencil);
unlockStencil();
}
}
void Image::loadCompressedData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei imageSize, const void *pixels)
{
if(zoffset != 0 || depth != 1)
{
UNIMPLEMENTED(); // FIXME
}
int inputPitch = ComputeCompressedPitch(width, format);
int rows = imageSize / inputPitch;
void *buffer = lock(xoffset, yoffset, sw::LOCK_WRITEONLY);
if(buffer)
{
for(int i = 0; i < rows; i++)
{
memcpy((void*)((GLbyte*)buffer + i * getPitch()), (void*)((GLbyte*)pixels + i * inputPitch), inputPitch);
}
}
unlock();
}
}
| 31.565554 | 211 | 0.693621 | aswimmingfish |
cd2fa4921c143259a4adcecca86c08b4d31061f4 | 337 | cpp | C++ | cEpiabm/src/dataclasses/household.cpp | Saketkr21/epiabm | 3ec0dcbc78d3fd4114ed3c6bdd78ef39f0013d2f | [
"BSD-3-Clause"
] | null | null | null | cEpiabm/src/dataclasses/household.cpp | Saketkr21/epiabm | 3ec0dcbc78d3fd4114ed3c6bdd78ef39f0013d2f | [
"BSD-3-Clause"
] | null | null | null | cEpiabm/src/dataclasses/household.cpp | Saketkr21/epiabm | 3ec0dcbc78d3fd4114ed3c6bdd78ef39f0013d2f | [
"BSD-3-Clause"
] | 1 | 2022-03-14T06:00:30.000Z | 2022-03-14T06:00:30.000Z |
#include "household.hpp"
namespace epiabm
{
Household::Household(size_t mcellPos) :
MembersInterface(mcellPos),
m_params(),
m_mcellPos(mcellPos)
{}
size_t Household::microcellPos() const { return m_mcellPos; }
HouseholdParams& Household::params() { return m_params; }
} // namespace epiabm
| 17.736842 | 65 | 0.661721 | Saketkr21 |
cd312e2187caf0c3593f1946fe944c2acd8e20ad | 3,745 | cc | C++ | lite/tests/kernels/sequence_pad_test.cc | winter-wang/Paddle-Lite | cd09ad060a0d7f20f55c4d6951ca95be75dc2c9c | [
"Apache-2.0"
] | 6 | 2020-07-01T02:52:16.000Z | 2021-06-22T12:15:59.000Z | lite/tests/kernels/sequence_pad_test.cc | winter-wang/Paddle-Lite | cd09ad060a0d7f20f55c4d6951ca95be75dc2c9c | [
"Apache-2.0"
] | null | null | null | lite/tests/kernels/sequence_pad_test.cc | winter-wang/Paddle-Lite | cd09ad060a0d7f20f55c4d6951ca95be75dc2c9c | [
"Apache-2.0"
] | 1 | 2021-07-24T15:30:46.000Z | 2021-07-24T15:30:46.000Z | // Copyright (c) 2021 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 <gtest/gtest.h>
#include <cstring>
#include "lite/api/paddle_use_kernels.h"
#include "lite/api/paddle_use_ops.h"
#include "lite/core/arena/framework.h"
#include "lite/tests/utils/fill_data.h"
namespace paddle {
namespace lite {
template <class T>
class SequencePadTester : public arena::TestCase {
protected:
std::string x_ = "x";
std::string pad_value_ = "pad_value";
std::string out_ = "out";
std::string length_ = "length";
DDim x_dims_{{9, 2, 3, 4}};
LoD x_lod_{{{0, 2, 5, 9}}};
T value_ = 0;
int padded_length_ = 4;
public:
SequencePadTester(const Place& place, const std::string& alias)
: TestCase(place, alias) {}
void RunBaseline(Scope* scope) override {
auto* out = scope->NewTensor(out_);
auto out_shape = x_dims_.Vectorize();
out_shape[0] = padded_length_;
out_shape.insert(out_shape.begin(),
static_cast<int64_t>(x_lod_[0].size() - 1));
out->Resize(out_shape);
auto* out_data = out->template mutable_data<T>();
for (int64_t i = 0; i < out->numel(); i++) {
out_data[i] = value_;
}
int n = x_dims_.production() / x_dims_[0];
int out_step = padded_length_ * n;
auto* x = scope->FindTensor(x_);
auto* x_data = x->template data<T>();
for (size_t i = 1; i < x_lod_[0].size(); i++) {
int x_step = (x_lod_[0][i] - x_lod_[0][i - 1]) * n;
memcpy(out_data, x_data, sizeof(T) * x_step);
x_data += x_step;
out_data += out_step;
}
auto* length = scope->NewTensor(length_);
length->Resize({static_cast<int64_t>(x_lod_[0].size() - 1)});
int64_t* length_data = length->template mutable_data<int64_t>();
for (size_t i = 1; i < x_lod_[0].size(); i++) {
length_data[i - 1] = x_lod_[0][i] - x_lod_[0][i - 1];
}
}
void PrepareOpDesc(cpp::OpDesc* op_desc) {
op_desc->SetType("sequence_pad");
op_desc->SetInput("X", {x_});
op_desc->SetInput("PadValue", {pad_value_});
op_desc->SetOutput("Out", {out_});
op_desc->SetOutput("Length", {length_});
op_desc->SetAttr("padded_length", padded_length_);
}
void PrepareData() override {
std::vector<T> x_data(x_dims_.production());
fill_data_rand<T>(x_data.data(), -10, 10, x_dims_.production());
SetCommonTensor(x_, x_dims_, x_data.data(), x_lod_);
std::vector<T> pad_value_data{0};
SetCommonTensor(pad_value_, DDim{{1}}, pad_value_data.data());
}
};
template <class T>
void TestSequencePad(const Place place,
const float abs_error,
const std::string alias) {
std::unique_ptr<arena::TestCase> tester(
new SequencePadTester<T>(place, alias));
arena::Arena arena(std::move(tester), place, abs_error);
arena.TestPrecision();
}
TEST(sequence_pad, precision) {
Place place;
float abs_error = 1e-5;
#if defined(LITE_WITH_ARM) || defined(LITE_WITH_X86)
place = TARGET(kHost);
#else
return;
#endif
TestSequencePad<float>(place, abs_error, "def");
TestSequencePad<int>(place, abs_error, "int32");
TestSequencePad<int64_t>(place, abs_error, "int64");
}
} // namespace lite
} // namespace paddle
| 32.008547 | 75 | 0.658745 | winter-wang |
cd332b0704436ea6dd1415cc10a86ee6c4d4c083 | 43,948 | hpp | C++ | include/jsoncons/json_container.hpp | snatesh/NEMoSys_fork | 5c1d8244c274a8e9e2a66c23baa91329dcdaf0eb | [
"NCSA"
] | 4 | 2019-10-25T00:37:17.000Z | 2020-06-02T22:23:02.000Z | include/jsoncons/json_container.hpp | snatesh/NEMoSys_fork | 5c1d8244c274a8e9e2a66c23baa91329dcdaf0eb | [
"NCSA"
] | null | null | null | include/jsoncons/json_container.hpp | snatesh/NEMoSys_fork | 5c1d8244c274a8e9e2a66c23baa91329dcdaf0eb | [
"NCSA"
] | null | null | null | // Copyright 2013 Daniel Parker
// Distributed under the Boost license, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See https://github.com/danielaparker/jsoncons for latest version
#ifndef JSONCONS_JSON_CONTAINER_HPP
#define JSONCONS_JSON_CONTAINER_HPP
#include <string>
#include <vector>
#include <deque>
#include <exception>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <utility>
#include <initializer_list>
#include <jsoncons/jsoncons.hpp>
#include <jsoncons/json_traits.hpp>
#include <jsoncons/jsoncons_util.hpp>
namespace jsoncons {
template <class Json>
class Json_string_base_
{
public:
typedef typename Json::allocator_type allocator_type;
Json_string_base_()
: self_allocator_()
{
}
Json_string_base_(const allocator_type& allocator)
: self_allocator_(allocator)
{
}
private:
allocator_type self_allocator_;
};
template <class Json>
class Json_string_
{
public:
typedef typename Json::allocator_type allocator_type;
typedef typename Json::char_allocator_type char_allocator_type;
typedef typename Json::char_type char_type;
typedef typename Json::string_storage_type string_storage_type;
typedef typename string_storage_type::iterator iterator;
typedef typename string_storage_type::const_iterator const_iterator;
//using Json_string_base_<Json>::get_allocator;
Json_string_()
: //Json_string_base_<Json>(),
string_()
{
}
Json_string_(const Json_string_& val)
: //Json_string_base_<Json>(val.get_allocator()),
string_(val.string_)
{
}
Json_string_(const Json_string_& val, const allocator_type& allocator)
: //Json_string_base_<Json>(allocator),
string_(val.string_,char_allocator_type(allocator))
{
}
Json_string_(Json_string_&& val) JSONCONS_NOEXCEPT
: //Json_string_base_<Json>(val.get_allocator()),
string_(std::move(val.string_))
{
}
Json_string_(Json_string_&& val, const allocator_type& allocator)
: //Json_string_base_<Json>(allocator),
string_(std::move(val.string_),char_allocator_type(allocator))
{
}
explicit Json_string_(const allocator_type& allocator)
: //Json_string_base_<Json>(allocator),
string_(char_allocator_type(allocator))
{
}
Json_string_(const char_type* data, size_t length)
: //Json_string_base_<Json>(),
string_(data,length)
{
}
Json_string_(const char_type* data, size_t length, allocator_type allocator)
: //Json_string_base_<Json>(allocator),
string_(data, length, allocator)
{
}
const char_type* data() const
{
return string_.data();
}
const char_type* c_str() const
{
return string_.c_str();
}
size_t length() const
{
return string_.size();
}
allocator_type get_allocator() const
{
return string_.get_allocator();
}
private:
string_storage_type string_;
Json_string_<Json>& operator=(const Json_string_<Json>&) = delete;
};
// json_array
template <class Json>
class Json_array_base_
{
public:
typedef typename Json::allocator_type allocator_type;
public:
Json_array_base_()
: self_allocator_()
{
}
Json_array_base_(const allocator_type& allocator)
: self_allocator_(allocator)
{
}
allocator_type get_allocator() const
{
return self_allocator_;
}
allocator_type self_allocator_;
};
template <class Json>
class json_array: public Json_array_base_<Json>
{
public:
typedef typename Json::allocator_type allocator_type;
typedef Json value_type;
typedef typename std::allocator_traits<allocator_type>:: template rebind_alloc<value_type> val_allocator_type;
typedef typename Json::array_storage_type array_storage_type;
typedef typename array_storage_type::iterator iterator;
typedef typename array_storage_type::const_iterator const_iterator;
typedef typename std::iterator_traits<iterator>::reference reference;
typedef typename std::iterator_traits<const_iterator>::reference const_reference;
using Json_array_base_<Json>::get_allocator;
json_array()
: Json_array_base_<Json>(),
elements_()
{
}
explicit json_array(const allocator_type& allocator)
: Json_array_base_<Json>(allocator),
elements_(val_allocator_type(allocator))
{
}
explicit json_array(size_t n,
const allocator_type& allocator = allocator_type())
: Json_array_base_<Json>(allocator),
elements_(n,Json(),val_allocator_type(allocator))
{
}
explicit json_array(size_t n,
const Json& value,
const allocator_type& allocator = allocator_type())
: Json_array_base_<Json>(allocator),
elements_(n,value,val_allocator_type(allocator))
{
}
template <class InputIterator>
json_array(InputIterator begin, InputIterator end, const allocator_type& allocator = allocator_type())
: Json_array_base_<Json>(allocator),
elements_(begin,end,val_allocator_type(allocator))
{
}
json_array(const json_array& val)
: Json_array_base_<Json>(val.get_allocator()),
elements_(val.elements_)
{
}
json_array(const json_array& val, const allocator_type& allocator)
: Json_array_base_<Json>(allocator),
elements_(val.elements_,val_allocator_type(allocator))
{
}
json_array(json_array&& val) JSONCONS_NOEXCEPT
: Json_array_base_<Json>(val.get_allocator()),
elements_(std::move(val.elements_))
{
}
json_array(json_array&& val, const allocator_type& allocator)
: Json_array_base_<Json>(allocator),
elements_(std::move(val.elements_),val_allocator_type(allocator))
{
}
json_array(std::initializer_list<Json> init)
: Json_array_base_<Json>(),
elements_(std::move(init))
{
}
json_array(std::initializer_list<Json> init,
const allocator_type& allocator)
: Json_array_base_<Json>(allocator),
elements_(std::move(init),val_allocator_type(allocator))
{
}
~json_array()
{
}
void swap(json_array<Json>& val)
{
elements_.swap(val.elements_);
}
size_t size() const {return elements_.size();}
size_t capacity() const {return elements_.capacity();}
void clear() {elements_.clear();}
void shrink_to_fit()
{
for (size_t i = 0; i < elements_.size(); ++i)
{
elements_[i].shrink_to_fit();
}
elements_.shrink_to_fit();
}
void reserve(size_t n) {elements_.reserve(n);}
void resize(size_t n) {elements_.resize(n);}
void resize(size_t n, const Json& val) {elements_.resize(n,val);}
void remove_range(size_t from_index, size_t to_index)
{
JSONCONS_ASSERT(from_index <= to_index);
JSONCONS_ASSERT(to_index <= elements_.size());
elements_.erase(elements_.begin()+from_index,elements_.begin()+to_index);
}
void erase(iterator first, iterator last)
{
elements_.erase(first,last);
}
Json& operator[](size_t i) {return elements_[i];}
const Json& operator[](size_t i) const {return elements_[i];}
template <class T, class U=allocator_type,
typename std::enable_if<is_stateless<U>::value
>::type* = nullptr>
void add(T&& value)
{
elements_.emplace_back(Json(std::forward<T&&>(value)));
}
template <class T, class U=allocator_type,
typename std::enable_if<!is_stateless<U>::value
>::type* = nullptr>
void add(T&& value)
{
elements_.emplace_back(std::forward<T&&>(value),get_allocator());
}
#if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 9
// work around https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54577
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
add(const_iterator pos, T&& value)
{
iterator it = elements_.begin() + (pos - elements_.begin());
return elements_.emplace(it, Json(std::forward<T&&>(value)));
}
#else
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
add(const_iterator pos, T&& value)
{
return elements_.emplace(pos, Json(std::forward<T&&>(value)));
}
#endif
iterator begin() {return elements_.begin();}
iterator end() {return elements_.end();}
const_iterator begin() const {return elements_.begin();}
const_iterator end() const {return elements_.end();}
bool operator==(const json_array<Json>& rhs) const
{
if (size() != rhs.size())
{
return false;
}
for (size_t i = 0; i < size(); ++i)
{
if (elements_[i] != rhs.elements_[i])
{
return false;
}
}
return true;
}
private:
array_storage_type elements_;
json_array& operator=(const json_array<Json>&) = delete;
};
// json_object
template <class BidirectionalIt,class BinaryPredicate>
BidirectionalIt last_wins_unique_sequence(BidirectionalIt first, BidirectionalIt last, BinaryPredicate compare)
{
if (first == last)
{
return last;
}
typedef typename BidirectionalIt::value_type value_type;
typedef typename BidirectionalIt::pointer pointer;
std::vector<value_type> dups;
{
std::vector<pointer> v(std::distance(first,last));
auto p = v.begin();
for (auto it = first; it != last; ++it)
{
*p++ = &(*it);
}
std::sort(v.begin(), v.end(), [&](pointer a, pointer b){return compare(*a,*b)<0;});
auto it = v.begin();
auto end = v.end();
for (auto begin = it+1; begin != end; ++it, ++begin)
{
if (compare(*(*it),*(*begin)) == 0)
{
dups.push_back(*(*it));
}
}
}
if (dups.size() == 0)
{
return last;
}
auto it = last;
for (auto p = first; p != last && p != it; )
{
bool no_dup = true;
if (dups.size() > 0)
{
for (auto q = dups.begin(); no_dup && q != dups.end();)
{
if (compare(*p,*q) == 0)
{
dups.erase(q);
no_dup = false;
}
else
{
++q;
}
}
}
if (!no_dup)
{
--it;
for (auto r = p; r != it; ++r)
{
*r = std::move(*(r+1));
}
}
else
{
++p;
}
}
return it;
}
template <class KeyT, class ValueT>
class key_value_pair
{
public:
typedef KeyT key_storage_type;
typedef typename KeyT::value_type char_type;
typedef typename KeyT::allocator_type allocator_type;
typedef typename ValueT::string_view_type string_view_type;
key_value_pair()
{
}
key_value_pair(const key_storage_type& name, const ValueT& val)
: key_(name), value_(val)
{
}
key_value_pair(key_storage_type&& name, ValueT&& val)
: key_(std::forward<key_storage_type&&>(name)),
value_(std::forward<ValueT&&>(val))
{
}
key_value_pair(const key_value_pair& member)
: key_(member.key_), value_(member.value_)
{
}
key_value_pair(key_value_pair&& member)
: key_(std::move(member.key_)), value_(std::move(member.value_))
{
}
template <class T>
key_value_pair(key_storage_type&& name,
T&& val,
const allocator_type& allocator)
: key_(std::forward<key_storage_type&&>(name)), value_(std::forward<T&&>(val), allocator)
{
}
string_view_type key() const
{
return string_view_type(key_.data(),key_.size());
}
ValueT& value()
{
return value_;
}
const ValueT& value() const
{
return value_;
}
void value(const ValueT& value)
{
value_ = value;
}
void value(ValueT&& value)
{
value_ = std::forward<ValueT&&>(value);
}
void swap(key_value_pair& member)
{
key_.swap(member.key_);
value_.swap(member.value_);
}
key_value_pair& operator=(const key_value_pair& member)
{
if (this != & member)
{
key_ = member.key_;
value_ = member.value_;
}
return *this;
}
key_value_pair& operator=(key_value_pair&& member)
{
if (this != &member)
{
key_.swap(member.key_);
value_.swap(member.value_);
}
return *this;
}
void shrink_to_fit()
{
key_.shrink_to_fit();
value_.shrink_to_fit();
}
#if !defined(JSONCONS_NO_DEPRECATED)
const key_storage_type& name() const
{
return key_;
}
#endif
private:
key_storage_type key_;
ValueT value_;
};
template <class KeyT,class Json>
class Json_object_
{
public:
typedef typename Json::allocator_type allocator_type;
typedef typename Json::char_type char_type;
typedef typename Json::char_allocator_type char_allocator_type;
typedef KeyT key_storage_type;
typedef typename Json::string_view_type string_view_type;
typedef key_value_pair<KeyT,Json> value_type;
typedef typename std::allocator_traits<allocator_type>:: template rebind_alloc<value_type> kvp_allocator_type;
typedef typename Json::object_storage_type object_storage_type;
typedef typename object_storage_type::iterator iterator;
typedef typename object_storage_type::const_iterator const_iterator;
protected:
allocator_type self_allocator_;
object_storage_type members_;
public:
Json_object_()
: self_allocator_(), members_()
{
}
Json_object_(const allocator_type& allocator)
: self_allocator_(allocator),
members_(kvp_allocator_type(allocator))
{
}
Json_object_(const Json_object_& val)
: self_allocator_(val.get_allocator()), members_(val.members_)
{
}
Json_object_(Json_object_&& val)
: self_allocator_(val.get_allocator()),
members_(std::move(val.members_))
{
}
Json_object_(const Json_object_& val, const allocator_type& allocator) :
self_allocator_(allocator),
members_(val.members_,kvp_allocator_type(allocator))
{
}
Json_object_(Json_object_&& val,const allocator_type& allocator) :
self_allocator_(allocator), members_(std::move(val.members_),kvp_allocator_type(allocator))
{
}
void swap(Json_object_& val)
{
members_.swap(val.members_);
}
allocator_type get_allocator() const
{
return this->self_allocator_;
}
};
template <class KeyT,class Json,bool PreserveOrder>
class json_object
{
};
// Do not preserve order
template <class KeyT,class Json>
class json_object<KeyT,Json,false> : public Json_object_<KeyT,Json>
{
public:
using typename Json_object_<KeyT,Json>::allocator_type;
using typename Json_object_<KeyT,Json>::char_type;
using typename Json_object_<KeyT,Json>::char_allocator_type;
using typename Json_object_<KeyT,Json>::key_storage_type;
using typename Json_object_<KeyT,Json>::string_view_type;
using typename Json_object_<KeyT,Json>::value_type;
using typename Json_object_<KeyT,Json>::kvp_allocator_type;
using typename Json_object_<KeyT,Json>::object_storage_type;
using typename Json_object_<KeyT,Json>::iterator;
using typename Json_object_<KeyT,Json>::const_iterator;
using Json_object_<KeyT,Json>::get_allocator;
json_object()
: Json_object_<KeyT,Json>()
{
}
json_object(const allocator_type& allocator)
: Json_object_<KeyT,Json>(allocator)
{
}
json_object(const json_object& val)
: Json_object_<KeyT,Json>(val)
{
}
json_object(json_object&& val)
: Json_object_<KeyT,Json>(std::forward<json_object&&>(val))
{
}
json_object(const json_object& val, const allocator_type& allocator)
: Json_object_<KeyT,Json>(val,allocator)
{
}
json_object(json_object&& val,const allocator_type& allocator)
: Json_object_<KeyT,Json>(std::forward<json_object&&>(val),allocator)
{
}
json_object(std::initializer_list<typename Json::array> init)
: Json_object_<KeyT,Json>()
{
for (const auto& element : init)
{
if (element.size() != 2 || !element[0].is_string())
{
JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list");
break;
}
}
for (auto& element : init)
{
set(element[0].as_string_view(), std::move(element[1]));
}
}
json_object(std::initializer_list<typename Json::array> init,
const allocator_type& allocator)
: Json_object_<KeyT,Json>(allocator)
{
for (const auto& element : init)
{
if (element.size() != 2 || !element[0].is_string())
{
JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list");
break;
}
}
for (auto& element : init)
{
set(element[0].as_string_view(), std::move(element[1]));
}
}
void swap(json_object& val)
{
Json_object_<KeyT,Json>::swap(val);
}
iterator begin()
{
return this->members_.begin();
}
iterator end()
{
return this->members_.end();
}
const_iterator begin() const
{
return this->members_.begin();
}
const_iterator end() const
{
return this->members_.end();
}
size_t size() const {return this->members_.size();}
size_t capacity() const {return this->members_.capacity();}
void clear() {this->members_.clear();}
void shrink_to_fit()
{
for (size_t i = 0; i < this->members_.size(); ++i)
{
this->members_[i].shrink_to_fit();
}
this->members_.shrink_to_fit();
}
void reserve(size_t n) {this->members_.reserve(n);}
Json& at(size_t i)
{
if (i >= this->members_.size())
{
JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript");
}
return this->members_[i].value();
}
const Json& at(size_t i) const
{
if (i >= this->members_.size())
{
JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript");
}
return this->members_[i].value();
}
iterator find(string_view_type name)
{
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
auto result = (it != this->members_.end() && it->key() == name) ? it : this->members_.end();
return result;
}
const_iterator find(string_view_type name) const
{
auto it = std::lower_bound(this->members_.begin(),this->members_.end(),
name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
auto result = (it != this->members_.end() && it->key() == name) ? it : this->members_.end();
return result;
}
void erase(iterator first, iterator last)
{
this->members_.erase(first,last);
}
void erase(string_view_type name)
{
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
if (it != this->members_.end() && it->key() == name)
{
this->members_.erase(it);
}
}
template<class InputIt, class UnaryPredicate>
void insert(InputIt first, InputIt last, UnaryPredicate pred)
{
size_t count = std::distance(first,last);
this->members_.reserve(this->members_.size() + count);
for (auto s = first; s != last; ++s)
{
this->members_.emplace_back(pred(*s));
}
std::stable_sort(this->members_.begin(),this->members_.end(),
[](const value_type& a, const value_type& b){return a.key().compare(b.key()) < 0;});
auto it = std::unique(this->members_.rbegin(), this->members_.rend(),
[](const value_type& a, const value_type& b){ return !(a.key().compare(b.key()));});
this->members_.erase(this->members_.begin(),it.base());
}
template <class T, class U=allocator_type,
typename std::enable_if<is_stateless<U>::value
>::type* = nullptr>
void set(string_view_type name, T&& value)
{
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
this->members_.emplace(it,
key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
}
}
template <class T, class U=allocator_type,
typename std::enable_if<!is_stateless<U>::value
>::type* = nullptr>
void set(string_view_type name, T&& value)
{
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value),get_allocator() );
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value),get_allocator() ));
}
else
{
this->members_.emplace(it,
key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value),get_allocator() );
}
}
template <class T, class U=allocator_type,
typename std::enable_if<is_stateless<U>::value
>::type* = nullptr>
void set_(key_storage_type&& name, T&& value)
{
string_view_type s(name.data(), name.size());
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
}
else if (string_view_type(it->key().data(),it->key().length()) == s)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
}
}
template <class T, class U=allocator_type,
typename std::enable_if<!is_stateless<U>::value
>::type* = nullptr>
void set_(key_storage_type&& name, T&& value)
{
string_view_type s(name.data(), name.size());
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value),get_allocator() );
}
else if (string_view_type(it->key().data(), it->key().length()) == s)
{
it->value(Json(std::forward<T&&>(value),get_allocator() ));
}
else
{
this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value),get_allocator() );
}
}
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
set(iterator hint, string_view_type name, T&& value)
{
iterator it;
if (hint != this->members_.end() && hint->key() <= name)
{
it = std::lower_bound(hint,this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
else
{
it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
it = this->members_.emplace(it,
key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<!is_stateless<U>::value,iterator>::type
set(iterator hint, string_view_type name, T&& value)
{
iterator it;
if (hint != this->members_.end() && hint->key() <= name)
{
it = std::lower_bound(hint,this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
else
{
it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value),get_allocator() );
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value),get_allocator() ));
}
else
{
it = this->members_.emplace(it,
key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value),get_allocator() );
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
set_(iterator hint, key_storage_type&& name, T&& value)
{
string_view_type s(name.data(), name.size());
iterator it;
if (hint != this->members_.end() && hint->key() <= s)
{
it = std::lower_bound(hint,this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
else
{
it = std::lower_bound(this->members_.begin(),this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (string_view_type(it->key().data(), it->key().length()) == s)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
it = this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<!is_stateless<U>::value,iterator>::type
set_(iterator hint, key_storage_type&& name, T&& value)
{
string_view_type s(name.data(), name.size());
iterator it;
if (hint != this->members_.end() && hint->key() <= s)
{
it = std::lower_bound(hint,this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
else
{
it = std::lower_bound(this->members_.begin(),this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value),get_allocator() );
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (string_view_type(it->key().data(), it->key().length()) == s)
{
it->value(Json(std::forward<T&&>(value),get_allocator() ));
}
else
{
it = this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value),get_allocator() );
}
return it;
}
bool operator==(const json_object& rhs) const
{
if (size() != rhs.size())
{
return false;
}
for (auto it = this->members_.begin(); it != this->members_.end(); ++it)
{
auto rhs_it = std::lower_bound(rhs.begin(), rhs.end(), *it,
[](const value_type& a, const value_type& b){return a.key().compare(b.key()) < 0;});
if (rhs_it == rhs.end() || rhs_it->key() != it->key() || rhs_it->value() != it->value())
{
return false;
}
}
return true;
}
private:
json_object& operator=(const json_object&) = delete;
};
// Preserve order
template <class KeyT,class Json>
class json_object<KeyT,Json,true> : public Json_object_<KeyT,Json>
{
public:
using typename Json_object_<KeyT,Json>::allocator_type;
using typename Json_object_<KeyT,Json>::char_type;
using typename Json_object_<KeyT,Json>::char_allocator_type;
using typename Json_object_<KeyT,Json>::key_storage_type;
using typename Json_object_<KeyT,Json>::string_view_type;
using typename Json_object_<KeyT,Json>::value_type;
using typename Json_object_<KeyT,Json>::kvp_allocator_type;
using typename Json_object_<KeyT,Json>::object_storage_type;
using typename Json_object_<KeyT,Json>::iterator;
using typename Json_object_<KeyT,Json>::const_iterator;
using Json_object_<KeyT,Json>::get_allocator;
json_object()
: Json_object_<KeyT,Json>()
{
}
json_object(const allocator_type& allocator)
: Json_object_<KeyT,Json>(allocator)
{
}
json_object(const json_object& val)
: Json_object_<KeyT,Json>(val)
{
}
json_object(json_object&& val)
: Json_object_<KeyT,Json>(std::forward<json_object&&>(val))
{
}
json_object(const json_object& val, const allocator_type& allocator)
: Json_object_<KeyT,Json>(val,allocator)
{
}
json_object(json_object&& val,const allocator_type& allocator)
: Json_object_<KeyT,Json>(std::forward<json_object&&>(val),allocator)
{
}
json_object(std::initializer_list<typename Json::array> init)
: Json_object_<KeyT,Json>()
{
for (const auto& element : init)
{
if (element.size() != 2 || !element[0].is_string())
{
JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list");
break;
}
}
for (auto& element : init)
{
set(element[0].as_string_view(), std::move(element[1]));
}
}
json_object(std::initializer_list<typename Json::array> init,
const allocator_type& allocator)
: Json_object_<KeyT,Json>(allocator)
{
for (const auto& element : init)
{
if (element.size() != 2 || !element[0].is_string())
{
JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list");
break;
}
}
for (auto& element : init)
{
set(element[0].as_string_view(), std::move(element[1]));
}
}
void swap(json_object& val)
{
Json_object_<KeyT,Json>::swap(val);
}
iterator begin()
{
return this->members_.begin();
}
iterator end()
{
return this->members_.end();
}
const_iterator begin() const
{
return this->members_.begin();
}
const_iterator end() const
{
return this->members_.end();
}
size_t size() const {return this->members_.size();}
size_t capacity() const {return this->members_.capacity();}
void clear() {this->members_.clear();}
void shrink_to_fit()
{
for (size_t i = 0; i < this->members_.size(); ++i)
{
this->members_[i].shrink_to_fit();
}
this->members_.shrink_to_fit();
}
void reserve(size_t n) {this->members_.reserve(n);}
Json& at(size_t i)
{
if (i >= this->members_.size())
{
JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript");
}
return this->members_[i].value();
}
const Json& at(size_t i) const
{
if (i >= this->members_.size())
{
JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript");
}
return this->members_[i].value();
}
iterator find(string_view_type name)
{
return std::find_if(this->members_.begin(),this->members_.end(),
[name](const value_type& kvp){return kvp.key() == name;});
}
const_iterator find(string_view_type name) const
{
return std::find_if(this->members_.begin(),this->members_.end(),
[name](const value_type& kvp){return kvp.key() == name;});
}
void erase(iterator first, iterator last)
{
this->members_.erase(first,last);
}
void erase(string_view_type name)
{
auto it = std::find_if(this->members_.begin(),this->members_.end(),
[name](const value_type& kvp){return kvp.key() == name;});
if (it != this->members_.end())
{
this->members_.erase(it);
}
}
template<class InputIt, class UnaryPredicate>
void insert(InputIt first, InputIt last, UnaryPredicate pred)
{
size_t count = std::distance(first,last);
this->members_.reserve(this->members_.size() + count);
for (auto s = first; s != last; ++s)
{
this->members_.emplace_back(pred(*s));
}
auto it = last_wins_unique_sequence(this->members_.begin(), this->members_.end(),
[](const value_type& a, const value_type& b){ return a.key().compare(b.key());});
this->members_.erase(it,this->members_.end());
}
template <class T, class U=allocator_type,
typename std::enable_if<is_stateless<U>::value
>::type* = nullptr>
void set(string_view_type name, T&& value)
{
auto it = std::find_if(this->members_.begin(),this->members_.end(),
[name](const value_type& a){return a.key() == name;});
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
}
else
{
it->value(Json(std::forward<T&&>(value)));
}
}
template <class T, class U=allocator_type,
typename std::enable_if<!is_stateless<U>::value
>::type* = nullptr>
void set(string_view_type name, T&& value)
{
auto it = std::find_if(this->members_.begin(),this->members_.end(),
[name](const value_type& a){return a.key() == name;});
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value),get_allocator());
}
else
{
it->value(Json(std::forward<T&&>(value),get_allocator()));
}
}
template <class T, class U=allocator_type,
typename std::enable_if<is_stateless<U>::value
>::type* = nullptr>
void set_(key_storage_type&& name, T&& value)
{
string_view_type s(name.data(),name.size());
auto it = std::find_if(this->members_.begin(),this->members_.end(),
[s](const value_type& a){return a.key().compare(s) == 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
}
else
{
it->value(Json(std::forward<T&&>(value)));
}
}
template <class T, class U=allocator_type,
typename std::enable_if<!is_stateless<U>::value
>::type* = nullptr>
void set_(key_storage_type&& name, T&& value)
{
string_view_type s(name.data(),name.size());
auto it = std::find_if(this->members_.begin(),this->members_.end(),
[s](const value_type& a){return a.key().compare(s) == 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value),get_allocator());
}
else
{
it->value(Json(std::forward<T&&>(value),get_allocator()));
}
}
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
set(iterator hint, string_view_type name, T&& value)
{
iterator it = hint;
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value));
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
it = this->members_.emplace(it,
key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<!is_stateless<U>::value,iterator>::type
set(iterator hint, string_view_type name, T&& value)
{
iterator it = hint;
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end(),get_allocator()),
std::forward<T&&>(value),get_allocator());
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value),get_allocator()));
}
else
{
it = this->members_.emplace(it,
key_storage_type(name.begin(),name.end(),get_allocator()),
std::forward<T&&>(value),get_allocator());
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
set_(iterator hint, key_storage_type&& name, T&& value)
{
iterator it = hint;
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
it = this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<!is_stateless<U>::value,iterator>::type
set_(iterator hint, key_storage_type&& name, T&& value)
{
iterator it = hint;
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value), get_allocator());
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value), get_allocator()));
}
else
{
it = this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value), get_allocator());
}
return it;
}
bool operator==(const json_object& rhs) const
{
if (size() != rhs.size())
{
return false;
}
for (auto it = this->members_.begin(); it != this->members_.end(); ++it)
{
auto rhs_it = std::find_if(rhs.begin(),rhs.end(),
[it](const value_type& a){return a.key() == it->key();});
if (rhs_it == rhs.end() || rhs_it->key() != it->key() || rhs_it->value() != it->value())
{
return false;
}
}
return true;
}
private:
json_object& operator=(const json_object&) = delete;
};
}
#endif
| 30.647141 | 127 | 0.554132 | snatesh |
cd3c3bcfed4b9ef19161bdc8e38477bd8c604bb7 | 224 | cpp | C++ | 113.cpp | abdullah1107/uva | 5c7107d41a586e30aa7cc91cd7498b82dbc506ee | [
"MIT"
] | null | null | null | 113.cpp | abdullah1107/uva | 5c7107d41a586e30aa7cc91cd7498b82dbc506ee | [
"MIT"
] | null | null | null | 113.cpp | abdullah1107/uva | 5c7107d41a586e30aa7cc91cd7498b82dbc506ee | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
double m,n,p,k;
while(scanf("%lf %lf",&n,&p)!=EOF)
{
k=pow(p,1/n);
printf("%0.lf\n",k);
}
return 0;
}
| 14.933333 | 38 | 0.526786 | abdullah1107 |
cd3d78ff7f43762aeff7c21c690982d576577192 | 5,277 | cxx | C++ | test/test_shm.cxx | yushansuger/nwcp | 8c2e6a31af59f3d209c962438b8b123b415b4fa4 | [
"MIT"
] | null | null | null | test/test_shm.cxx | yushansuger/nwcp | 8c2e6a31af59f3d209c962438b8b123b415b4fa4 | [
"MIT"
] | null | null | null | test/test_shm.cxx | yushansuger/nwcp | 8c2e6a31af59f3d209c962438b8b123b415b4fa4 | [
"MIT"
] | 1 | 2020-09-14T09:06:25.000Z | 2020-09-14T09:06:25.000Z | #include "cpshm.h"
#include <stdio.h>
#include "cpstring.h"
const char* shm_id = "test_nwdl_shm";
struct TEST_SHM_DATA
{
char str[128];
int len;
};
void print_data(TEST_SHM_DATA* data)
{
printf("TEST_SHM_DATA::str: %s \nTEST_SHM_DATA::len: %d\n\n",
data->str, data->len);
}
int test_1()
{
cpshm_t shm_t = 0;
int ret = -1;
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t);
if (CPDL_SUCCESS != ret)
{
return -1;
}
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return -2;
}
}
else
{
ret = cpshm_map(shm_id, &shm_t);
if (CPDL_SUCCESS != ret)
{
return -1;
}
}
TEST_SHM_DATA* data = 0;
unsigned int len = 0;
ret = cpshm_data(shm_t, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);;
return -4;
}
strlcpy(data->str, "test_1 shm by nonwill", 128);
data->len = strlen(data->str);
print_data(data);
ret = cpshm_unmap(shm_t);
data = 0;
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return -2;
}
cpshm_t shm_t2 = 0;
ret = cpshm_map(shm_id, &shm_t2);
ret = cpshm_data(shm_t2, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t2);
ret = cpshm_close(&shm_t);
return -5;
}
print_data(data);
ret = cpshm_close(&shm_t2);
ret = cpshm_close(&shm_t);
return 1;
}
int test_2()
{
cpshm_t shm_t = 0;
int ret = -1;
ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t);
if (CPDL_SUCCESS != ret)
{
return -1;
}
TEST_SHM_DATA* data = 0;
unsigned int len = 0;
ret = cpshm_data(shm_t, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return -5;
}
strlcpy(data->str, "test_2 shm by nonwill", 128);
data->len = strlen(data->str);
print_data(data);
ret = cpshm_close(&shm_t);
shm_t = 0;
data = 0;
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS == ret)
{
//ret = cpshm_close(&shm_t);
return -2;
}
ret = cpshm_map(shm_id, &shm_t);
if (CPDL_SUCCESS == ret)
{
ret = cpshm_close(&shm_t);
return -3;
}
ret = cpshm_data(shm_t, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS == ret)
{
print_data(data);
ret = cpshm_close(&shm_t);
return -4;
}
return 1;
}
int test_3()
{
cpshm_t shm_t = 0;
int ret = -1;
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t);
if (CPDL_SUCCESS != ret)
{
return -1;
}
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return -2;
}
}
TEST_SHM_DATA* data = 0;
unsigned int len = 0;
ret = cpshm_data(shm_t, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);;
return -4;
}
strlcpy(data->str, "test_3 shm by nonwill", 128);
data->len = strlen(data->str);
print_data(data);
cpshm_t shm_t2 = 0;
ret = cpshm_map(shm_id, &shm_t2);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return -5;
}
ret = cpshm_close(&shm_t);
ret = cpshm_data(shm_t2, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t2);
return -5;
}
print_data(data);
ret = cpshm_close(&shm_t2);
return 1;
}
void test_4()
{
cpshm_t shm_t = 0;
int ret = -1;
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t);
if (CPDL_SUCCESS != ret)
{
return ;
}
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return ;
}
}
cpshm_t shm_t2 = 0;
cpshm_t shm_t3 = 0;
ret = cpshm_map(shm_id, &shm_t2);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return ;
}
ret = cpshm_close(&shm_t2);
ret = cpshm_map(shm_id, &shm_t3);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return ;
}
else
{
ret = cpshm_close(&shm_t3);
}
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
printf("test_4 cpshm_exist : no shm exist\n");
}
ret = cpshm_close(&shm_t);
}
int main(int /*argc*/, char* /*argv*/[])
{
test_1();
test_2();
test_3();
test_4();
#ifdef _NWCP_WIN32
system("pause");
#endif
return 1;
}
| 19.838346 | 67 | 0.492515 | yushansuger |
cd40158fa587ea149d6323d39ce5d36b66d36005 | 440 | hpp | C++ | tests/gt_os/inc/mocks/window-enumerator.mock.hpp | my-repositories/GameTrainer | fd307e0bd6e0ef74e8b3195ad6394c71e2fac555 | [
"MIT"
] | 3 | 2018-10-11T13:37:42.000Z | 2021-03-23T21:54:02.000Z | tests/gt_os/inc/mocks/window-enumerator.mock.hpp | my-repositories/GameTrainer | fd307e0bd6e0ef74e8b3195ad6394c71e2fac555 | [
"MIT"
] | null | null | null | tests/gt_os/inc/mocks/window-enumerator.mock.hpp | my-repositories/GameTrainer | fd307e0bd6e0ef74e8b3195ad6394c71e2fac555 | [
"MIT"
] | null | null | null | #ifndef GAMETRAINER_WINDOW_ENUMERATOR_MOCK_HPP
#define GAMETRAINER_WINDOW_ENUMERATOR_MOCK_HPP
#include <gt_os/window-enumerator.i.hpp>
class WindowEnumeratorMock : public gt::os::IWindowEnumerator {
public:
MOCK_METHOD1(setTitle, gt::os::IWindowEnumerator*(const std::string&));
MOCK_METHOD0(enumerate, gt::os::IWindowEnumerator*());
MOCK_CONST_METHOD0(getWindow, HWND());
};
#endif // GAMETRAINER_WINDOW_ENUMERATOR_MOCK_HPP
| 31.428571 | 75 | 0.793182 | my-repositories |
cd44485256c8664d140b4cc445f59264c2e94353 | 11,768 | hxx | C++ | include/geombd/CRTP/DJointBase.hxx | garechav/geombd_crtp | c723c0cda841728fcb34fbad634f166e3237d9d9 | [
"MIT"
] | 1 | 2021-12-20T23:11:23.000Z | 2021-12-20T23:11:23.000Z | include/geombd/CRTP/DJointBase.hxx | garechav/geombd_crtp | c723c0cda841728fcb34fbad634f166e3237d9d9 | [
"MIT"
] | null | null | null | include/geombd/CRTP/DJointBase.hxx | garechav/geombd_crtp | c723c0cda841728fcb34fbad634f166e3237d9d9 | [
"MIT"
] | null | null | null | /**
* \file include/geombd/CRTP/DJointBase.hxx
* \author Alvaro Paz, Gustavo Arechavaleta
* \version 1.0
* \date 2021
*
* Class to implement the CRTP base (interface)
* Copyright (c) 2021 Cinvestav
* This library is distributed under the MIT License.
*/
#ifdef EIGEN_VECTORIZE
#endif
#ifndef GEOMBD_JOINT_BASE_DIFFERENTIATION_CRTP_HXX
#define GEOMBD_JOINT_BASE_DIFFERENTIATION_CRTP_HXX
//! Include Eigen Library
//!--------------------------------------------------------------------------------!//
#define EIGEN_NO_DEBUG
#define EIGEN_MPL2_ONLY
#define EIGEN_UNROLLING_LIMIT 30
#include "Eigen/Core"
//#include "Eigen/../unsupported/Eigen/KroneckerProduct"
//!--------------------------------------------------------------------------------!//
namespace geo {
//! Joint Type Base
//!------------------------------------------------------------------------------!//
template<typename Derived>
struct D_CRTPInterface{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
//! Recurring Pattern for the Forward Kinematics.
template<typename ScalarType, typename Vector3Type, typename Matrix3Type>
EIGEN_ALWAYS_INLINE void
D_FwdKin(const ScalarType & qi,
const Eigen::MatrixBase<Vector3Type> & S_,
typename Eigen::MatrixBase<Matrix3Type> & R) {
static_cast<Derived*>(this)->runD_FK(qi, S_, R);
// static_cast<Derived&>(*this).runD_FK(qi, S_, R);
}
//! Recurring Pattern for Twist, C bias and P bias at root.
template<typename ScalarType, typename Vector3Type, typename Vector6Type, typename Matrix6Type, typename D_Vector6Type>
EIGEN_ALWAYS_INLINE void
D_TCP_root(const ScalarType & vi,
const Eigen::MatrixBase<Vector3Type> & S_,
Eigen::MatrixBase<Vector6Type> & S_i,
Eigen::MatrixBase<Vector6Type> & p_,
const Eigen::MatrixBase<Matrix6Type> & M_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_p_) {
static_cast<Derived*>(this)->runD_TCP_root(vi, S_, S_i, p_.derived(), M_.derived(), D_dq_p_.derived());
}
//! Recurring Pattern for Twist, C bias and P bias.
template<typename ScalarType, typename Matrix3Type, typename Matrix6Type,
typename Vector3Type, typename Vector6Type, typename D_Vector6Type>
EIGEN_ALWAYS_INLINE void
D_TwCbPb(bool zeroFlag,
const ScalarType & vi,
const Eigen::MatrixBase<Vector3Type> & S_,
const Eigen::MatrixBase<Matrix3Type> & R_,
const Eigen::MatrixBase<Vector3Type> & P_,
const Eigen::MatrixBase<Vector6Type> & S_l,
const Eigen::MatrixBase<Matrix6Type> & M_,
Eigen::MatrixBase<Vector6Type> & S_i,
Eigen::MatrixBase<Vector6Type> & c_,
Eigen::MatrixBase<Vector6Type> & p_,
Eigen::MatrixBase<D_Vector6Type> & D_q_V_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_V_,
const Eigen::MatrixBase<D_Vector6Type> & D_q_Vj_,
const Eigen::MatrixBase<D_Vector6Type> & D_dq_Vj_,
Eigen::MatrixBase<D_Vector6Type> & D_q_c_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_c_,
Eigen::MatrixBase<D_Vector6Type> & D_q_p_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_p_) {
static_cast<Derived*>(this)->runD_TwCbPb(zeroFlag, vi, S_.derived(), R_.derived(), P_.derived(), S_l.derived(), M_.derived(),
S_i.derived(), c_.derived(), p_.derived(), D_q_V_.derived(), D_dq_V_.derived(),
D_q_Vj_.derived(), D_dq_Vj_.derived(), D_q_c_.derived(), D_dq_c_.derived(),
D_q_p_.derived(), D_dq_p_.derived());
}
//! Recurring pattern for inertial expressions at leaf.
template<typename ScalarType, typename Vector3Type, typename Matrix3Type, typename Vector6Type,
typename Matrix6Type, typename RowVectorXType, typename D_Vector6Type, typename D_Matrix6Type>
EIGEN_ALWAYS_INLINE void
D_InertiaLeaf(ScalarType & u,
ScalarType & iD,
const ScalarType tau,
const Eigen::MatrixBase<Vector3Type> & S_,
Eigen::MatrixBase<Vector6Type> & U_,
Eigen::MatrixBase<Vector6Type> & c_,
Eigen::MatrixBase<Vector6Type> & P_a_,
Eigen::MatrixBase<Matrix6Type> & M_a_,
Eigen::MatrixBase<Vector6Type> & P_A_,
Eigen::MatrixBase<Matrix6Type> & M_A_,
bool P_z,
Eigen::MatrixBase<Vector3Type> & P_,
Eigen::MatrixBase<Matrix3Type> & R_,
Eigen::MatrixBase<Vector6Type> & P_Aj_,
Eigen::MatrixBase<Matrix6Type> & M_Aj_,
Eigen::MatrixBase<D_Matrix6Type> & D_M_Aj_,
Eigen::MatrixBase<RowVectorXType> & D_q_u_,
Eigen::MatrixBase<RowVectorXType> & D_dq_u_,
Eigen::MatrixBase<D_Vector6Type> & D_q_p_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_p_,
Eigen::MatrixBase<D_Vector6Type> & D_q_Pa_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_Pa_,
Eigen::MatrixBase<D_Vector6Type> & D_q_PA_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_PA_,
Eigen::MatrixBase<D_Vector6Type> & D_q_PAj_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_PAj_,
Eigen::MatrixBase<D_Vector6Type> & D_q_c_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_c_) {
static_cast<Derived*>(this)->runD_InertiaLeaf(u, iD, tau, S_, U_, c_, P_a_, M_a_, P_A_, M_A_, P_z, P_, R_, P_Aj_,
M_Aj_, D_M_Aj_, D_q_u_, D_dq_u_, D_q_p_, D_dq_p_, D_q_Pa_, D_dq_Pa_,
D_q_PA_, D_dq_PA_, D_q_PAj_, D_dq_PAj_, D_q_c_, D_dq_c_);
}
//! Recurring pattern for inertial expressions.
template<typename ScalarType, typename Vector6iType, typename Vector3Type, typename Matrix3Type, typename Vector6Type,
typename Matrix6Type, typename VectorXType, typename RowVectorXType, typename D_Vector6Type, typename D_Matrix6Type>
EIGEN_ALWAYS_INLINE void
D_Inertial(bool rootFlag,
Eigen::MatrixBase<Vector6iType> & indexVec,
ScalarType & u,
ScalarType & iD,
const ScalarType tau,
const Eigen::MatrixBase<Vector3Type> & S_,
Eigen::MatrixBase<Vector6Type> & U_,
Eigen::MatrixBase<Vector6Type> & c_,
Eigen::MatrixBase<Vector6Type> & P_a_,
Eigen::MatrixBase<Matrix6Type> & M_a_,
Eigen::MatrixBase<Vector6Type> & P_A_,
Eigen::MatrixBase<Matrix6Type> & M_A_,
bool P_z,
Eigen::MatrixBase<Vector3Type> & P_,
Eigen::MatrixBase<Matrix3Type> & R_,
Eigen::MatrixBase<Vector6Type> & P_Aj_,
Eigen::MatrixBase<Matrix6Type> & M_Aj_,
Eigen::MatrixBase<D_Vector6Type> & D_U_h_,
Eigen::MatrixBase<VectorXType> & D_U_v_,
Eigen::MatrixBase<RowVectorXType> & D_invD_,
Eigen::MatrixBase<D_Matrix6Type> & D_M_A_,
Eigen::MatrixBase<D_Matrix6Type> & D_M_Aj_,
Eigen::MatrixBase<RowVectorXType> & D_q_u_,
Eigen::MatrixBase<RowVectorXType> & D_dq_u_,
Eigen::MatrixBase<D_Vector6Type> & D_q_Pa_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_Pa_,
Eigen::MatrixBase<D_Vector6Type> & D_q_PA_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_PA_,
Eigen::MatrixBase<D_Vector6Type> & D_q_PAj_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_PAj_,
Eigen::MatrixBase<D_Vector6Type> & D_q_c_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_c_) {
static_cast<Derived*>(this)->runD_Inertial(rootFlag, indexVec, u, iD, tau, S_, U_, c_, P_a_, M_a_, P_A_, M_A_, P_z,
P_, R_, P_Aj_, M_Aj_, D_U_h_, D_U_v_, D_invD_, D_M_A_, D_M_Aj_,
D_q_u_, D_dq_u_, D_q_Pa_, D_dq_Pa_, D_q_PA_, D_dq_PA_, D_q_PAj_,
D_dq_PAj_, D_q_c_, D_dq_c_);
}
//! Recurring pattern for acceleration expression at root.
template<typename ScalarType, typename Vector3Type, typename Matrix3Type, typename Vector6Type,
typename D_Vector6Type, typename RowVectorXType, typename MatrixXType>
EIGEN_ALWAYS_INLINE void
D_AccelRoot(ScalarType u,
ScalarType iD,
ScalarType* ddq,
const Eigen::MatrixBase<Vector3Type> & S,
const Eigen::MatrixBase<Vector3Type> & P_r,
const Eigen::MatrixBase<Matrix3Type> & R_r,
const Eigen::MatrixBase<Vector6Type> & U_r,
Eigen::MatrixBase<Vector6Type> & Acc_i_r,
Eigen::MatrixBase<D_Vector6Type> & D_U_h_,
Eigen::MatrixBase<RowVectorXType> & D_invD_,
Eigen::MatrixBase<RowVectorXType> & D_q_u_,
Eigen::MatrixBase<RowVectorXType> & D_dq_u_,
Eigen::MatrixBase<D_Vector6Type> & D_q_A_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_A_,
Eigen::MatrixBase<MatrixXType> & D_ddq_) {
static_cast<Derived*>(this)->runD_AccelRoot(u, iD, ddq, S, P_r, R_r, U_r, Acc_i_r, D_U_h_, D_invD_,
D_q_u_, D_dq_u_, D_q_A_, D_dq_A_, D_ddq_);
}
//! Recurring pattern for acceleration expression.
template<typename ScalarType, typename IndexType, typename Vector3Type, typename Matrix3Type,
typename Vector6Type, typename D_Vector6Type, typename RowVectorXType, typename MatrixXType>
EIGEN_ALWAYS_INLINE void
D_Accel(IndexType ID,
bool zeroFlag,
ScalarType u,
ScalarType iD,
ScalarType* ddq,
const Eigen::MatrixBase<Vector3Type> & S,
const Eigen::MatrixBase<Vector3Type> & P_,
const Eigen::MatrixBase<Matrix3Type> & R_,
const Eigen::MatrixBase<Vector6Type> & c_,
const Eigen::MatrixBase<Vector6Type> & U_,
Eigen::MatrixBase<Vector6Type> & A_,
const Eigen::MatrixBase<Vector6Type> & Aj_,
bool isLeaf,
std::vector< IndexType >* Pre_,
std::vector< IndexType >* Suc_,
std::vector< IndexType >* PreSuc_,
Eigen::MatrixBase<D_Vector6Type> & D_U_h_,
Eigen::MatrixBase<RowVectorXType> & D_invD_,
Eigen::MatrixBase<MatrixXType> & D_ddq_,
Eigen::MatrixBase<RowVectorXType> & D_q_u_,
Eigen::MatrixBase<RowVectorXType> & D_dq_u_,
Eigen::MatrixBase<D_Vector6Type> & D_q_c_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_c_,
Eigen::MatrixBase<D_Vector6Type> & D_q_A_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_A_,
Eigen::MatrixBase<D_Vector6Type> & D_q_Aj_,
Eigen::MatrixBase<D_Vector6Type> & D_dq_Aj_) {
static_cast<Derived*>(this)->runD_Accel(ID, zeroFlag, u, iD, ddq, S, P_, R_, c_, U_, A_, Aj_, isLeaf, Pre_, Suc_, PreSuc_, D_U_h_, D_invD_,
D_ddq_, D_q_u_, D_dq_u_, D_q_c_, D_dq_c_, D_q_A_, D_dq_A_, D_q_Aj_, D_dq_Aj_);
}
};
}
#include "DJointDerived/DJointDerived.hpp"
#include "DJointDerived/DVisitors.hxx"
#endif // GEOMBD_JOINT_BASE_DIFFERENTIATION_CRTP_HXX
| 48.829876 | 145 | 0.592284 | garechav |
cd49f7c4a184424639af62ff5022ff61a394ae59 | 963 | cpp | C++ | 0071 Simplify Path/solution.cpp | Aden-Tao/LeetCode | c34019520b5808c4251cb76f69ca2befa820401d | [
"MIT"
] | 1 | 2019-12-19T04:13:15.000Z | 2019-12-19T04:13:15.000Z | 0071 Simplify Path/solution.cpp | Aden-Tao/LeetCode | c34019520b5808c4251cb76f69ca2befa820401d | [
"MIT"
] | null | null | null | 0071 Simplify Path/solution.cpp | Aden-Tao/LeetCode | c34019520b5808c4251cb76f69ca2befa820401d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string simplifyPath(string path) {
if (path.back() != '/') path += '/';
string res, s;
for (auto &c : path)
{
if (res.empty()) res += c;
else if (c == '/')
{
if (s == "..")
{
if (res.size() > 1)
{
res.pop_back();
while (res.back() != '/') res.pop_back();
}
}
else if (s != "" && s != ".")
{
res += s + '/';
}
s = "";
}
else
{
s += c;
}
}
if (res.size() > 1) res.pop_back();
return res;
}
};
int main(){
assert(Solution().simplifyPath("/home//foo/") == "/home/foo");
return 0;
} | 22.928571 | 66 | 0.298027 | Aden-Tao |
cd4d1bae880e0dda4505079c61cb2fd611e8eda9 | 1,010 | cpp | C++ | src/Standard/FirstPersonCameraController.cpp | HyperionDH/Tristeon | 8475df94b9dbd4e3b4cc82b89c6d4bab45acef29 | [
"MIT"
] | 38 | 2017-12-04T10:48:28.000Z | 2018-05-11T09:59:41.000Z | src/Standard/FirstPersonCameraController.cpp | Tristeon/Tristeon3D | 8475df94b9dbd4e3b4cc82b89c6d4bab45acef29 | [
"MIT"
] | 9 | 2017-12-04T09:58:55.000Z | 2018-02-05T00:06:41.000Z | src/Standard/FirstPersonCameraController.cpp | Tristeon/Tristeon3D | 8475df94b9dbd4e3b4cc82b89c6d4bab45acef29 | [
"MIT"
] | 3 | 2018-01-10T13:39:12.000Z | 2018-03-17T20:53:22.000Z | #include "FirstPersonCameraController.h"
#include "Core/Transform.h"
#include "Misc/Hardware/Mouse.h"
#include "Misc/Hardware/Time.h"
#include "XPlatform/typename.h"
namespace Tristeon
{
namespace Standard
{
DerivedRegister<FirstPersonCameraController> FirstPersonCameraController::reg;
nlohmann::json FirstPersonCameraController::serialize()
{
nlohmann::json j;
j["typeID"] = TRISTEON_TYPENAME(FirstPersonCameraController);
j["sensitivity"] = sensitivity;
return j;
}
void FirstPersonCameraController::deserialize(nlohmann::json json)
{
sensitivity = json["sensitivity"];
}
void FirstPersonCameraController::start()
{
}
void FirstPersonCameraController::update()
{
float const x = Misc::Mouse::getMouseDelta().x * sensitivity * Misc::Time::getDeltaTime();
float const y = Misc::Mouse::getMouseDelta().y * sensitivity * Misc::Time::getDeltaTime();
xRot -= y;
yRot -= x;
transform.get()->rotation = Math::Quaternion::euler(xRot, yRot, 0);
}
}
}
| 24.634146 | 93 | 0.715842 | HyperionDH |
cd5175264eeaf261eed1956dba071251b8e5418c | 3,924 | cpp | C++ | ParticleShooter/Polygon.cpp | fuzzwaz/ParticleShooter | 9165f5142d797b223e73d145de80317b1fdababf | [
"Apache-2.0"
] | 1 | 2021-09-10T00:44:09.000Z | 2021-09-10T00:44:09.000Z | Fuzzy2D/Polygon.cpp | fuzzwaz/Fuzzy2D-Game-Engine | 1258bb0268a5be5925ce31f7c7edbdcf87eb27c2 | [
"Apache-2.0"
] | null | null | null | Fuzzy2D/Polygon.cpp | fuzzwaz/Fuzzy2D-Game-Engine | 1258bb0268a5be5925ce31f7c7edbdcf87eb27c2 | [
"Apache-2.0"
] | null | null | null | #include "Common.h"
#include "Polygon.h"
#include "Vector2.h"
Polygon::Polygon()
{
_vertices.reset(new std::vector<Vector2>());
_perpendiculars.reset(new std::vector<Vector2>());
}
void Polygon::operator=(const Polygon& source)
{
if (this == &source)
return;
_vertices->clear();
_perpendiculars->clear();
_vertices->insert(_vertices->end(), source._vertices->cbegin(), source._vertices->cend());
_perpendiculars->insert(_perpendiculars->end(), source._perpendiculars->cbegin(), source._perpendiculars->cend());
}
void Polygon::AddVertexPoint(float x, float y)
{
AddVertexPoint(Vector2(x, y));
}
void Polygon::AddVertexPoint(const Vector2& vertex)
{
_vertices->push_back(vertex);
_numOfVertices++;
_dirtyPerpendiculars = true; //New vertex means a new edge has been added. Perpendiculars need to be recalculated
RecalculateCenterPoint();
}
void Polygon::AddVertexPoint(const std::vector<Vector2>& vertices)
{
for (auto it = vertices.begin(); it != vertices.end(); it++)
{
AddVertexPoint(*it);
}
}
/*
Description:
A getter which can trigger a Perpendicular recalculation if marked as dirty
Returns:
shared_ptr<vector<Vector2>> - Pointer to the cached perpendiculars for this Collider
*/
const std::shared_ptr<const std::vector<Vector2>> Polygon::GetPerpendiculars() const
{
if (_dirtyPerpendiculars)
{
RecalculatePerpendicularVectors();
}
return _perpendiculars;
}
/*
Description:
Rotates each vertex point by "degrees" degrees clockwise. Sets the dirty flag for perpendiculars.
Arguments:
degrees - Clockwise rotatation
*/
void Polygon::Rotate(float degrees)
{
const float radians = CommonHelpers::DegToRad(degrees);
for (int i = 0; i < _vertices->size(); i++)
{
float newX = (_vertices->at(i).x * cos(radians)) + (_vertices->at(i).y * sin(radians) * -1);
float newY = (_vertices->at(i).x * sin(radians)) + (_vertices->at(i).y * cos(radians));
_vertices->at(i).x = newX;
_vertices->at(i).y = newY;
}
if (degrees != 0)
_dirtyPerpendiculars = true;
}
/*
Description:
Resets the current Perpendicular list. Goes through each edge in the polygon and calculates a
clockwise perpendicular vector. Adds that vector to _perpendiculars.
Clears the dirty flag
*/
void Polygon::RecalculatePerpendicularVectors() const
{
_perpendiculars->clear();
if (_vertices->size() >= 2)
{
for (int i = 0; i < _vertices->size() - 1; i++)
{
_perpendiculars->push_back(ClockwisePerpendicularVector(_vertices->at(i), _vertices->at(i + 1)));
}
//Wrap the last vertex to the first for the final polygon perpendicular
_perpendiculars->push_back(ClockwisePerpendicularVector(_vertices->at(_vertices->size() - 1), _vertices->at(0)));
}
_dirtyPerpendiculars = false;
}
void Polygon::RecalculateCenterPoint()
{
float minX = INT_MAX, minY = INT_MAX;
float maxX = INT_MIN, maxY = INT_MIN;
for (int i = 0; i < _vertices->size(); i++)
{
Vector2 vertex(_vertices->at(i));
if (vertex.x < minX)
minX = vertex.x;
if (vertex.x > maxX)
maxX = vertex.x;
if (vertex.y < minY)
minY = vertex.y;
if (vertex.y > maxY)
maxY = vertex.y;
}
Vector2 sizeVector(maxX - minX, maxY - minY);
_center.x = (sizeVector.x / 2) + minX;
_center.y = (sizeVector.y / 2) + minY;
}
Vector2 ClockwisePerpendicularVector(const Vector2& pointA, const Vector2& pointB)
{
const Vector2 clockwiseVector(pointB.x - pointA.x, pointB.y - pointA.y);
return ClockwisePerpendicularVector(clockwiseVector);
}
Vector2 ClockwisePerpendicularVector(const Vector2& vector)
{
return Vector2(vector.y, -1 * vector.x);
}
Vector2 CounterClockwisePerpendicularVector(const Vector2& pointA, const Vector2& pointB)
{
const Vector2 counterClockwiseVector(pointB.x - pointA.x, pointB.y - pointA.y);
return CounterClockwisePerpendicularVector(counterClockwiseVector);
}
Vector2 CounterClockwisePerpendicularVector(const Vector2& vector)
{
return Vector2(-1 * vector.y, vector.x);
} | 25.480519 | 115 | 0.717635 | fuzzwaz |
cd5192159d2d380d6bb84e44bfdf7fbeccf894f7 | 1,695 | cc | C++ | src/FractalStruct/force_at_particle.cc | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/FractalStruct/force_at_particle.cc | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/FractalStruct/force_at_particle.cc | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | #include "libs.hh"
#include "classes.hh"
#include "headers.hh"
namespace FractalSpace
{
void force_at_particle(Group& group, Fractal& fractal,const bool& conserve)
{
fractal.timing(-1,8);
ofstream& FileFractal=fractal.p_file->DUMPS;
vector <double> dens(8);
vector <double> weights(8);
vector <double> pott(8);
vector <double> f_x(8);
vector <double> f_y(8);
vector <double> f_z(8);
vector <double> sum_pf(4);
Group* p_group=&group;
double d_x,d_y,d_z;
vector <double> pos(3);
double d_inv=pow(2.0,group.get_level()-fractal.get_level_max());
const double scale=(double)(fractal.get_grid_length()*Misc::pow(2,fractal.get_level_max()));
//
for(auto &p : group.list_points)
{
Point& point=*p;
if(point.list_particles.empty()) continue;
bool not_yet=true;
for(auto &part : point.list_particles)
{
Particle& particle=*part;
if(!particle.get_real_particle())
continue;
if(particle.get_p_highest_level_group() != 0)
{
if(conserve || p_group == particle.get_p_highest_level_group())
{
if(not_yet)
{
point.get_field_values(pott,f_x,f_y,f_z);
not_yet=false;
}
//
particle.get_pos(pos);
point.get_deltas(pos,d_x,d_y,d_z,scale,d_inv);
Misc::set_weights(weights,d_x,d_y,d_z);
Misc::sum_prod<double>(0,7,1,sum_pf,weights,pott,f_x,f_y,f_z);
particle.set_field_pf(sum_pf);
if(sum_pf[0]*sum_pf[1]*sum_pf[2]*sum_pf[3] ==0.0)
particle.dump(FileFractal,pott,f_x,f_y,f_z);
}
}
else
{
particle.dump(FileFractal);
particle.set_field_pf(0.0);
}
}
}
fractal.timing(1,8);
}
}
| 27.33871 | 97 | 0.632448 | jmikeowen |
cd54b296c3370bee409421ff58e93b1bb0ca1fc3 | 4,596 | hpp | C++ | include/realm/core/component.hpp | pyrbin/realm.hpp | e34b18ce1f5c39b080a9e70f675adf740490ff83 | [
"MIT"
] | 2 | 2020-03-01T18:15:27.000Z | 2020-03-25T10:21:59.000Z | include/realm/core/component.hpp | pyrbin/realm.hpp | e34b18ce1f5c39b080a9e70f675adf740490ff83 | [
"MIT"
] | null | null | null | include/realm/core/component.hpp | pyrbin/realm.hpp | e34b18ce1f5c39b080a9e70f675adf740490ff83 | [
"MIT"
] | 1 | 2020-03-25T10:22:00.000Z | 2020-03-25T10:22:00.000Z | #pragma once
#include <cstddef>
#include <functional>
#include <iostream>
#include <vector>
#include <realm/util/identifier.hpp>
#include <realm/util/type_traits.hpp>
namespace realm {
/**
* @brief Memory layout
* Describes a particular layout of memory. Inspired by Rust's alloc::Layout.
* @ref https://doc.rust-lang.org/std/alloc/struct.Layout.html
*/
struct memory_layout
{
const unsigned size{ 0 };
const unsigned align{ 0 };
constexpr memory_layout() = default;
constexpr memory_layout(const unsigned size, const unsigned align)
: size{ size }
, align{ align }
{
/**
* TODO: add some necessary checks, eg. align has to be power of 2
* see Rust impl. for examples
*/
}
/**
* Create a memory layout of a specified type
* @tparam T
* @return
*/
template<typename T>
static constexpr memory_layout of()
{
return { sizeof(T), alignof(T) };
}
/**
* @brief Returns the amount of padding that has to be added to size to satisfy the
* layouts alignment
* @param size
* @param align
* @return Padding to insert
*/
static constexpr int align_up(const int size, const int align) noexcept
{
return (size + (align - 1)) & !(align - 1);
}
[[nodiscard]] constexpr int align_up(const int size) const noexcept
{
return align_up(size, align);
}
};
/**
* @brief Component meta
* Describes component metadata of a specified type.
*/
struct component_meta
{
const u64 hash{ 0 };
const u64 mask{ 0 };
constexpr component_meta() = default;
constexpr component_meta(const u64 hash, const u64 mask)
: hash{ hash }
, mask{ mask } {};
/**
* Create component meta of a type.
* @tparam T
* @return
*/
template<typename T>
static constexpr internal::enable_if_component<T, component_meta> of()
{
return component_meta{ internal::identifier_hash_v<internal::pure_t<T>>,
internal::identifier_mask_v<internal::pure_t<T>> };
}
};
/**
* @brief Component
* Describes a component (metadata, memory layout & functions for construction and
* destruction).
*/
struct component
{
using constructor_t = void(void*);
const component_meta meta;
const memory_layout layout;
constructor_t* alloc{ nullptr };
constructor_t* destroy{ nullptr };
constexpr component() = default;
constexpr component(
component_meta meta, memory_layout layout, constructor_t* alloc, constructor_t* destroy)
: meta{ meta }
, layout{ layout }
, alloc{ alloc }
, destroy{ destroy }
{}
constexpr bool operator==(const component& other) const { return other.meta.hash == meta.hash; }
/**
* Create a component of a specified type
* @tparam T
* @return
*/
template<typename T>
static constexpr internal::enable_if_component<T, component> of()
{
return { component_meta::of<T>(), memory_layout::of<T>(), [](void* ptr) { new (ptr) T{}; },
[](void* ptr) { static_cast<T*>(ptr)->~T(); } };
}
};
/**
* @brief Singleton component
* Singleton component base class
*/
struct singleton_component
{
singleton_component() = default;
singleton_component(component&& comp)
: component_info{ comp } {};
virtual ~singleton_component() = default;
const component component_info;
};
/**
* @brief Singleton instance
* Stores a single component using a unique_ptr.
* Currently used in world to store singleton components.
* @tparam T
*/
template<typename T>
struct singleton_instance final : singleton_component
{
explicit singleton_instance(T& t)
: singleton_component{ component::of<T>() }
, instance_{ std::unique_ptr<T>(std::move(t)) }
{}
template<typename... Args>
explicit singleton_instance(Args&&... args)
: singleton_component{ component::of<T>() }
, instance_{ std::make_unique<T>(std::forward<Args>(args)...) }
{}
/**
* Get the underlying component instance
* @return Pointer to component instance
*/
T* get() { return static_cast<T*>(instance_.get()); }
private:
const std::unique_ptr<T> instance_;
};
} // namespace realm
/**
* @cond TURN_OFF_DOXYGEN
* Internal details not to be documented.
*/
namespace std {
template<>
struct hash<realm::component>
{
size_t operator()(const realm::component& c) const noexcept
{
return (hash<size_t>{}(c.meta.hash));
}
};
} // namespace std | 24.446809 | 100 | 0.629896 | pyrbin |
cd5b3fd49836834a174cc6548e2045163fc7744e | 4,738 | hpp | C++ | src/main/cpp/Balau/Dev/Assert.hpp | borasoftware/balau | 8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14 | [
"Apache-2.0"
] | 6 | 2018-12-30T15:09:26.000Z | 2020-04-20T09:27:59.000Z | src/main/cpp/Balau/Dev/Assert.hpp | borasoftware/balau | 8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14 | [
"Apache-2.0"
] | null | null | null | src/main/cpp/Balau/Dev/Assert.hpp | borasoftware/balau | 8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14 | [
"Apache-2.0"
] | 2 | 2019-11-12T08:07:16.000Z | 2019-11-29T11:19:47.000Z | // @formatter:off
//
// Balau core C++ library
//
// Copyright (C) 2008 Bora Software (contact@borasoftware.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.
//
///
/// @file Assert.hpp
///
/// Assertion utilities for development purposes.
///
#ifndef COM_BORA_SOFTWARE__BALAU_DEV__ASSERT
#define COM_BORA_SOFTWARE__BALAU_DEV__ASSERT
#include <boost/core/ignore_unused.hpp>
#include <string>
#ifdef BALAU_ENABLE_STACKTRACES
#include <boost/stacktrace.hpp>
#endif
#include <iostream>
#include <sstream>
namespace Balau {
///
/// An assertion class for development purposes.
///
class Assert {
///
/// Abort after logging the message.
///
public: static void fail(const char * fatalMessage) {
performAssertion(false, fatalMessage, "Fail called");
}
///////////////////////////////////////////////////////////////////////////
///
/// If the bug test assertion fails, abort after logging the message supplied by the function.
///
public: template <typename StringFunctionT>
static void assertion(bool test, StringFunctionT function) {
performAssertion(test, function, "Bug found");
}
///
/// If the bug test assertion fails, abort after logging the message.
///
public: static void assertion(bool test, const char * fatalMessage) {
performAssertion(test, fatalMessage, "Bug found");
}
///
/// Abort if the bug test fails.
///
public: static void assertion(bool test) {
performAssertion(test, "", "Bug found");
}
///
/// If the bug test assertion predicate function fails, abort after logging the message supplied by the function.
///
public: template <typename TestFunctionT, typename StringFunctionT>
static void assertion(TestFunctionT test, StringFunctionT function) {
performAssertion(test, function, "Bug found");
}
///
/// If the bug test assertion predicate function fails, abort after logging the message.
///
public: template <typename TestFunctionT>
static void assertion(TestFunctionT test, const char * fatalMessage) {
performAssertion(test, fatalMessage, "Bug found");
}
///
/// Abort if the bug test assertion predicate function fails.
///
public: template <typename TestFunctionT>
static void assertion(TestFunctionT test) {
performAssertion(test, "", "Bug found");
}
///////////////////////////////////////////////////////////////////////////
private: template <typename FunctionT>
static void performAssertion(bool test, FunctionT function, const char * testType) {
boost::ignore_unused(test);
boost::ignore_unused(function);
boost::ignore_unused(testType);
#ifdef BALAU_DEBUG
if (!test) {
const std::string message = function();
abortProcess(message.c_str(), testType);
}
#endif
}
private: template <typename TestT, typename FunctionT>
static void performAssertion(TestT test, FunctionT function, const char * testType) {
boost::ignore_unused(test);
boost::ignore_unused(function);
boost::ignore_unused(testType);
#ifdef BALAU_DEBUG
if (!test()) {
const std::string message = function();
abortProcess(message.c_str(), testType);
}
#endif
}
private: static void performAssertion(bool test, const char * fatalMessage, const char * testType) {
boost::ignore_unused(test);
boost::ignore_unused(fatalMessage);
boost::ignore_unused(testType);
#ifdef BALAU_DEBUG
if (!test) {
abortProcess(fatalMessage, testType);
}
#endif
}
private: template <typename TestT>
static void performAssertion(TestT test, const char * fatalMessage, const char * testType) {
boost::ignore_unused(test);
boost::ignore_unused(fatalMessage);
boost::ignore_unused(testType);
#ifdef BALAU_DEBUG
if (!test()) {
abortProcess(fatalMessage, testType);
}
#endif
}
private: static void abortProcess(const char * fatalMessage, const char * testType) {
std::ostringstream str;
if (fatalMessage != nullptr) {
str << testType << ": " << fatalMessage << "\n";
} else {
str << testType << "\n";
}
#ifdef BALAU_ENABLE_STACKTRACES
str << "Stack trace: " << boost::stacktrace::stacktrace() << "\n";
#endif
str << "Program will abort now\n";
std::cerr << str.str();
abort();
}
};
} // namespace Balau
#endif // COM_BORA_SOFTWARE__BALAU_DEV__ASSERT
| 26.768362 | 114 | 0.689109 | borasoftware |
cd5cd82914164fe87e414e025406662814b15a1b | 2,913 | cpp | C++ | src/projects/scripts/run.cpp | AntonBankevich/DR | 73450ad3b25f90a3c7747aaf17fe60d13d9692d3 | [
"BSD-3-Clause"
] | 3 | 2020-11-14T14:41:55.000Z | 2020-12-12T07:05:51.000Z | src/projects/scripts/run.cpp | AntonBankevich/DR | 73450ad3b25f90a3c7747aaf17fe60d13d9692d3 | [
"BSD-3-Clause"
] | 1 | 2022-02-01T11:16:31.000Z | 2022-02-01T18:56:55.000Z | src/projects/scripts/run.cpp | AntonBankevich/DR | 73450ad3b25f90a3c7747aaf17fe60d13d9692d3 | [
"BSD-3-Clause"
] | null | null | null | #include <common/verify.hpp>
#include <experimental/filesystem>
#include <fstream>
#include <unistd.h>
#include <common/dir_utils.hpp>
#include <common/string_utils.hpp>
std::string getFirst(const std::experimental::filesystem::path &cfile) {
std::string res;
std::ifstream is;
is.open(cfile);
std::getline(is, res);
is.close();
return std::move(res);
}
void removeFirst(const std::experimental::filesystem::path &cfile) {
std::vector<std::string> contents;
std::string next;
std::ifstream is;
is.open(cfile);
while(std::getline(is, next)) {
if(!next.empty()) {
contents.emplace_back(next);
}
}
is.close();
std::ofstream os;
os.open(cfile);
contents.erase(contents.begin());
for(std::string &line : contents) {
os << line << "\n";
}
os.close();
}
void append(const std::experimental::filesystem::path &cfile, const std::string &next) {
std::ofstream os;
os.open(cfile, std::ios_base::app);
os << next << "\n";
os.close();
}
int main(int argc, char **argv) {
VERIFY(argc == 3);
std::experimental::filesystem::path cfile(argv[1]);
std::experimental::filesystem::path dir(argv[2]);
ensure_dir_existance(dir);
ensure_dir_existance(dir / "logs");
std::experimental::filesystem::path log_path = dir/"log.txt";
size_t max = 0;
for(const std::experimental::filesystem::path &p :std::experimental::filesystem::directory_iterator(dir / "logs")){
max = std::max<size_t>(max, std::stoull(p.filename()));
}
bool slept = false;
#pragma clang diagnostic push
#pragma ide diagnostic ignored "EndlessLoop"
while(true) {
std::string command = getFirst(cfile);
if(command.empty()) {
if(!slept) {
std::cout << "No command. Sleeping." << std::endl;
slept = true;
}
sleep(60);
} else {
slept = false;
std::cout << "Running new command: " << command << std::endl;
std::experimental::filesystem::path log(dir/"logs"/itos(max + 1));
std::cout << "Printing output to file " << log << std::endl;
std::ofstream os;
os.open(log_path, std::ios_base::app);
os << (max + 1) << " started\n" << command << "\n";
os.close();
int res = system((command + " > " + log.string() + " 2>&1").c_str());
std::cout << "Finished running command: " << command << std::endl;
std::cout << "Return code: " << res << "\n\n" << std::endl;
std::ofstream os1;
os1.open(log_path, std::ios_base::app);
os1 << (max + 1) << " finished " << res << "\n\n";
os1.close();
max++;
removeFirst(cfile);
append(dir / "finished.txt", command);
}
}
#pragma clang diagnostic pop
} | 33.482759 | 119 | 0.557501 | AntonBankevich |
cd6085a4c75c956e4f3511e5d4460f2db121b6ba | 6,017 | cc | C++ | contrib/gcc-4.1/libstdc++-v3/src/ios.cc | masami256/dfly-3.0.2-bhyve | 6f6c18db6fa90734135a2044769035eb82b821c1 | [
"BSD-3-Clause"
] | 3 | 2017-03-06T14:12:57.000Z | 2019-11-23T09:35:10.000Z | contrib/gcc-4.1/libstdc++-v3/src/ios.cc | masami256/dfly-3.0.2-bhyve | 6f6c18db6fa90734135a2044769035eb82b821c1 | [
"BSD-3-Clause"
] | null | null | null | contrib/gcc-4.1/libstdc++-v3/src/ios.cc | masami256/dfly-3.0.2-bhyve | 6f6c18db6fa90734135a2044769035eb82b821c1 | [
"BSD-3-Clause"
] | null | null | null | // Iostreams base classes -*- C++ -*-
// Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
// As a special exception, you may use this file as part of a free software
// library without restriction. Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License. This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.
//
// ISO C++ 14882: 27.4 Iostreams base classes
//
#include <ios>
#include <limits>
#include <bits/atomicity.h>
namespace std
{
// Definitions for static const members of ios_base.
const ios_base::fmtflags ios_base::boolalpha;
const ios_base::fmtflags ios_base::dec;
const ios_base::fmtflags ios_base::fixed;
const ios_base::fmtflags ios_base::hex;
const ios_base::fmtflags ios_base::internal;
const ios_base::fmtflags ios_base::left;
const ios_base::fmtflags ios_base::oct;
const ios_base::fmtflags ios_base::right;
const ios_base::fmtflags ios_base::scientific;
const ios_base::fmtflags ios_base::showbase;
const ios_base::fmtflags ios_base::showpoint;
const ios_base::fmtflags ios_base::showpos;
const ios_base::fmtflags ios_base::skipws;
const ios_base::fmtflags ios_base::unitbuf;
const ios_base::fmtflags ios_base::uppercase;
const ios_base::fmtflags ios_base::adjustfield;
const ios_base::fmtflags ios_base::basefield;
const ios_base::fmtflags ios_base::floatfield;
const ios_base::iostate ios_base::badbit;
const ios_base::iostate ios_base::eofbit;
const ios_base::iostate ios_base::failbit;
const ios_base::iostate ios_base::goodbit;
const ios_base::openmode ios_base::app;
const ios_base::openmode ios_base::ate;
const ios_base::openmode ios_base::binary;
const ios_base::openmode ios_base::in;
const ios_base::openmode ios_base::out;
const ios_base::openmode ios_base::trunc;
const ios_base::seekdir ios_base::beg;
const ios_base::seekdir ios_base::cur;
const ios_base::seekdir ios_base::end;
_Atomic_word ios_base::Init::_S_refcount;
bool ios_base::Init::_S_synced_with_stdio = true;
ios_base::ios_base()
: _M_precision(), _M_width(), _M_flags(), _M_exception(),
_M_streambuf_state(), _M_callbacks(0), _M_word_zero(),
_M_word_size(_S_local_word_size), _M_word(_M_local_word), _M_ios_locale()
{
// Do nothing: basic_ios::init() does it.
// NB: _M_callbacks and _M_word must be zero for non-initialized
// ios_base to go through ~ios_base gracefully.
}
// 27.4.2.7 ios_base constructors/destructors
ios_base::~ios_base()
{
_M_call_callbacks(erase_event);
_M_dispose_callbacks();
if (_M_word != _M_local_word)
{
delete [] _M_word;
_M_word = 0;
}
}
// 27.4.2.5 ios_base storage functions
int
ios_base::xalloc() throw()
{
// Implementation note: Initialize top to zero to ensure that
// initialization occurs before main() is started.
static _Atomic_word _S_top = 0;
return __gnu_cxx::__exchange_and_add(&_S_top, 1) + 4;
}
void
ios_base::register_callback(event_callback __fn, int __index)
{ _M_callbacks = new _Callback_list(__fn, __index, _M_callbacks); }
// 27.4.2.5 iword/pword storage
ios_base::_Words&
ios_base::_M_grow_words(int __ix, bool __iword)
{
// Precondition: _M_word_size <= __ix
int __newsize = _S_local_word_size;
_Words* __words = _M_local_word;
if (__ix > _S_local_word_size - 1)
{
if (__ix < numeric_limits<int>::max())
{
__newsize = __ix + 1;
try
{ __words = new _Words[__newsize]; }
catch (...)
{
_M_streambuf_state |= badbit;
if (_M_streambuf_state & _M_exception)
__throw_ios_failure(__N("ios_base::_M_grow_words "
"allocation failed"));
if (__iword)
_M_word_zero._M_iword = 0;
else
_M_word_zero._M_pword = 0;
return _M_word_zero;
}
for (int __i = 0; __i < _M_word_size; __i++)
__words[__i] = _M_word[__i];
if (_M_word && _M_word != _M_local_word)
{
delete [] _M_word;
_M_word = 0;
}
}
else
{
_M_streambuf_state |= badbit;
if (_M_streambuf_state & _M_exception)
__throw_ios_failure(__N("ios_base::_M_grow_words is not valid"));
if (__iword)
_M_word_zero._M_iword = 0;
else
_M_word_zero._M_pword = 0;
return _M_word_zero;
}
}
_M_word = __words;
_M_word_size = __newsize;
return _M_word[__ix];
}
void
ios_base::_M_call_callbacks(event __e) throw()
{
_Callback_list* __p = _M_callbacks;
while (__p)
{
try
{ (*__p->_M_fn) (__e, *this, __p->_M_index); }
catch (...)
{ }
__p = __p->_M_next;
}
}
void
ios_base::_M_dispose_callbacks(void)
{
_Callback_list* __p = _M_callbacks;
while (__p && __p->_M_remove_reference() == 0)
{
_Callback_list* __next = __p->_M_next;
delete __p;
__p = __next;
}
_M_callbacks = 0;
}
} // namespace std
| 30.85641 | 79 | 0.69769 | masami256 |
cd62b9eb823200cbe57965f55ecc0ad90ba578ba | 405 | hpp | C++ | src/TextFile.hpp | oleksandrkozlov/touch-typing | e38f315fa979ab66539c0a6a47796b5e6cabe0a2 | [
"MIT"
] | 1 | 2020-10-10T14:04:15.000Z | 2020-10-10T14:04:15.000Z | src/TextFile.hpp | oleksandrkozlov/touch-typing | e38f315fa979ab66539c0a6a47796b5e6cabe0a2 | [
"MIT"
] | 37 | 2020-04-19T12:37:03.000Z | 2021-06-06T09:33:37.000Z | src/TextFile.hpp | oleksandrkozlov/touch-typing | e38f315fa979ab66539c0a6a47796b5e6cabe0a2 | [
"MIT"
] | null | null | null | #ifndef TOUCH_TYPING_TEXT_FILER_HPP
#define TOUCH_TYPING_TEXT_FILER_HPP
#include <filesystem>
#include <string>
namespace touch_typing {
class TextFile {
public:
explicit TextFile(const std::filesystem::path& filename);
[[nodiscard]] auto asString() const noexcept -> const std::string&;
private:
std::string m_text;
};
} // namespace touch_typing
#endif // TOUCH_TYPING_TEXT_FILER_HPP
| 18.409091 | 71 | 0.753086 | oleksandrkozlov |
cd661369a54ab9c8aa3fdc9d51347c4ab770b7e6 | 3,534 | hpp | C++ | include/eve/module/bessel/detail/kernel_bessel_i.hpp | HadrienG2/eve | 3afdcfb524f88c0b88df9b54e25bbb9b33f518ec | [
"MIT"
] | null | null | null | include/eve/module/bessel/detail/kernel_bessel_i.hpp | HadrienG2/eve | 3afdcfb524f88c0b88df9b54e25bbb9b33f518ec | [
"MIT"
] | null | null | null | include/eve/module/bessel/detail/kernel_bessel_i.hpp | HadrienG2/eve | 3afdcfb524f88c0b88df9b54e25bbb9b33f518ec | [
"MIT"
] | null | null | null | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#pragma once
#include <eve/module/core.hpp>
#include <eve/module/math.hpp>
#include <eve/module/bessel/regular/cyl_bessel_i0.hpp>
#include <eve/module/bessel/regular/cyl_bessel_i1.hpp>
#include <eve/module/bessel/detail/kernel_bessel_ik.hpp>
#include <eve/module/bessel/detail/kernel_bessel_ij_small.hpp>
/////////////////////////////////////////////////////////////////////////////////
// These routines are detail of the computation of modifiesd cylindrical bessel
// fnctions of the first kind. .
// They are not meant to be called directly, as their validities depends on
// n and x ranges values which are not tested on entry.
// The inspiration is from boost math
/////////////////////////////////////////////////////////////////////////////////
namespace eve::detail
{
/////////////////////////////////////////////////////////////////////////
// bessel_i
template<floating_real_value T>
EVE_FORCEINLINE auto kernel_bessel_i (T n, T x) noexcept
{
auto br_small = [](auto n, auto x)
{
return bessel_i_small_z_series(n, x);
};
auto br_medium = [](auto n, auto x)
{
auto [in, ipn, kn, kpn] = kernel_bessel_ik(n, x);
return in;
};
auto br_half = [](auto x)
{
if(eve::any(x >= maxlog(as(x))))
{
auto ex = eve::exp(x/2);
return ex*(ex*rsqrt(x*twopi(as(x))));
}
else return rsqrt(x*pio_2(as(x)))*sinh(x);
};
if constexpr(scalar_value<T>)
{
if (is_ngez(x)) return nan(as(x));
if (is_eqz(x)) return (n == 0) ? one(as(x)) : zero(as(x));
if (x == inf(as(x))) return inf(as(x));
if (n == T(0.5)) return br_half(x); //cyl_bessel_i order 0.5
if (n == 0) return cyl_bessel_i0(x); //cyl_bessel_i0(x);
if (n == 1) return cyl_bessel_i1(x); //cyl_bessel_i1(x);
if (x*4 < n) return br_small(n, x); // serie
return br_medium(n, x); // general
}
else
{
auto r = nan(as(x));
auto isinfx = x == inf(as(x));
r = if_else(isinfx, inf(as(x)), allbits);
x = if_else(isinfx, mone, x);
auto iseqzx = is_eqz(x);
auto iseqzn = is_eqz(n);
if (eve::any(iseqzx))
{
r = if_else(iseqzx, if_else(iseqzn, zero, one(as(x))), r);
}
if (eve::any(iseqzn))
{
r = if_else(iseqzn, cyl_bessel_i0(x), r);
}
auto iseq1n = n == one(as(n));
if (eve::any(iseq1n))
{
r = if_else(n == one(as(n)), cyl_bessel_i1(x), r);
}
auto notdone = is_gez(x) && !(iseqzn || iseq1n) ;
x = if_else(notdone, x, allbits);
if( eve::any(notdone) )
{
notdone = next_interval(br_half, notdone, n == T(0.5), r, x);
if( eve::any(notdone) )
{
if( eve::any(notdone) )
{
notdone = last_interval(br_medium, notdone, r, n, x);
}
}
}
return r;
}
}
}
| 34.647059 | 101 | 0.44652 | HadrienG2 |
cd68929d6cfcef605b9da503ac4e87f494cd9ead | 1,295 | cpp | C++ | grid_map_filters/src/DeletionFilter.cpp | saikrn112/grid_map | f64a471c6fc9059a7db7e3327ff94a65f862d95c | [
"BSD-3-Clause"
] | 2 | 2019-04-18T01:26:21.000Z | 2021-07-14T01:23:05.000Z | grid_map_filters/src/DeletionFilter.cpp | saikrn112/grid_map | f64a471c6fc9059a7db7e3327ff94a65f862d95c | [
"BSD-3-Clause"
] | null | null | null | grid_map_filters/src/DeletionFilter.cpp | saikrn112/grid_map | f64a471c6fc9059a7db7e3327ff94a65f862d95c | [
"BSD-3-Clause"
] | 8 | 2018-02-20T17:33:33.000Z | 2021-07-18T20:48:36.000Z | /*
* DeletionFilter.cpp
*
* Created on: Mar 19, 2015
* Author: Martin Wermelinger, Peter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include "grid_map_filters/DeletionFilter.hpp"
#include <grid_map_core/GridMap.hpp>
#include <pluginlib/class_list_macros.h>
using namespace filters;
namespace grid_map {
template<typename T>
DeletionFilter<T>::DeletionFilter()
{
}
template<typename T>
DeletionFilter<T>::~DeletionFilter()
{
}
template<typename T>
bool DeletionFilter<T>::configure()
{
// Load Parameters
if (!FilterBase<T>::getParam(std::string("layers"), layers_)) {
ROS_ERROR("DeletionFilter did not find parameter 'layers'.");
return false;
}
return true;
}
template<typename T>
bool DeletionFilter<T>::update(const T& mapIn, T& mapOut)
{
mapOut = mapIn;
for (const auto& layer : layers_) {
// Check if layer exists.
if (!mapOut.exists(layer)) {
ROS_ERROR("Check your deletion layers! Type %s does not exist.",
layer.c_str());
continue;
}
if (!mapOut.erase(layer)) {
ROS_ERROR("Could not remove type %s.", layer.c_str());
}
}
return true;
}
} /* namespace */
PLUGINLIB_EXPORT_CLASS(grid_map::DeletionFilter<grid_map::GridMap>, filters::FilterBase<grid_map::GridMap>)
| 20.234375 | 107 | 0.680309 | saikrn112 |
cd6a0ac75ba33cbd688135f9d2195d3c74ea56fb | 411 | cpp | C++ | pepcoding_problem/decimal_to_any_base.cpp | sahilduhan/Learn-C-plus-plus | 80dba2ee08b36985deb297293a0318da5d6ace94 | [
"RSA-MD"
] | null | null | null | pepcoding_problem/decimal_to_any_base.cpp | sahilduhan/Learn-C-plus-plus | 80dba2ee08b36985deb297293a0318da5d6ace94 | [
"RSA-MD"
] | null | null | null | pepcoding_problem/decimal_to_any_base.cpp | sahilduhan/Learn-C-plus-plus | 80dba2ee08b36985deb297293a0318da5d6ace94 | [
"RSA-MD"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int get_value_base(int num, int base)
{
int rv = 0;
int p = 1;
while (num > 0)
{
int dig = num % base;
num = num / base;
rv += dig * p;
p = p * 10;
}
return rv;
}
int main()
{
int num = 634;
int base = 8;
int ans = 0;
ans = get_value_base(num, base);
cout << ans << endl;
return 0;
} | 15.807692 | 37 | 0.479319 | sahilduhan |
cd6b4e146f8b9dc27e50e2dccd2cfbba91574315 | 1,493 | cpp | C++ | art-of-prog/31-longest_inc_seq/31-longest_inc_seq.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | art-of-prog/31-longest_inc_seq/31-longest_inc_seq.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | art-of-prog/31-longest_inc_seq/31-longest_inc_seq.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cstdlib>
/**< 问题:最长递增子序列 */
// Ref: http://blog.csdn.net/joylnwang/article/details/6766317
// Ref: http://qiemengdao.iteye.com/blog/1660229
/* 给定一个长度为 N 的数组 a0, a1, a2, ..., an - 1,找出一个最长的单调递增子序列
* 递增的意思是对于任意的 i < j,都满足 ai < aj,此外子序列的意思是不要求连续,顺序不乱即可。
* 例如,长度为 6 的数组 A = {5, 6, 7, 1, 2, 8},则其最长的单调递增子序列为 {5, 6, 7, 8},长度为 4。 */
int LIncSeq1(int const* inArr, int const len)
{
if (len < 0) return len;
int* const dp = new int[len];
int* const pre = new int[len]; // 储存开始位置
for (int k = 0; k < len; ++k) { dp[k] = 1; pre[k] = k; }
// 寻找以 k 为末尾的最长递增子序列
for (int k = 1; k < len; ++k)
for (int m = 0; m < k; ++m)
{
if (inArr[m] < inArr[k] && dp[k] < dp[m] + 1)
{
dp[k] = dp[m] + 1;
pre[k] = m;
}
}
int liss = 1; int iE = 0; // 末尾
for (int k = 1; k < len; ++k)
if (liss < dp[k])
{
liss = dp[k];
iE = k;
}
int* rst = new int[liss];
int pos = liss - 1;
while (pre[iE] != iE)
{
rst[pos] = inArr[iE];
--pos;
iE = pre[iE];
}
rst[pos] = inArr[iE];
// 输出原始数组和结果
printf("\nArray (%d):\n", len);
for (int k = 0; k < len; ++k)
printf(" %+d", inArr[k]);;
printf("\nLongest Increase Sub-Sequence (%d):\n", liss);
for (int k = 0; k < liss; ++k)
printf(" %+d", rst[k]);
delete[] dp; delete[] pre; delete[] rst;
return liss;
}
int main()
{
int const arr1[] = { 35, 36, 39, 3, 15, 27, 6, 42 };
int const n1 = sizeof(arr1) / sizeof(arr1[0]);
LIncSeq1(arr1, n1);
printf("\n");
return 0;
}
| 22.283582 | 75 | 0.536504 | Ginkgo-Biloba |
cd6c4ec5bc7be4140ea8941d1cbc673016774ea5 | 2,739 | cpp | C++ | src/volt/config.cpp | voltengine/volt | fbefe2e0a8e461b6130ffe926870c4848bd6e7d1 | [
"MIT"
] | null | null | null | src/volt/config.cpp | voltengine/volt | fbefe2e0a8e461b6130ffe926870c4848bd6e7d1 | [
"MIT"
] | null | null | null | src/volt/config.cpp | voltengine/volt | fbefe2e0a8e461b6130ffe926870c4848bd6e7d1 | [
"MIT"
] | null | null | null | #include <volt/pch.hpp>
#include <volt/config.hpp>
#include <volt/util/util.hpp>
#include <volt/log.hpp>
#include <volt/paths.hpp>
namespace fs = std::filesystem;
namespace nl = nlohmann;
#ifdef VOLT_DEVELOPMENT
static nl::json base_config;
#endif
static nl::json default_config, config;
static nl::json cleave(nl::json from, const nl::json &what) {
// Cleave from + what
std::stack<std::pair<nl::json &, const nl::json &>> objects_to_cleave;
objects_to_cleave.emplace(from, what);
while (!objects_to_cleave.empty()) {
nl::json &from = objects_to_cleave.top().first;
const nl::json &what = objects_to_cleave.top().second;
objects_to_cleave.pop();
for (auto it = from.begin(); it != from.end();) {
auto prev = it++;
if (what.contains(prev.key())) {
nl::json &from_v = prev.value();
const nl::json &what_v = what[prev.key()];
if (from_v == what_v)
from.erase(prev);
else if (from_v.is_object() && what_v.is_object())
objects_to_cleave.emplace(from_v, what_v);
}
}
}
return from;
}
namespace volt::config {
static void load_from_data() {
try {
::config.update(nl::json::parse(util::read_text_file(
paths::data() / "config.json")));
VOLT_LOG_INFO("User configuration has been loaded.")
} catch (...) {
VOLT_LOG_INFO("No user configuration available.")
}
}
nl::json &json() {
return ::config;
}
void save() {
nl::json cleaved = cleave(::config, default_config);
util::write_file(paths::data() / "config.json", cleaved.dump(1, '\t'));
}
void reset_to_default() {
::config = default_config;
}
#ifdef VOLT_DEVELOPMENT
void save_default() {
nl::json cleaved = cleave(default_config, base_config);
util::write_file(fs::path(VOLT_DEVELOPMENT_PATH) /
"config.json", cleaved.dump(1, '\t'));
}
void reset_to_base() {
::config = default_config = base_config;
}
void load() {
load_from_data();
}
#endif
}
namespace volt::config::_internal {
void init() {
#ifdef VOLT_DEVELOPMENT
std::vector<std::string> paths = util::split(util::read_text_file(
fs::path(VOLT_DEVELOPMENT_PATH) / "cache" / "packages.txt"), "\n");
base_config = nl::json::object();
for (auto &path_item : paths) {
auto path = path_item.substr(path_item.find(' ') + 1) / fs::path("config.json");
if (fs::exists(path))
base_config.update(nl::json::parse(util::read_text_file(path)));
}
default_config = base_config;
auto path = fs::path(VOLT_DEVELOPMENT_PATH) / "config.json";
if (fs::exists(path))
default_config.update(nl::json::parse(util::read_text_file(path)));
#else
default_config = nl::json::parse(util::read_text_file(
fs::current_path() / ".." / "config.json"));
#endif
::config = default_config;
#ifndef VOLT_DEVELOPMENT
load_from_data();
#endif
}
}
| 22.636364 | 82 | 0.676159 | voltengine |
cd70c8416a48b9fcb1fee0c060b9d22f4b4d9b86 | 11,349 | cpp | C++ | samples/ExternalFunction/ExternalFunction.cpp | kidaa/xalan-c | bb666d0ab3d0a192410823e6857c203d83c27b16 | [
"Apache-2.0"
] | null | null | null | samples/ExternalFunction/ExternalFunction.cpp | kidaa/xalan-c | bb666d0ab3d0a192410823e6857c203d83c27b16 | [
"Apache-2.0"
] | 1 | 2021-08-18T12:32:31.000Z | 2021-08-18T12:32:31.000Z | samples/ExternalFunction/ExternalFunction.cpp | AaronNGray/xalan | 6741bbdcb64a9d33df8bd7e21b558d66bb4292ec | [
"Apache-2.0"
] | null | null | null | /*
* 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 <xalanc/Include/PlatformDefinitions.hpp>
#include <cmath>
#include <cstring>
#include <ctime>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream.h>
#else
#include <iostream>
#endif
#include <xercesc/util/PlatformUtils.hpp>
#include <xalanc/XalanTransformer/XalanTransformer.hpp>
#include <xalanc/XPath/Function.hpp>
#include <xalanc/XPath/XObjectFactory.hpp>
XALAN_USING_XALAN(Function)
XALAN_USING_XALAN(Locator)
XALAN_USING_XALAN(XPathExecutionContext)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XObjectPtr)
XALAN_USING_XALAN(MemoryManager)
XALAN_USING_XALAN(XalanCopyConstruct)
// This class defines a function that will return the square root
// of its argument.
class FunctionSquareRoot : public Function
{
public:
/**
* Execute an XPath function object. The function must return a valid
* object. Extension functions should override this version of execute(),
* rather than one of the other calls designed for a specific number of
* arguments.
*
* @param executionContext executing context
* @param context current context node
* @param args vector of pointers to XObject arguments
* @param locator Locator for the XPath expression that contains the function call
* @return pointer to the result XObject
*/
virtual XObjectPtr
execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectArgVectorType& args,
const Locator* locator) const
{
if (args.size() != 1)
{
XPathExecutionContext::GetAndReleaseCachedString theGuard(executionContext);
generalError(executionContext, context, locator);
}
assert(args[0].null() == false);
#if defined(XALAN_STRICT_ANSI_HEADERS)
using std::sqrt;
#endif
return executionContext.getXObjectFactory().createNumber(sqrt(args[0]->num(executionContext)));
}
using Function::execute;
/**
* Create a copy of the function object.
*
* @return pointer to the new object
*/
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
virtual Function*
#else
virtual FunctionSquareRoot*
#endif
clone(MemoryManager& theManager) const
{
return XalanCopyConstruct(theManager, *this);
}
protected:
/**
* Get the error message to report when
* the function is called with the wrong
* number of arguments.
*
* @return function error message
*/
const XalanDOMString&
getError(XalanDOMString& theResult) const
{
theResult.assign("The square-root() function accepts one argument!");
return theResult;
}
private:
// Not implemented...
FunctionSquareRoot&
operator=(const FunctionSquareRoot&);
bool
operator==(const FunctionSquareRoot&) const;
};
// This class defines a function that will return the cube
// of its argument.
class FunctionCube : public Function
{
public:
/**
* Execute an XPath function object. The function must return a valid
* object. Extension functions should override this version of execute(),
* rather than one of the other calls designed for a specific number of
* arguments.
*
* @param executionContext executing context
* @param context current context node
* @param args vector of pointers to XObject arguments
* @param locator Locator for the XPath expression that contains the function call
* @return pointer to the result XObject
*/
virtual XObjectPtr
execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectArgVectorType& args,
const Locator* locator) const
{
if (args.size() != 1)
{
XPathExecutionContext::GetAndReleaseCachedString theGuard(executionContext);
generalError(executionContext, context, locator);
}
assert(args[0].null() == false);
#if defined(XALAN_STRICT_ANSI_HEADERS)
using std::pow;
#endif
return executionContext.getXObjectFactory().createNumber(pow(args[0]->num(executionContext), 3));
}
using Function::execute;
/**
* Create a copy of the function object.
*
* @return pointer to the new object
*/
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
virtual Function*
#else
virtual FunctionCube*
#endif
clone(MemoryManager& theManager) const
{
return XalanCopyConstruct(theManager, *this);
}
protected:
/**
* Get the error message to report when
* the function is called with the wrong
* number of arguments.
*
* @return function error message
*/
const XalanDOMString&
getError(XalanDOMString& theResult) const
{
theResult.assign("The cube() function accepts one argument!");
return theResult;
}
private:
// Not implemented...
FunctionCube&
operator=(const FunctionCube&);
bool
operator==(const FunctionCube&) const;
};
// This class defines a function that runs the C function
// asctime() using the current system time.
class FunctionAsctime : public Function
{
public:
/**
* Execute an XPath function object. The function must return a valid
* object. Extension functions should override this version of execute(),
* rather than one of the other calls designed for a specific number of
* arguments.
*
* @param executionContext executing context
* @param context current context node
* @param args vector of pointers to XObject arguments
* @param locator Locator for the XPath expression that contains the function call
* @return pointer to the result XObject
*/
virtual XObjectPtr
execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectArgVectorType& args,
const Locator* locator) const
{
if (args.empty() == false)
{
generalError(executionContext, context, locator);
}
#if defined(XALAN_STRICT_ANSI_HEADERS)
using std::time;
using std::time_t;
using std::localtime;
using std::asctime;
using std::strlen;
#endif
time_t theTime;
time(&theTime);
char* const theTimeString = asctime(localtime(&theTime));
assert(theTimeString != 0);
// The resulting string has a newline character at the end,
// so get rid of it.
theTimeString[strlen(theTimeString) - 1] = '\0';
return executionContext.getXObjectFactory().createString(XalanDOMString(theTimeString));
}
using Function::execute;
/**
* Create a copy of the function object.
*
* @return pointer to the new object
*/
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
virtual Function*
#else
virtual FunctionAsctime*
#endif
clone(MemoryManager& theManager) const
{
return XalanCopyConstruct(theManager, *this);
}
protected:
/**
* Get the error message to report when
* the function is called with the wrong
* number of arguments.
*
* @return function error message
*/
const XalanDOMString&
getError(XalanDOMString& theResult) const
{
theResult.assign("The asctime() function accepts one argument!");
return theResult;
}
private:
// Not implemented...
FunctionAsctime&
operator=(const FunctionAsctime&);
bool
operator==(const FunctionAsctime&) const;
};
int
main(
int argc,
char* /* argv */[])
{
XALAN_USING_STD(cerr)
XALAN_USING_STD(endl)
int theResult = 0;
if (argc != 1)
{
cerr << "Usage: ExternalFunction"
<< endl
<< endl;
}
else
{
XALAN_USING_XERCES(XMLPlatformUtils)
XALAN_USING_XERCES(XMLException)
XALAN_USING_XALAN(XalanTransformer)
// Call the static initializer for Xerces.
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch)
{
cerr << "Error during Xerces initialization. Error code was "
<< toCatch.getCode()
<< "."
<< endl;
theResult = -1;
}
if (theResult == 0)
{
// Initialize Xalan.
XalanTransformer::initialize();
{
// Create a XalanTransformer.
XalanTransformer theXalanTransformer;
// The namespace for our functions...
const XalanDOMString theNamespace("http://ExternalFunction.xalan-c++.xml.apache.org");
// Install the functions in the local space. They will only
// be installed in this instance, so no other instances
// will know about them...
theXalanTransformer.installExternalFunction(
theNamespace,
XalanDOMString("asctime"),
FunctionAsctime());
theXalanTransformer.installExternalFunction(
theNamespace,
XalanDOMString("square-root"),
FunctionSquareRoot());
theXalanTransformer.installExternalFunction(
theNamespace,
XalanDOMString("cube"),
FunctionCube());
// Do the transform.
theResult = theXalanTransformer.transform("foo.xml", "foo.xsl", "foo.out");
if(theResult != 0)
{
cerr << "ExternalFunction Error: \n" << theXalanTransformer.getLastError()
<< endl
<< endl;
}
}
// Terminate Xalan...
XalanTransformer::terminate();
}
// Terminate Xerces...
XMLPlatformUtils::Terminate();
// Clean up the ICU, if it's integrated...
XalanTransformer::ICUCleanUp();
}
return theResult;
}
| 27.021429 | 105 | 0.61186 | kidaa |
cd721d3b8d1bf423a2e2d42632a35078e291a2cc | 28,059 | cpp | C++ | packages/arb-avm-cpp/tests/checkpoint.cpp | mrsmkl/arbitrum | 7941a8c4870f98ed7999357049a5eec4a75d8c78 | [
"Apache-2.0"
] | null | null | null | packages/arb-avm-cpp/tests/checkpoint.cpp | mrsmkl/arbitrum | 7941a8c4870f98ed7999357049a5eec4a75d8c78 | [
"Apache-2.0"
] | null | null | null | packages/arb-avm-cpp/tests/checkpoint.cpp | mrsmkl/arbitrum | 7941a8c4870f98ed7999357049a5eec4a75d8c78 | [
"Apache-2.0"
] | 1 | 2020-09-20T19:25:23.000Z | 2020-09-20T19:25:23.000Z | /*
* Copyright 2019, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.hpp"
#include "helper.hpp"
#include <avm/machinestate/machinestate.hpp>
#include <avm_values/vmValueParser.hpp>
#include <data_storage/checkpoint/checkpointstorage.hpp>
#include <data_storage/checkpoint/machinestatedeleter.hpp>
#include <data_storage/checkpoint/machinestatefetcher.hpp>
#include <data_storage/checkpoint/machinestatesaver.hpp>
#include <catch2/catch.hpp>
#include <boost/filesystem.hpp>
void saveValue(MachineStateSaver& saver,
const value& val,
int expected_ref_count,
bool expected_status) {
auto results = saver.saveValue(val);
saver.commitTransaction();
REQUIRE(results.status.ok() == expected_status);
REQUIRE(results.reference_count == expected_ref_count);
}
void getValue(MachineStateFetcher& fetcher,
std::vector<unsigned char>& hash_key,
int expected_ref_count,
uint256_t& expected_hash,
ValueTypes expected_value_type,
bool expected_status) {
auto results = fetcher.getValue(hash_key);
auto serialized_val = checkpoint::utils::serializeValue(results.data);
auto type = (ValueTypes)serialized_val[0];
REQUIRE(results.status.ok() == expected_status);
REQUIRE(results.reference_count == expected_ref_count);
REQUIRE(type == expected_value_type);
REQUIRE(hash(results.data) == expected_hash);
}
void saveTuple(MachineStateSaver& saver,
const Tuple& tup,
int expected_ref_count,
bool expected_status) {
auto results = saver.saveTuple(tup);
saver.commitTransaction();
REQUIRE(results.status.ok() == expected_status);
REQUIRE(results.reference_count == expected_ref_count);
}
void getTuple(MachineStateFetcher& fetcher,
std::vector<unsigned char>& hash_key,
int expected_ref_count,
uint256_t& expected_hash,
int expected_tuple_size,
bool expected_status) {
auto results = fetcher.getTuple(hash_key);
REQUIRE(results.reference_count == expected_ref_count);
REQUIRE(results.data.calculateHash() == expected_hash);
REQUIRE(results.data.tuple_size() == expected_tuple_size);
REQUIRE(results.status.ok() == expected_status);
}
void getTupleValues(MachineStateFetcher& fetcher,
std::vector<unsigned char>& hash_key,
std::vector<uint256_t> value_hashes) {
auto results = fetcher.getTuple(hash_key);
REQUIRE(results.data.tuple_size() == value_hashes.size());
for (size_t i = 0; i < value_hashes.size(); i++) {
REQUIRE(hash(results.data.get_element(i)) == value_hashes[i]);
}
}
TEST_CASE("Save value") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
SECTION("save 1 num tuple") {
TuplePool pool;
uint256_t num = 1;
auto tuple = Tuple(num, &pool);
saveValue(saver, tuple, 1, true);
}
SECTION("save num") {
uint256_t num = 1;
saveValue(saver, num, 1, true);
}
SECTION("save codepoint") {
auto code_point = CodePoint(1, Operation(), 0);
saveValue(saver, code_point, 1, true);
}
}
TEST_CASE("Save tuple") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
TuplePool pool;
SECTION("save 1 num tuple") {
uint256_t num = 1;
auto tuple = Tuple(num, &pool);
saveTuple(saver, tuple, 1, true);
}
SECTION("save 2, 1 num tuples") {
uint256_t num = 1;
auto tuple = Tuple(num, &pool);
saveTuple(saver, tuple, 1, true);
saveTuple(saver, tuple, 2, true);
}
SECTION("saved tuple in tuple") {
uint256_t num = 1;
auto inner_tuple = Tuple(num, &pool);
auto tuple = Tuple(inner_tuple, &pool);
saveTuple(saver, tuple, 1, true);
saveTuple(saver, tuple, 2, true);
}
}
TEST_CASE("Save and get value") {
SECTION("save empty tuple") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto tuple = Tuple();
auto hash_key = GetHashKey(tuple);
auto tup_hash = tuple.calculateHash();
saveValue(saver, tuple, 1, true);
getValue(fetcher, hash_key, 1, tup_hash, TUPLE, true);
}
SECTION("save tuple") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
uint256_t num = 1;
TuplePool pool;
auto tuple = Tuple(num, &pool);
auto hash_key = GetHashKey(tuple);
auto tup_hash = tuple.calculateHash();
saveValue(saver, tuple, 1, true);
getValue(fetcher, hash_key, 1, tup_hash, TUPLE, true);
}
SECTION("save num") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
uint256_t num = 1;
auto hash_key = GetHashKey(num);
auto num_hash = hash(num);
saveValue(saver, num, 1, true);
getValue(fetcher, hash_key, 1, num_hash, NUM, true);
}
SECTION("save codepoint") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto hash_key = GetHashKey(code_point);
auto cp_hash = hash(code_point);
saveValue(saver, code_point, 1, true);
getValue(fetcher, hash_key, 1, cp_hash, CODEPT, true);
}
SECTION("save err codepoint") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
auto code_point = getErrCodePoint();
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto hash_key = GetHashKey(code_point);
auto cp_hash = hash(code_point);
saveValue(saver, code_point, 1, true);
getValue(fetcher, hash_key, 1, cp_hash, CODEPT, true);
}
}
TEST_CASE("Save and get tuple values") {
SECTION("save num tuple") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
uint256_t num = 1;
TuplePool pool;
auto tuple = Tuple(num, &pool);
saveTuple(saver, tuple, 1, true);
std::vector<uint256_t> hashes{hash(num)};
auto hash_key = GetHashKey(tuple);
getTupleValues(fetcher, hash_key, hashes);
}
SECTION("save codepoint tuple") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[1];
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
TuplePool pool;
auto tuple = Tuple(code_point, &pool);
saveTuple(saver, tuple, 1, true);
std::vector<uint256_t> hashes{hash(code_point)};
auto hash_key = GetHashKey(tuple);
getTupleValues(fetcher, hash_key, hashes);
}
SECTION("save codepoint tuple") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
TuplePool pool;
auto tuple = Tuple(code_point, &pool);
saveValue(saver, tuple, 1, true);
std::vector<uint256_t> hashes{hash(code_point)};
auto hash_key = GetHashKey(tuple);
getTupleValues(fetcher, hash_key, hashes);
}
SECTION("save nested tuple") {
DBDeleter deleter;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto inner_tuple = Tuple();
TuplePool pool;
auto tuple = Tuple(inner_tuple, &pool);
saveTuple(saver, tuple, 1, true);
std::vector<uint256_t> hashes{hash(inner_tuple)};
auto hash_key = GetHashKey(tuple);
getTupleValues(fetcher, hash_key, hashes);
}
SECTION("save multiple valued tuple") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto inner_tuple = Tuple();
uint256_t num = 1;
auto tuple = Tuple(inner_tuple, num, code_point, &pool);
saveTuple(saver, tuple, 1, true);
std::vector<uint256_t> hashes{hash(inner_tuple), hash(num),
hash(code_point)};
auto hash_key = GetHashKey(tuple);
getTupleValues(fetcher, hash_key, hashes);
}
SECTION("save multiple valued tuple, saveValue()") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[2];
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto inner_tuple = Tuple();
uint256_t num = 1;
auto tuple = Tuple(inner_tuple, num, code_point, &pool);
saveValue(saver, tuple, 1, true);
std::vector<uint256_t> hashes{hash(inner_tuple), hash(num),
hash(code_point)};
auto hash_key = GetHashKey(tuple);
getTupleValues(fetcher, hash_key, hashes);
}
}
TEST_CASE("Save And Get Tuple") {
SECTION("save 1 num tuple") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
uint256_t num = 1;
auto tuple = Tuple(num, &pool);
auto tup_hash = tuple.calculateHash();
auto hash_key = GetHashKey(tuple);
saveTuple(saver, tuple, 1, true);
getTuple(fetcher, hash_key, 1, tup_hash, 1, true);
}
SECTION("save codepoint in tuple") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
auto code_point = storage.getInitialVmValues().code[0];
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto tuple = Tuple(code_point, &pool);
auto tup_hash = tuple.calculateHash();
auto hash_key = GetHashKey(tuple);
saveTuple(saver, tuple, 1, true);
getTuple(fetcher, hash_key, 1, tup_hash, 1, true);
}
SECTION("save 1 num tuple twice") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
auto saver2 = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
uint256_t num = 1;
auto tuple = Tuple(num, &pool);
auto tup_hash = tuple.calculateHash();
auto hash_key = GetHashKey(tuple);
saveTuple(saver, tuple, 1, true);
saveTuple(saver2, tuple, 2, true);
getTuple(fetcher, hash_key, 2, tup_hash, 1, true);
}
SECTION("save 2 num tuple") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
std::vector<CodePoint> code;
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
uint256_t num = 1;
uint256_t num2 = 2;
auto tuple = Tuple(num, num2, &pool);
auto tup_hash = tuple.calculateHash();
auto hash_key = GetHashKey(tuple);
saveTuple(saver, tuple, 1, true);
getTuple(fetcher, hash_key, 1, tup_hash, 2, true);
}
SECTION("save tuple in tuple") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
uint256_t num = 1;
auto inner_tuple = Tuple(num, &pool);
auto tuple = Tuple(inner_tuple, &pool);
saveTuple(saver, tuple, 1, true);
auto inner_hash_key = GetHashKey(inner_tuple);
auto inner_tup_hash = inner_tuple.calculateHash();
auto hash_key = GetHashKey(tuple);
auto tup_hash = tuple.calculateHash();
getTuple(fetcher, hash_key, 1, tup_hash, 1, true);
getTuple(fetcher, inner_hash_key, 1, inner_tup_hash, 1, true);
}
SECTION("save 2 tuples in tuple") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
uint256_t num = 1;
auto inner_tuple = Tuple(num, &pool);
uint256_t num2 = 2;
auto inner_tuple2 = Tuple(num2, &pool);
auto tuple = Tuple(inner_tuple, inner_tuple2, &pool);
saveTuple(saver, tuple, 1, true);
auto inner_hash_key = GetHashKey(inner_tuple);
auto inner_tup_hash = inner_tuple.calculateHash();
auto inner_hash_key2 = GetHashKey(inner_tuple2);
auto inner_tup_hash2 = inner_tuple2.calculateHash();
auto hash_key = GetHashKey(tuple);
auto tup_hash = tuple.calculateHash();
getTuple(fetcher, hash_key, 1, tup_hash, 2, true);
getTuple(fetcher, inner_hash_key, 1, inner_tup_hash, 1, true);
getTuple(fetcher, inner_hash_key2, 1, inner_tup_hash2, 1, true);
}
SECTION("save saved tuple in tuple") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
auto saver = MachineStateSaver(storage.makeTransaction());
auto saver2 = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
uint256_t num = 1;
auto inner_tuple = Tuple(num, &pool);
auto tuple = Tuple(inner_tuple, &pool);
auto inner_hash_key = GetHashKey(inner_tuple);
auto inner_tup_hash = inner_tuple.calculateHash();
auto hash_key = GetHashKey(tuple);
auto tup_hash = tuple.calculateHash();
saveTuple(saver, inner_tuple, 1, true);
getTuple(fetcher, inner_hash_key, 1, inner_tup_hash, 1, true);
saveTuple(saver2, tuple, 1, true);
getTuple(fetcher, hash_key, 1, tup_hash, 1, true);
getTuple(fetcher, inner_hash_key, 2, inner_tup_hash, 1, true);
}
}
void saveState(MachineStateSaver& saver,
MachineStateKeys storage_data,
std::vector<unsigned char> checkpoint_name) {
auto results = saver.saveMachineState(storage_data, checkpoint_name);
auto status = saver.commitTransaction();
REQUIRE(results.reference_count == 1);
REQUIRE(results.status.ok());
}
void getSavedState(MachineStateFetcher& fetcher,
std::vector<unsigned char> checkpoint_name,
MachineStateKeys expected_data,
int expected_ref_count,
std::vector<std::vector<unsigned char>> keys) {
auto results = fetcher.getMachineState(checkpoint_name);
REQUIRE(results.status.ok());
REQUIRE(results.reference_count == expected_ref_count);
auto data = results.data;
REQUIRE(data.status_char == expected_data.status_char);
REQUIRE(data.pc_key == expected_data.pc_key);
REQUIRE(data.datastack_key == expected_data.datastack_key);
REQUIRE(data.auxstack_key == expected_data.auxstack_key);
REQUIRE(data.register_val_key == expected_data.register_val_key);
for (auto& key : keys) {
auto res = fetcher.getValue(key);
REQUIRE(res.status.ok());
}
}
void deleteCheckpoint(CheckpointStorage& storage,
MachineStateFetcher& fetcher,
std::vector<unsigned char> checkpoint_name,
std::vector<std::vector<unsigned char>> deleted_values) {
auto res = deleteCheckpoint(storage, checkpoint_name);
auto results = fetcher.getMachineState(checkpoint_name);
REQUIRE(results.status.ok() == false);
for (auto& hash_key : deleted_values) {
auto res = fetcher.getValue(hash_key);
REQUIRE(res.status.ok() == false);
}
}
void deleteCheckpointSavedTwice(
CheckpointStorage& storage,
MachineStateFetcher& fetcher,
std::vector<unsigned char> checkpoint_name,
std::vector<std::vector<unsigned char>> deleted_values) {
auto res = deleteCheckpoint(storage, checkpoint_name);
auto res2 = deleteCheckpoint(storage, checkpoint_name);
auto results = fetcher.getMachineState(checkpoint_name);
REQUIRE(results.status.ok() == false);
for (auto& hash_key : deleted_values) {
auto res = fetcher.getValue(hash_key);
REQUIRE(res.status.ok() == false);
}
}
void deleteCheckpointSavedTwiceReordered(
CheckpointStorage& storage,
MachineStateFetcher& fetcher,
std::vector<unsigned char> checkpoint_name,
std::vector<std::vector<unsigned char>> deleted_values) {
auto resultsx = fetcher.getMachineState(checkpoint_name);
for (auto& hash_key : deleted_values) {
auto res = fetcher.getValue(hash_key);
REQUIRE(res.status.ok());
}
auto res = deleteCheckpoint(storage, checkpoint_name);
auto results = fetcher.getMachineState(checkpoint_name);
REQUIRE(results.status.ok() == true);
for (auto& hash_key : deleted_values) {
auto res = fetcher.getValue(hash_key);
REQUIRE(res.status.ok());
}
auto res2 = deleteCheckpoint(storage, checkpoint_name);
auto results2 = fetcher.getMachineState(checkpoint_name);
REQUIRE(results2.status.ok() == false);
for (auto& hash_key : deleted_values) {
auto res = fetcher.getValue(hash_key);
REQUIRE(res.status.ok() == false);
}
}
MachineStateKeys makeStorageData(MachineStateSaver& stateSaver,
value registerVal,
Datastack stack,
Datastack auxstack,
Status state,
CodePoint pc,
CodePoint err_pc,
BlockReason blockReason) {
TuplePool pool;
auto datastack_results = stack.checkpointState(stateSaver, &pool);
auto auxstack_results = auxstack.checkpointState(stateSaver, &pool);
auto register_val_results = stateSaver.saveValue(registerVal);
auto pc_results = stateSaver.saveValue(pc);
auto err_pc_results = stateSaver.saveValue(err_pc);
auto status_str = (unsigned char)state;
return MachineStateKeys{
register_val_results.storage_key, datastack_results.storage_key,
auxstack_results.storage_key, pc_results.storage_key,
err_pc_results.storage_key, status_str};
}
MachineStateKeys getStateValues(MachineStateSaver& saver) {
TuplePool pool;
uint256_t register_val = 100;
auto static_val = Tuple(register_val, Tuple(), &pool);
auto code_point = CodePoint(1, Operation(), 0);
auto tup1 = Tuple(register_val, &pool);
auto tup2 = Tuple(code_point, tup1, &pool);
Datastack data_stack;
data_stack.push(register_val);
Datastack aux_stack;
aux_stack.push(register_val);
aux_stack.push(code_point);
CodePoint pc_codepoint(0, Operation(), 0);
CodePoint err_pc_codepoint(0, Operation(), 0);
Status state = Status::Extensive;
auto inbox_blocked = InboxBlocked(0);
auto saved_data =
makeStorageData(saver, register_val, data_stack, aux_stack, state,
pc_codepoint, err_pc_codepoint, inbox_blocked);
return saved_data;
}
MachineStateKeys getDefaultValues(MachineStateSaver& saver) {
TuplePool pool;
auto register_val = Tuple();
auto data_stack = Tuple();
auto aux_stack = Tuple();
Status state = Status::Extensive;
CodePoint code_point(0, Operation(), 0);
auto data = makeStorageData(saver, Tuple(), Datastack(), Datastack(), state,
code_point, code_point, NotBlocked());
return data;
}
std::vector<std::vector<unsigned char>> getHashKeys(MachineStateKeys data) {
std::vector<std::vector<unsigned char>> hash_keys;
hash_keys.push_back(data.auxstack_key);
hash_keys.push_back(data.datastack_key);
hash_keys.push_back(data.pc_key);
hash_keys.push_back(data.err_pc_key);
hash_keys.push_back(data.register_val_key);
return hash_keys;
}
TEST_CASE("Save Machinestatedata") {
SECTION("default") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
auto saver = MachineStateSaver(storage.makeTransaction());
auto data_values = getDefaultValues(saver);
std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'};
saveState(saver, data_values, checkpoint_key);
}
SECTION("with values") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
CodePoint code_point2 = storage.getInitialVmValues().code[1];
auto saver = MachineStateSaver(storage.makeTransaction());
auto state_data = getStateValues(saver);
std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'};
saveState(saver, state_data, checkpoint_key);
}
}
TEST_CASE("Get Machinestate data") {
SECTION("default") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto data_values = getDefaultValues(saver);
auto keys = getHashKeys(data_values);
std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'};
saver.saveMachineState(data_values, checkpoint_key);
saver.commitTransaction();
getSavedState(fetcher, checkpoint_key, data_values, 1, keys);
}
SECTION("with values") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
CodePoint code_point2 = storage.getInitialVmValues().code[1];
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto state_data = getStateValues(saver);
auto keys = getHashKeys(state_data);
std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'};
saveState(saver, state_data, checkpoint_key);
getSavedState(fetcher, checkpoint_key, state_data, 1, keys);
}
}
TEST_CASE("Delete checkpoint") {
SECTION("default") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto data_values = getDefaultValues(saver);
std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'};
saver.saveMachineState(data_values, checkpoint_key);
saver.commitTransaction();
auto hash_keys = getHashKeys(data_values);
deleteCheckpoint(storage, fetcher, checkpoint_key, hash_keys);
}
SECTION("with actual state values") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
CodePoint code_point2 = storage.getInitialVmValues().code[2];
auto saver = MachineStateSaver(storage.makeTransaction());
auto fetcher = MachineStateFetcher(storage);
auto data_values = getStateValues(saver);
std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'};
saver.saveMachineState(data_values, checkpoint_key);
saver.commitTransaction();
auto hash_keys = getHashKeys(data_values);
deleteCheckpoint(storage, fetcher, checkpoint_key, hash_keys);
}
SECTION("delete checkpoint saved twice") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
CodePoint code_point2 = storage.getInitialVmValues().code[1];
auto fetcher = MachineStateFetcher(storage);
auto saver = MachineStateSaver(storage.makeTransaction());
auto data_values = getStateValues(saver);
std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'};
saver.saveMachineState(data_values, checkpoint_key);
saver.saveMachineState(data_values, checkpoint_key);
saver.commitTransaction();
auto hash_keys = getHashKeys(data_values);
deleteCheckpointSavedTwice(storage, fetcher, checkpoint_key, hash_keys);
}
SECTION("delete checkpoint saved twice, reordered") {
DBDeleter deleter;
TuplePool pool;
CheckpointStorage storage(dbpath, test_contract_path);
CodePoint code_point = storage.getInitialVmValues().code[0];
CodePoint code_point2 = storage.getInitialVmValues().code[1];
auto fetcher = MachineStateFetcher(storage);
auto saver = MachineStateSaver(storage.makeTransaction());
auto saver2 = MachineStateSaver(storage.makeTransaction());
auto data_values = getStateValues(saver);
std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'};
saver.saveMachineState(data_values, checkpoint_key);
saver.commitTransaction();
saver2.saveMachineState(data_values, checkpoint_key);
saver2.commitTransaction();
auto hash_keys = getHashKeys(data_values);
deleteCheckpointSavedTwiceReordered(storage, fetcher, checkpoint_key,
hash_keys);
}
}
| 35.42803 | 80 | 0.656545 | mrsmkl |
cd725f4ea754645fb58c747c8a825c92039711a7 | 27,365 | cpp | C++ | Source/Urho3D/IK/IKSolver.cpp | jayrulez/Urho3D | ff211d94240c1e848304aaaa9ccfa8d4f6315457 | [
"MIT"
] | null | null | null | Source/Urho3D/IK/IKSolver.cpp | jayrulez/Urho3D | ff211d94240c1e848304aaaa9ccfa8d4f6315457 | [
"MIT"
] | null | null | null | Source/Urho3D/IK/IKSolver.cpp | jayrulez/Urho3D | ff211d94240c1e848304aaaa9ccfa8d4f6315457 | [
"MIT"
] | null | null | null | // Copyright (c) 2008-2022 the Urho3D project
// License: MIT
#include "../IK/IKSolver.h"
#include "../IK/IKConstraint.h"
#include "../IK/IKEvents.h"
#include "../IK/IKEffector.h"
#include "../IK/IKConverters.h"
#include "../Core/Context.h"
#include "../Core/Profiler.h"
#include "../Graphics/Animation.h"
#include "../Graphics/AnimationState.h"
#include "../Graphics/DebugRenderer.h"
#include "../IO/Log.h"
#include "../Scene/SceneEvents.h"
#include <ik/effector.h>
#include <ik/node.h>
#include <ik/solver.h>
#include <ik/util.h>
namespace Urho3D
{
extern const char* IK_CATEGORY;
// ----------------------------------------------------------------------------
IKSolver::IKSolver(Context* context) :
Component(context),
solver_(nullptr),
algorithm_(FABRIK),
features_(AUTO_SOLVE | JOINT_ROTATIONS | UPDATE_ACTIVE_POSE),
chainTreesNeedUpdating_(false),
treeNeedsRebuild(true),
solverTreeValid_(false)
{
context_->RequireIK();
SetAlgorithm(FABRIK);
SubscribeToEvent(E_COMPONENTADDED, URHO3D_HANDLER(IKSolver, HandleComponentAdded));
SubscribeToEvent(E_COMPONENTREMOVED, URHO3D_HANDLER(IKSolver, HandleComponentRemoved));
SubscribeToEvent(E_NODEADDED, URHO3D_HANDLER(IKSolver, HandleNodeAdded));
SubscribeToEvent(E_NODEREMOVED, URHO3D_HANDLER(IKSolver, HandleNodeRemoved));
}
// ----------------------------------------------------------------------------
IKSolver::~IKSolver()
{
// Destroying the solver tree will destroy the effector objects, so remove
// any references any of the IKEffector objects could be holding
for (Vector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it)
(*it)->SetIKEffectorNode(nullptr);
ik_solver_destroy(solver_);
context_->ReleaseIK();
}
// ----------------------------------------------------------------------------
void IKSolver::RegisterObject(Context* context)
{
context->RegisterFactory<IKSolver>(IK_CATEGORY);
static const char* algorithmNames[] = {
"1 Bone",
"2 Bone",
"FABRIK",
/* not implemented,
"MSD (Mass/Spring/Damper)",
"Jacobian Inverse",
"Jacobian Transpose",*/
nullptr
};
URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Algorithm", GetAlgorithm, SetAlgorithm, Algorithm, algorithmNames, FABRIK, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Max Iterations", GetMaximumIterations, SetMaximumIterations, unsigned, 20, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Convergence Tolerance", GetTolerance, SetTolerance, float, 0.001, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Joint Rotations", GetJOINT_ROTATIONS, SetJOINT_ROTATIONS, bool, true, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Target Rotations", GetTARGET_ROTATIONS, SetTARGET_ROTATIONS, bool, false, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Update Original Pose", GetUPDATE_ORIGINAL_POSE, SetUPDATE_ORIGINAL_POSE, bool, false, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Update Active Pose", GetUPDATE_ACTIVE_POSE, SetUPDATE_ACTIVE_POSE, bool, true, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Use Original Pose", GetUSE_ORIGINAL_POSE, SetUSE_ORIGINAL_POSE, bool, false, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Enable Constraints", GetCONSTRAINTS, SetCONSTRAINTS, bool, false, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Auto Solve", GetAUTO_SOLVE, SetAUTO_SOLVE, bool, true, AM_DEFAULT);
}
// ----------------------------------------------------------------------------
IKSolver::Algorithm IKSolver::GetAlgorithm() const
{
return algorithm_;
}
// ----------------------------------------------------------------------------
void IKSolver::SetAlgorithm(IKSolver::Algorithm algorithm)
{
algorithm_ = algorithm;
/* We need to rebuild the tree so make sure that the scene is in the
* initial pose when this occurs.*/
if (node_ != nullptr)
ApplyOriginalPoseToScene();
// Initial flags for when there is no solver to destroy
uint8_t initialFlags = 0;
// Destroys the tree and the solver
if (solver_ != nullptr)
{
initialFlags = solver_->flags;
DestroyTree();
ik_solver_destroy(solver_);
}
switch (algorithm_)
{
case ONE_BONE : solver_ = ik_solver_create(SOLVER_ONE_BONE); break;
case TWO_BONE : solver_ = ik_solver_create(SOLVER_TWO_BONE); break;
case FABRIK : solver_ = ik_solver_create(SOLVER_FABRIK); break;
/*case MSD : solver_ = ik_solver_create(SOLVER_MSD); break;*/
}
solver_->flags = initialFlags;
if (node_ != nullptr)
RebuildTree();
}
// ----------------------------------------------------------------------------
bool IKSolver::GetFeature(Feature feature) const
{
return (features_ & feature) != 0;
}
// ----------------------------------------------------------------------------
void IKSolver::SetFeature(Feature feature, bool enable)
{
switch (feature)
{
case CONSTRAINTS:
{
solver_->flags &= ~SOLVER_ENABLE_CONSTRAINTS;
if (enable)
solver_->flags |= SOLVER_ENABLE_CONSTRAINTS;
} break;
case TARGET_ROTATIONS:
{
solver_->flags &= ~SOLVER_CALCULATE_TARGET_ROTATIONS;
if (enable)
solver_->flags |= SOLVER_CALCULATE_TARGET_ROTATIONS;
} break;
case AUTO_SOLVE:
{
if (((features_ & AUTO_SOLVE) != 0) == enable)
break;
if (enable)
SubscribeToEvent(GetScene(), E_SCENEDRAWABLEUPDATEFINISHED, URHO3D_HANDLER(IKSolver, HandleSceneDrawableUpdateFinished));
else
UnsubscribeFromEvent(GetScene(), E_SCENEDRAWABLEUPDATEFINISHED);
} break;
default: break;
}
features_ &= ~feature;
if (enable)
features_ |= feature;
}
// ----------------------------------------------------------------------------
unsigned IKSolver::GetMaximumIterations() const
{
return solver_->max_iterations;
}
// ----------------------------------------------------------------------------
void IKSolver::SetMaximumIterations(unsigned iterations)
{
solver_->max_iterations = iterations;
}
// ----------------------------------------------------------------------------
float IKSolver::GetTolerance() const
{
return solver_->tolerance;
}
// ----------------------------------------------------------------------------
void IKSolver::SetTolerance(float tolerance)
{
if (tolerance < M_EPSILON)
tolerance = M_EPSILON;
solver_->tolerance = tolerance;
}
// ----------------------------------------------------------------------------
ik_node_t* IKSolver::CreateIKNodeFromUrhoNode(const Node* node)
{
ik_node_t* ikNode = ik_node_create(node->GetID());
// Set initial position/rotation and pass in Node* as user data for later
ikNode->original_position = Vec3Urho2IK(node->GetWorldPosition());
ikNode->original_rotation = QuatUrho2IK(node->GetWorldRotation());
ikNode->user_data = (void*)node;
/*
* If Urho's node has an effector, also create and attach one to the
* library's node. At this point, the IKEffector component shouldn't be
* holding a reference to any internal effector. Check this for debugging
* purposes and log if it does.
*/
auto* effector = node->GetComponent<IKEffector>();
if (effector != nullptr)
{
#ifdef DEBUG
if (effector->ikEffectorNode_ != nullptr)
URHO3D_LOGWARNINGF("[ik] IKEffector (attached to node \"%s\") has a reference to a possibly invalid internal effector. Should be NULL.", effector->GetNode()->GetName().CString());
#endif
ik_effector_t* ikEffector = ik_effector_create();
ik_node_attach_effector(ikNode, ikEffector); // ownership of effector
effector->SetIKSolver(this);
effector->SetIKEffectorNode(ikNode);
}
// Exact same deal with the constraint
auto* constraint = node->GetComponent<IKConstraint>();
if (constraint != nullptr)
{
#ifdef DEBUG
if (constraint->ikConstraintNode_ != nullptr)
URHO3D_LOGWARNINGF("[ik] IKConstraint (attached to node \"%s\") has a reference to a possibly invalid internal constraint. Should be NULL.", constraint->GetNode()->GetName().CString());
#endif
constraint->SetIKConstraintNode(ikNode);
}
return ikNode;
}
// ----------------------------------------------------------------------------
void IKSolver::DestroyTree()
{
ik_solver_destroy_tree(solver_);
effectorList_.Clear();
constraintList_.Clear();
}
// ----------------------------------------------------------------------------
void IKSolver::RebuildTree()
{
assert (node_ != nullptr);
// Destroy current tree and set a new root node
DestroyTree();
ik_node_t* ikRoot = CreateIKNodeFromUrhoNode(node_);
ik_solver_set_tree(solver_, ikRoot);
/*
* Collect all effectors and constraints from children, and filter them to
* make sure they are in our subtree.
*/
node_->GetComponents<IKEffector>(effectorList_, true);
node_->GetComponents<IKConstraint>(constraintList_, true);
for (Vector<IKEffector*>::Iterator it = effectorList_.Begin(); it != effectorList_.End();)
{
if (ComponentIsInOurSubtree(*it))
{
BuildTreeToEffector((*it));
++it;
}
else
{
it = effectorList_.Erase(it);
}
}
for (Vector<IKConstraint*>::Iterator it = constraintList_.Begin(); it != constraintList_.End();)
{
if (ComponentIsInOurSubtree(*it))
++it;
else
it = constraintList_.Erase(it);
}
treeNeedsRebuild = false;
MarkChainsNeedUpdating();
}
// ----------------------------------------------------------------------------
bool IKSolver::BuildTreeToEffector(IKEffector* effector)
{
/*
* NOTE: This function makes the assumption that the node the effector is
* attached to is -- without a doubt -- in our subtree (by using
* ComponentIsInOurSubtree() first). If this is not the case, the program
* will abort.
*/
/*
* we need to build tree up to the node where this effector was added. Do
* this by following the chain of parent nodes until we hit a node that
* exists in the solver's subtree. Then iterate backwards again and add each
* missing node to the solver's tree.
*/
const Node* iterNode = effector->GetNode();
ik_node_t* ikNode;
Vector<const Node*> missingNodes;
while ((ikNode = ik_node_find_child(solver_->tree, iterNode->GetID())) == nullptr)
{
missingNodes.Push(iterNode);
iterNode = iterNode->GetParent();
// Assert the assumptions made (described in the beginning of this function)
assert(iterNode != nullptr);
assert (iterNode->HasComponent<IKSolver>() == false || iterNode == node_);
}
while (missingNodes.Size() > 0)
{
iterNode = missingNodes.Back();
missingNodes.Pop();
ik_node_t* ikChildNode = CreateIKNodeFromUrhoNode(iterNode);
ik_node_add_child(ikNode, ikChildNode);
ikNode = ikChildNode;
}
return true;
}
// ----------------------------------------------------------------------------
bool IKSolver::ComponentIsInOurSubtree(Component* component) const
{
const Node* iterNode = component->GetNode();
while (true)
{
// Note part of our subtree
if (iterNode == nullptr)
return false;
// Reached the root node, it's part of our subtree!
if (iterNode == node_)
return true;
// Path to us is being blocked by another solver
Component* otherSolver = iterNode->GetComponent<IKSolver>();
if (otherSolver != nullptr && otherSolver != component)
return false;
iterNode = iterNode->GetParent();
}
return true;
}
// ----------------------------------------------------------------------------
void IKSolver::RebuildChainTrees()
{
solverTreeValid_ = (ik_solver_rebuild_chain_trees(solver_) == 0);
ik_calculate_rotation_weight_decays(&solver_->chain_tree);
chainTreesNeedUpdating_ = false;
}
// ----------------------------------------------------------------------------
void IKSolver::RecalculateSegmentLengths()
{
ik_solver_recalculate_segment_lengths(solver_);
}
// ----------------------------------------------------------------------------
void IKSolver::CalculateJointRotations()
{
ik_solver_calculate_joint_rotations(solver_);
}
// ----------------------------------------------------------------------------
void IKSolver::Solve()
{
URHO3D_PROFILE(IKSolve);
if (treeNeedsRebuild)
RebuildTree();
if (chainTreesNeedUpdating_)
RebuildChainTrees();
if (IsSolverTreeValid() == false)
return;
if (features_ & UPDATE_ORIGINAL_POSE)
ApplySceneToOriginalPose();
if (features_ & UPDATE_ACTIVE_POSE)
ApplySceneToActivePose();
if (features_ & USE_ORIGINAL_POSE)
ApplyOriginalPoseToActivePose();
for (Vector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it)
{
(*it)->UpdateTargetNodePosition();
}
ik_solver_solve(solver_);
if (features_ & JOINT_ROTATIONS)
ik_solver_calculate_joint_rotations(solver_);
ApplyActivePoseToScene();
}
// ----------------------------------------------------------------------------
static void ApplyInitialPoseToSceneCallback(ik_node_t* ikNode)
{
auto* node = (Node*)ikNode->user_data;
node->SetWorldRotation(QuatIK2Urho(&ikNode->original_rotation));
node->SetWorldPosition(Vec3IK2Urho(&ikNode->original_position));
}
void IKSolver::ApplyOriginalPoseToScene()
{
ik_solver_iterate_tree(solver_, ApplyInitialPoseToSceneCallback);
}
// ----------------------------------------------------------------------------
static void ApplySceneToInitialPoseCallback(ik_node_t* ikNode)
{
auto* node = (Node*)ikNode->user_data;
ikNode->original_rotation = QuatUrho2IK(node->GetWorldRotation());
ikNode->original_position = Vec3Urho2IK(node->GetWorldPosition());
}
void IKSolver::ApplySceneToOriginalPose()
{
ik_solver_iterate_tree(solver_, ApplySceneToInitialPoseCallback);
}
// ----------------------------------------------------------------------------
static void ApplyActivePoseToSceneCallback(ik_node_t* ikNode)
{
auto* node = (Node*)ikNode->user_data;
node->SetWorldRotation(QuatIK2Urho(&ikNode->rotation));
node->SetWorldPosition(Vec3IK2Urho(&ikNode->position));
}
void IKSolver::ApplyActivePoseToScene()
{
ik_solver_iterate_tree(solver_, ApplyActivePoseToSceneCallback);
}
// ----------------------------------------------------------------------------
static void ApplySceneToActivePoseCallback(ik_node_t* ikNode)
{
auto* node = (Node*)ikNode->user_data;
ikNode->rotation = QuatUrho2IK(node->GetWorldRotation());
ikNode->position = Vec3Urho2IK(node->GetWorldPosition());
}
void IKSolver::ApplySceneToActivePose()
{
ik_solver_iterate_tree(solver_, ApplySceneToActivePoseCallback);
}
// ----------------------------------------------------------------------------
void IKSolver::ApplyOriginalPoseToActivePose()
{
ik_solver_reset_to_original_pose(solver_);
}
// ----------------------------------------------------------------------------
void IKSolver::MarkChainsNeedUpdating()
{
chainTreesNeedUpdating_ = true;
}
// ----------------------------------------------------------------------------
void IKSolver::MarkTreeNeedsRebuild()
{
treeNeedsRebuild = true;
}
// ----------------------------------------------------------------------------
bool IKSolver::IsSolverTreeValid() const
{
return solverTreeValid_;
}
// ----------------------------------------------------------------------------
/*
* This next section maintains the internal list of effector nodes. Whenever
* nodes are deleted or added to the scene, or whenever components are added
* or removed from nodes, we must check to see which of those nodes are/were
* IK effector nodes and update our internal list accordingly.
*
* Unfortunately, E_COMPONENTREMOVED and E_COMPONENTADDED do not fire when a
* parent node is removed/added containing child effector nodes, so we must
* also monitor E_NODEREMOVED AND E_NODEADDED.
*/
// ----------------------------------------------------------------------------
void IKSolver::OnSceneSet(Scene* scene)
{
if (features_ & AUTO_SOLVE)
SubscribeToEvent(scene, E_SCENEDRAWABLEUPDATEFINISHED, URHO3D_HANDLER(IKSolver, HandleSceneDrawableUpdateFinished));
}
// ----------------------------------------------------------------------------
void IKSolver::OnNodeSet(Node* node)
{
ApplyOriginalPoseToScene();
DestroyTree();
if (node != nullptr)
RebuildTree();
}
// ----------------------------------------------------------------------------
void IKSolver::HandleComponentAdded(StringHash eventType, VariantMap& eventData)
{
using namespace ComponentAdded;
(void)eventType;
auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
auto* component = static_cast<Component*>(eventData[P_COMPONENT].GetPtr());
/*
* When a solver gets added into the scene, any parent solver's tree will
* be invalidated. We need to find all parent solvers (by iterating up the
* tree) and mark them as such.
*/
if (component->GetType() == IKSolver::GetTypeStatic())
{
for (Node* iterNode = node; iterNode != nullptr; iterNode = iterNode->GetParent())
{
auto* parentSolver = iterNode->GetComponent<IKSolver>();
if (parentSolver != nullptr)
parentSolver->MarkTreeNeedsRebuild();
}
return; // No need to continue processing effectors or constraints
}
if (solver_->tree == nullptr)
return;
/*
* Update tree if component is an effector and is part of our subtree.
*/
if (component->GetType() == IKEffector::GetTypeStatic())
{
// Not interested in components that won't be part of our
if (ComponentIsInOurSubtree(component) == false)
return;
BuildTreeToEffector(static_cast<IKEffector*>(component));
effectorList_.Push(static_cast<IKEffector*>(component));
return;
}
if (component->GetType() == IKConstraint::GetTypeStatic())
{
if (ComponentIsInOurSubtree(component) == false)
return;
constraintList_.Push(static_cast<IKConstraint*>(component));
}
}
// ----------------------------------------------------------------------------
void IKSolver::HandleComponentRemoved(StringHash eventType, VariantMap& eventData)
{
using namespace ComponentRemoved;
if (solver_->tree == nullptr)
return;
auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
auto* component = static_cast<Component*>(eventData[P_COMPONENT].GetPtr());
/*
* When a solver gets added into the scene, any parent solver's tree will
* be invalidated. We need to find all parent solvers (by iterating up the
* tree) and mark them as such.
*/
if (component->GetType() == IKSolver::GetTypeStatic())
{
for (Node* iterNode = node; iterNode != nullptr; iterNode = iterNode->GetParent())
{
auto* parentSolver = iterNode->GetComponent<IKSolver>();
if (parentSolver != nullptr)
parentSolver->MarkTreeNeedsRebuild();
}
return; // No need to continue processing effectors or constraints
}
// If an effector was removed, the tree will have to be rebuilt.
if (component->GetType() == IKEffector::GetTypeStatic())
{
if (ComponentIsInOurSubtree(component) == false)
return;
ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID());
assert(ikNode != nullptr);
ik_node_destroy_effector(ikNode);
static_cast<IKEffector*>(component)->SetIKEffectorNode(nullptr);
effectorList_.RemoveSwap(static_cast<IKEffector*>(component));
ApplyOriginalPoseToScene();
MarkTreeNeedsRebuild();
return;
}
// Remove the ikNode* reference the IKConstraint was holding
if (component->GetType() == IKConstraint::GetTypeStatic())
{
if (ComponentIsInOurSubtree(component) == false)
return;
ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID());
assert(ikNode != nullptr);
static_cast<IKConstraint*>(component)->SetIKConstraintNode(nullptr);
constraintList_.RemoveSwap(static_cast<IKConstraint*>(component));
}
}
// ----------------------------------------------------------------------------
void IKSolver::HandleNodeAdded(StringHash eventType, VariantMap& eventData)
{
using namespace NodeAdded;
if (solver_->tree == nullptr)
return;
auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
Vector<IKEffector*> effectors;
node->GetComponents<IKEffector>(effectors, true);
for (Vector<IKEffector*>::ConstIterator it = effectors.Begin(); it != effectors.End(); ++it)
{
if (ComponentIsInOurSubtree(*it) == false)
continue;
BuildTreeToEffector(*it);
effectorList_.Push(*it);
}
Vector<IKConstraint*> constraints;
node->GetComponents<IKConstraint>(constraints, true);
for (Vector<IKConstraint*>::ConstIterator it = constraints.Begin(); it != constraints.End(); ++it)
{
if (ComponentIsInOurSubtree(*it) == false)
continue;
constraintList_.Push(*it);
}
}
// ----------------------------------------------------------------------------
void IKSolver::HandleNodeRemoved(StringHash eventType, VariantMap& eventData)
{
using namespace NodeRemoved;
if (solver_->tree == nullptr)
return;
auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
// Remove cached IKEffectors from our list
Vector<IKEffector*> effectors;
node->GetComponents<IKEffector>(effectors, true);
for (Vector<IKEffector*>::ConstIterator it = effectors.Begin(); it != effectors.End(); ++it)
{
(*it)->SetIKEffectorNode(nullptr);
effectorList_.RemoveSwap(*it);
}
Vector<IKConstraint*> constraints;
node->GetComponents<IKConstraint>(constraints, true);
for (Vector<IKConstraint*>::ConstIterator it = constraints.Begin(); it != constraints.End(); ++it)
{
constraintList_.RemoveSwap(*it);
}
// Special case, if the node being destroyed is the root node, destroy the
// solver's tree instead of destroying the single node. Calling
// ik_node_destroy() on the solver's root node will cause segfaults.
ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID());
if (ikNode != nullptr)
{
if (ikNode == solver_->tree)
ik_solver_destroy_tree(solver_);
else
ik_node_destroy(ikNode);
MarkChainsNeedUpdating();
}
}
// ----------------------------------------------------------------------------
void IKSolver::HandleSceneDrawableUpdateFinished(StringHash eventType, VariantMap& eventData)
{
Solve();
}
// ----------------------------------------------------------------------------
void IKSolver::DrawDebugGeometry(bool depthTest)
{
auto* debug = GetScene()->GetComponent<DebugRenderer>();
if (debug)
DrawDebugGeometry(debug, depthTest);
}
// ----------------------------------------------------------------------------
void IKSolver::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
{
// Draws all scene segments
for (Vector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it)
(*it)->DrawDebugGeometry(debug, depthTest);
ORDERED_VECTOR_FOR_EACH(&solver_->effector_nodes_list, ik_node_t*, pnode)
ik_effector_t* effector = (*pnode)->effector;
// Calculate average length of all segments so we can determine the radius
// of the debug spheres to draw
int chainLength = effector->chain_length == 0 ? -1 : effector->chain_length;
ik_node_t* a = *pnode;
ik_node_t* b = a->parent;
float averageLength = 0.0f;
unsigned numberOfSegments = 0;
while (b && chainLength-- != 0)
{
vec3_t v = a->original_position;
vec3_sub_vec3(v.f, b->original_position.f);
averageLength += vec3_length(v.f);
++numberOfSegments;
a = b;
b = b->parent;
}
averageLength /= numberOfSegments;
// connect all chained nodes together with lines
chainLength = effector->chain_length == 0 ? -1 : effector->chain_length;
a = *pnode;
b = a->parent;
debug->AddSphere(
Sphere(Vec3IK2Urho(&a->original_position), averageLength * 0.1f),
Color(0, 0, 255),
depthTest
);
debug->AddSphere(
Sphere(Vec3IK2Urho(&a->position), averageLength * 0.1f),
Color(255, 128, 0),
depthTest
);
while (b && chainLength-- != 0)
{
debug->AddLine(
Vec3IK2Urho(&a->original_position),
Vec3IK2Urho(&b->original_position),
Color(0, 255, 255),
depthTest
);
debug->AddSphere(
Sphere(Vec3IK2Urho(&b->original_position), averageLength * 0.1f),
Color(0, 0, 255),
depthTest
);
debug->AddLine(
Vec3IK2Urho(&a->position),
Vec3IK2Urho(&b->position),
Color(255, 0, 0),
depthTest
);
debug->AddSphere(
Sphere(Vec3IK2Urho(&b->position), averageLength * 0.1f),
Color(255, 128, 0),
depthTest
);
a = b;
b = b->parent;
}
ORDERED_VECTOR_END_EACH
}
// ----------------------------------------------------------------------------
// Need these wrapper functions flags of GetFeature/SetFeature can be correctly
// exposed to the editor
// ----------------------------------------------------------------------------
#define DEF_FEATURE_GETTER(feature_name) \
bool IKSolver::Get##feature_name() const \
{ \
return GetFeature(feature_name); \
}
#define DEF_FEATURE_SETTER(feature_name) \
void IKSolver::Set##feature_name(bool enable) \
{ \
SetFeature(feature_name, enable); \
}
DEF_FEATURE_GETTER(JOINT_ROTATIONS)
DEF_FEATURE_GETTER(TARGET_ROTATIONS)
DEF_FEATURE_GETTER(UPDATE_ORIGINAL_POSE)
DEF_FEATURE_GETTER(UPDATE_ACTIVE_POSE)
DEF_FEATURE_GETTER(USE_ORIGINAL_POSE)
DEF_FEATURE_GETTER(CONSTRAINTS)
DEF_FEATURE_GETTER(AUTO_SOLVE)
DEF_FEATURE_SETTER(JOINT_ROTATIONS)
DEF_FEATURE_SETTER(TARGET_ROTATIONS)
DEF_FEATURE_SETTER(UPDATE_ORIGINAL_POSE)
DEF_FEATURE_SETTER(UPDATE_ACTIVE_POSE)
DEF_FEATURE_SETTER(USE_ORIGINAL_POSE)
DEF_FEATURE_SETTER(CONSTRAINTS)
DEF_FEATURE_SETTER(AUTO_SOLVE)
} // namespace Urho3D
| 33.250304 | 197 | 0.587466 | jayrulez |
cd74b2c0719fc846f8b3ecd83fd50fd4f8253f4f | 3,349 | cpp | C++ | examples/Pose2SLAMwSPCG.cpp | zwn/gtsam | 3422c3bb66bef319d66a950857bb6ec073b43703 | [
"BSD-3-Clause"
] | 1,402 | 2017-03-28T00:18:11.000Z | 2022-03-30T10:28:32.000Z | examples/Pose2SLAMwSPCG.cpp | zwn/gtsam | 3422c3bb66bef319d66a950857bb6ec073b43703 | [
"BSD-3-Clause"
] | 851 | 2017-11-27T15:09:56.000Z | 2022-03-31T22:26:38.000Z | examples/Pose2SLAMwSPCG.cpp | zwn/gtsam | 3422c3bb66bef319d66a950857bb6ec073b43703 | [
"BSD-3-Clause"
] | 565 | 2017-11-30T16:15:59.000Z | 2022-03-31T02:53:04.000Z | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file Pose2SLAMwSPCG.cpp
* @brief A 2D Pose SLAM example using the SimpleSPCGSolver.
* @author Yong-Dian Jian
* @date June 2, 2012
*/
// For an explanation of headers below, please see Pose2SLAMExample.cpp
#include <gtsam/slam/BetweenFactor.h>
#include <gtsam/geometry/Pose2.h>
#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
// In contrast to that example, however, we will use a PCG solver here
#include <gtsam/linear/SubgraphSolver.h>
using namespace std;
using namespace gtsam;
int main(int argc, char** argv) {
// 1. Create a factor graph container and add factors to it
NonlinearFactorGraph graph;
// 2a. Add a prior on the first pose, setting it to the origin
Pose2 prior(0.0, 0.0, 0.0); // prior at origin
auto priorNoise = noiseModel::Diagonal::Sigmas(Vector3(0.3, 0.3, 0.1));
graph.addPrior(1, prior, priorNoise);
// 2b. Add odometry factors
auto odometryNoise = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1));
graph.emplace_shared<BetweenFactor<Pose2> >(1, 2, Pose2(2.0, 0.0, M_PI_2), odometryNoise);
graph.emplace_shared<BetweenFactor<Pose2> >(2, 3, Pose2(2.0, 0.0, M_PI_2), odometryNoise);
graph.emplace_shared<BetweenFactor<Pose2> >(3, 4, Pose2(2.0, 0.0, M_PI_2), odometryNoise);
graph.emplace_shared<BetweenFactor<Pose2> >(4, 5, Pose2(2.0, 0.0, M_PI_2), odometryNoise);
// 2c. Add the loop closure constraint
auto model = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1));
graph.emplace_shared<BetweenFactor<Pose2> >(5, 1, Pose2(0.0, 0.0, 0.0),
model);
graph.print("\nFactor Graph:\n"); // print
// 3. Create the data structure to hold the initialEstimate estimate to the
// solution
Values initialEstimate;
initialEstimate.insert(1, Pose2(0.5, 0.0, 0.2));
initialEstimate.insert(2, Pose2(2.3, 0.1, 1.1));
initialEstimate.insert(3, Pose2(2.1, 1.9, 2.8));
initialEstimate.insert(4, Pose2(-.3, 2.5, 4.2));
initialEstimate.insert(5, Pose2(0.1, -0.7, 5.8));
initialEstimate.print("\nInitial Estimate:\n"); // print
// 4. Single Step Optimization using Levenberg-Marquardt
LevenbergMarquardtParams parameters;
parameters.verbosity = NonlinearOptimizerParams::ERROR;
parameters.verbosityLM = LevenbergMarquardtParams::LAMBDA;
// LM is still the outer optimization loop, but by specifying "Iterative"
// below We indicate that an iterative linear solver should be used. In
// addition, the *type* of the iterativeParams decides on the type of
// iterative solver, in this case the SPCG (subgraph PCG)
parameters.linearSolverType = NonlinearOptimizerParams::Iterative;
parameters.iterativeParams = boost::make_shared<SubgraphSolverParameters>();
LevenbergMarquardtOptimizer optimizer(graph, initialEstimate, parameters);
Values result = optimizer.optimize();
result.print("Final Result:\n");
cout << "subgraph solver final error = " << graph.error(result) << endl;
return 0;
}
| 41.345679 | 92 | 0.682293 | zwn |
cd778fa773c1ed4aa674daa897d493533115fcdb | 23,425 | cpp | C++ | aidl.cpp | 00liujj/aidl-cpp | 24ddb77dc7f38e12627f1c7cdaed34d66cd2baf4 | [
"Apache-2.0"
] | 6 | 2017-06-30T05:36:52.000Z | 2022-03-24T01:08:46.000Z | aidl.cpp | 00liujj/aidl-cpp | 24ddb77dc7f38e12627f1c7cdaed34d66cd2baf4 | [
"Apache-2.0"
] | 3 | 2018-06-06T07:02:22.000Z | 2018-06-06T11:29:16.000Z | aidl.cpp | 00liujj/aidl-cpp | 24ddb77dc7f38e12627f1c7cdaed34d66cd2baf4 | [
"Apache-2.0"
] | 20 | 2017-06-15T01:37:23.000Z | 2022-03-25T23:13:06.000Z | /*
* Copyright (C) 2015, The Android Open Source Project
*
* 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 "aidl.h"
#include <fcntl.h>
#include <iostream>
#include <map>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef _WIN32
#include <io.h>
#include <direct.h>
#include <sys/stat.h>
#endif
#include <android-base/strings.h>
#include "aidl_language.h"
#include "generate_cpp.h"
#include "generate_java.h"
#include "import_resolver.h"
#include "logging.h"
#include "options.h"
#include "os.h"
#include "type_cpp.h"
#include "type_java.h"
#include "type_namespace.h"
#ifndef O_BINARY
# define O_BINARY 0
#endif
using android::base::Join;
using android::base::Split;
using std::cerr;
using std::endl;
using std::map;
using std::set;
using std::string;
using std::unique_ptr;
using std::vector;
namespace android {
namespace aidl {
namespace {
// The following are gotten as the offset from the allowable id's between
// android.os.IBinder.FIRST_CALL_TRANSACTION=1 and
// android.os.IBinder.LAST_CALL_TRANSACTION=16777215
const int kMinUserSetMethodId = 0;
const int kMaxUserSetMethodId = 16777214;
bool check_filename(const std::string& filename,
const std::string& package,
const std::string& name,
unsigned line) {
const char* p;
string expected;
string fn;
size_t len;
bool valid = false;
if (!IoDelegate::GetAbsolutePath(filename, &fn)) {
return false;
}
if (!package.empty()) {
expected = package;
expected += '.';
}
len = expected.length();
for (size_t i=0; i<len; i++) {
if (expected[i] == '.') {
expected[i] = OS_PATH_SEPARATOR;
}
}
expected.append(name, 0, name.find('.'));
expected += ".aidl";
len = fn.length();
valid = (len >= expected.length());
if (valid) {
p = fn.c_str() + (len - expected.length());
#ifdef _WIN32
if (OS_PATH_SEPARATOR != '/') {
// Input filename under cygwin most likely has / separators
// whereas the expected string uses \\ separators. Adjust
// them accordingly.
for (char *c = const_cast<char *>(p); *c; ++c) {
if (*c == '/') *c = OS_PATH_SEPARATOR;
}
}
#endif
// aidl assumes case-insensitivity on Mac Os and Windows.
#if defined(__linux__)
valid = (expected == p);
#else
valid = !strcasecmp(expected.c_str(), p);
#endif
}
if (!valid) {
fprintf(stderr, "%s:%d interface %s should be declared in a file"
" called %s.\n",
filename.c_str(), line, name.c_str(), expected.c_str());
}
return valid;
}
bool check_filenames(const std::string& filename, const AidlDocument* doc) {
if (!doc)
return true;
const AidlInterface* interface = doc->GetInterface();
if (interface) {
return check_filename(filename, interface->GetPackage(),
interface->GetName(), interface->GetLine());
}
bool success = true;
for (const auto& item : doc->GetParcelables()) {
success &= check_filename(filename, item->GetPackage(), item->GetName(),
item->GetLine());
}
return success;
}
bool gather_types(const std::string& filename,
const AidlDocument* doc,
TypeNamespace* types) {
bool success = true;
const AidlInterface* interface = doc->GetInterface();
if (interface)
return types->AddBinderType(*interface, filename);
for (const auto& item : doc->GetParcelables()) {
success &= types->AddParcelableType(*item, filename);
}
return success;
}
int check_types(const string& filename,
const AidlInterface* c,
TypeNamespace* types) {
int err = 0;
if (c->IsUtf8() && c->IsUtf8InCpp()) {
cerr << filename << ":" << c->GetLine()
<< "Interface cannot be marked as both @utf8 and @utf8InCpp";
err = 1;
}
// Has to be a pointer due to deleting copy constructor. No idea why.
map<string, const AidlMethod*> method_names;
for (const auto& m : c->GetMethods()) {
bool oneway = m->IsOneway() || c->IsOneway();
if (!types->MaybeAddContainerType(m->GetType())) {
err = 1; // return type is invalid
}
const ValidatableType* return_type =
types->GetReturnType(m->GetType(), filename, *c);
if (!return_type) {
err = 1;
}
m->GetMutableType()->SetLanguageType(return_type);
if (oneway && m->GetType().GetName() != "void") {
cerr << filename << ":" << m->GetLine()
<< " oneway method '" << m->GetName() << "' cannot return a value"
<< endl;
err = 1;
}
int index = 1;
for (const auto& arg : m->GetArguments()) {
if (!types->MaybeAddContainerType(arg->GetType())) {
err = 1;
}
const ValidatableType* arg_type =
types->GetArgType(*arg, index, filename, *c);
if (!arg_type) {
err = 1;
}
arg->GetMutableType()->SetLanguageType(arg_type);
if (oneway && arg->IsOut()) {
cerr << filename << ":" << m->GetLine()
<< " oneway method '" << m->GetName()
<< "' cannot have out parameters" << endl;
err = 1;
}
}
auto it = method_names.find(m->GetName());
// prevent duplicate methods
if (it == method_names.end()) {
method_names[m->GetName()] = m.get();
} else {
cerr << filename << ":" << m->GetLine()
<< " attempt to redefine method " << m->GetName() << "," << endl
<< filename << ":" << it->second->GetLine()
<< " previously defined here." << endl;
err = 1;
}
}
return err;
}
void write_common_dep_file(const string& output_file,
const vector<string>& aidl_sources,
CodeWriter* writer) {
// Encode that the output file depends on aidl input files.
writer->Write("%s : \\\n", output_file.c_str());
writer->Write(" %s", Join(aidl_sources, " \\\n ").c_str());
writer->Write("\n\n");
// Output "<input_aidl_file>: " so make won't fail if the input .aidl file
// has been deleted, moved or renamed in incremental build.
for (const auto& src : aidl_sources) {
writer->Write("%s :\n", src.c_str());
}
}
bool write_java_dep_file(const JavaOptions& options,
const vector<unique_ptr<AidlImport>>& imports,
const IoDelegate& io_delegate,
const string& output_file_name) {
string dep_file_name = options.DependencyFilePath();
if (dep_file_name.empty()) {
return true; // nothing to do
}
CodeWriterPtr writer = io_delegate.GetCodeWriter(dep_file_name);
if (!writer) {
LOG(ERROR) << "Could not open dependency file: " << dep_file_name;
return false;
}
vector<string> source_aidl = {options.input_file_name_};
for (const auto& import : imports) {
if (!import->GetFilename().empty()) {
source_aidl.push_back(import->GetFilename());
}
}
write_common_dep_file(output_file_name, source_aidl, writer.get());
return true;
}
bool write_cpp_dep_file(const CppOptions& options,
const AidlInterface& interface,
const vector<unique_ptr<AidlImport>>& imports,
const IoDelegate& io_delegate) {
using ::android::aidl::cpp::HeaderFile;
using ::android::aidl::cpp::ClassNames;
string dep_file_name = options.DependencyFilePath();
if (dep_file_name.empty()) {
return true; // nothing to do
}
CodeWriterPtr writer = io_delegate.GetCodeWriter(dep_file_name);
if (!writer) {
LOG(ERROR) << "Could not open dependency file: " << dep_file_name;
return false;
}
vector<string> source_aidl = {options.InputFileName()};
for (const auto& import : imports) {
if (!import->GetFilename().empty()) {
source_aidl.push_back(import->GetFilename());
}
}
vector<string> headers;
for (ClassNames c : {ClassNames::CLIENT,
ClassNames::SERVER,
ClassNames::INTERFACE}) {
headers.push_back(options.OutputHeaderDir() + '/' +
HeaderFile(interface, c, false /* use_os_sep */));
}
write_common_dep_file(options.OutputCppFilePath(), source_aidl, writer.get());
writer->Write("\n");
// Generated headers also depend on the source aidl files.
writer->Write("%s : \\\n %s\n", Join(headers, " \\\n ").c_str(),
Join(source_aidl, " \\\n ").c_str());
return true;
}
string generate_outputFileName(const JavaOptions& options,
const AidlInterface& interface) {
const string& name = interface.GetName();
string package = interface.GetPackage();
string result;
// create the path to the destination folder based on the
// interface package name
result = options.output_base_folder_;
result += OS_PATH_SEPARATOR;
string packageStr = package;
size_t len = packageStr.length();
for (size_t i=0; i<len; i++) {
if (packageStr[i] == '.') {
packageStr[i] = OS_PATH_SEPARATOR;
}
}
result += packageStr;
// add the filename by replacing the .aidl extension to .java
result += OS_PATH_SEPARATOR;
result.append(name, 0, name.find('.'));
result += ".java";
return result;
}
int check_and_assign_method_ids(const char * filename,
const std::vector<std::unique_ptr<AidlMethod>>& items) {
// Check whether there are any methods with manually assigned id's and any that are not.
// Either all method id's must be manually assigned or all of them must not.
// Also, check for duplicates of user set id's and that the id's are within the proper bounds.
set<int> usedIds;
bool hasUnassignedIds = false;
bool hasAssignedIds = false;
for (const auto& item : items) {
if (item->HasId()) {
hasAssignedIds = true;
// Ensure that the user set id is not duplicated.
if (usedIds.find(item->GetId()) != usedIds.end()) {
// We found a duplicate id, so throw an error.
fprintf(stderr,
"%s:%d Found duplicate method id (%d) for method: %s\n",
filename, item->GetLine(),
item->GetId(), item->GetName().c_str());
return 1;
}
// Ensure that the user set id is within the appropriate limits
if (item->GetId() < kMinUserSetMethodId ||
item->GetId() > kMaxUserSetMethodId) {
fprintf(stderr, "%s:%d Found out of bounds id (%d) for method: %s\n",
filename, item->GetLine(),
item->GetId(), item->GetName().c_str());
fprintf(stderr, " Value for id must be between %d and %d inclusive.\n",
kMinUserSetMethodId, kMaxUserSetMethodId);
return 1;
}
usedIds.insert(item->GetId());
} else {
hasUnassignedIds = true;
}
if (hasAssignedIds && hasUnassignedIds) {
fprintf(stderr,
"%s: You must either assign id's to all methods or to none of them.\n",
filename);
return 1;
}
}
// In the case that all methods have unassigned id's, set a unique id for them.
if (hasUnassignedIds) {
int newId = 0;
for (const auto& item : items) {
item->SetId(newId++);
}
}
// success
return 0;
}
bool validate_constants(const AidlInterface& interface) {
bool success = true;
set<string> names;
for (const std::unique_ptr<AidlIntConstant>& int_constant :
interface.GetIntConstants()) {
if (names.count(int_constant->GetName()) > 0) {
LOG(ERROR) << "Found duplicate constant name '" << int_constant->GetName()
<< "'";
success = false;
}
names.insert(int_constant->GetName());
// We've logged an error message for this on object construction.
success = success && int_constant->IsValid();
}
for (const std::unique_ptr<AidlStringConstant>& string_constant :
interface.GetStringConstants()) {
if (names.count(string_constant->GetName()) > 0) {
LOG(ERROR) << "Found duplicate constant name '" << string_constant->GetName()
<< "'";
success = false;
}
names.insert(string_constant->GetName());
// We've logged an error message for this on object construction.
success = success && string_constant->IsValid();
}
return success;
}
// TODO: Remove this in favor of using the YACC parser b/25479378
bool ParsePreprocessedLine(const string& line, string* decl,
vector<string>* package, string* class_name) {
// erase all trailing whitespace and semicolons
const size_t end = line.find_last_not_of(" ;\t");
if (end == string::npos) {
return false;
}
if (line.rfind(';', end) != string::npos) {
return false;
}
decl->clear();
string type;
vector<string> pieces = Split(line.substr(0, end + 1), " \t");
for (const string& piece : pieces) {
if (piece.empty()) {
continue;
}
if (decl->empty()) {
*decl = std::move(piece);
} else if (type.empty()) {
type = std::move(piece);
} else {
return false;
}
}
// Note that this logic is absolutely wrong. Given a parcelable
// org.some.Foo.Bar, the class name is Foo.Bar, but this code will claim that
// the class is just Bar. However, this was the way it was done in the past.
//
// See b/17415692
size_t dot_pos = type.rfind('.');
if (dot_pos != string::npos) {
*class_name = type.substr(dot_pos + 1);
*package = Split(type.substr(0, dot_pos), ".");
} else {
*class_name = type;
package->clear();
}
return true;
}
} // namespace
namespace internals {
bool parse_preprocessed_file(const IoDelegate& io_delegate,
const string& filename, TypeNamespace* types) {
bool success = true;
unique_ptr<LineReader> line_reader = io_delegate.GetLineReader(filename);
if (!line_reader) {
LOG(ERROR) << "cannot open preprocessed file: " << filename;
success = false;
return success;
}
string line;
unsigned lineno = 1;
for ( ; line_reader->ReadLine(&line); ++lineno) {
if (line.empty() || line.compare(0, 2, "//") == 0) {
// skip comments and empty lines
continue;
}
string decl;
vector<string> package;
string class_name;
if (!ParsePreprocessedLine(line, &decl, &package, &class_name)) {
success = false;
break;
}
if (decl == "parcelable") {
AidlParcelable doc(new AidlQualifiedName(class_name, ""),
lineno, package);
types->AddParcelableType(doc, filename);
} else if (decl == "interface") {
auto temp = new std::vector<std::unique_ptr<AidlMember>>();
AidlInterface doc(class_name, lineno, "", false, temp, package);
types->AddBinderType(doc, filename);
} else {
success = false;
break;
}
}
if (!success) {
LOG(ERROR) << filename << ':' << lineno
<< " malformed preprocessed file line: '" << line << "'";
}
return success;
}
AidlError load_and_validate_aidl(
const std::vector<std::string>& preprocessed_files,
const std::vector<std::string>& import_paths,
const std::string& input_file_name,
const IoDelegate& io_delegate,
TypeNamespace* types,
std::unique_ptr<AidlInterface>* returned_interface,
std::vector<std::unique_ptr<AidlImport>>* returned_imports) {
AidlError err = AidlError::OK;
std::map<AidlImport*,std::unique_ptr<AidlDocument>> docs;
// import the preprocessed file
for (const string& s : preprocessed_files) {
if (!parse_preprocessed_file(io_delegate, s, types)) {
err = AidlError::BAD_PRE_PROCESSED_FILE;
}
}
if (err != AidlError::OK) {
return err;
}
// parse the input file
Parser p{io_delegate};
if (!p.ParseFile(input_file_name)) {
return AidlError::PARSE_ERROR;
}
AidlDocument* parsed_doc = p.GetDocument();
unique_ptr<AidlInterface> interface(parsed_doc->ReleaseInterface());
if (!interface) {
LOG(ERROR) << "refusing to generate code from aidl file defining "
"parcelable";
return AidlError::FOUND_PARCELABLE;
}
if (!check_filename(input_file_name.c_str(), interface->GetPackage(),
interface->GetName(), interface->GetLine()) ||
!types->IsValidPackage(interface->GetPackage())) {
LOG(ERROR) << "Invalid package declaration '" << interface->GetPackage()
<< "'";
return AidlError::BAD_PACKAGE;
}
// parse the imports of the input file
ImportResolver import_resolver{io_delegate, import_paths};
for (auto& import : p.GetImports()) {
if (types->HasImportType(*import)) {
// There are places in the Android tree where an import doesn't resolve,
// but we'll pick the type up through the preprocessed types.
// This seems like an error, but legacy support demands we support it...
continue;
}
string import_path = import_resolver.FindImportFile(import->GetNeededClass());
if (import_path.empty()) {
cerr << import->GetFileFrom() << ":" << import->GetLine()
<< ": couldn't find import for class "
<< import->GetNeededClass() << endl;
err = AidlError::BAD_IMPORT;
continue;
}
import->SetFilename(import_path);
Parser p{io_delegate};
if (!p.ParseFile(import->GetFilename())) {
cerr << "error while parsing import for class "
<< import->GetNeededClass() << endl;
err = AidlError::BAD_IMPORT;
continue;
}
std::unique_ptr<AidlDocument> document(p.ReleaseDocument());
if (!check_filenames(import->GetFilename(), document.get()))
err = AidlError::BAD_IMPORT;
docs[import.get()] = std::move(document);
}
if (err != AidlError::OK) {
return err;
}
// gather the types that have been declared
if (!types->AddBinderType(*interface.get(), input_file_name)) {
err = AidlError::BAD_TYPE;
}
interface->SetLanguageType(types->GetInterfaceType(*interface));
for (const auto& import : p.GetImports()) {
// If we skipped an unresolved import above (see comment there) we'll have
// an empty bucket here.
const auto import_itr = docs.find(import.get());
if (import_itr == docs.cend()) {
continue;
}
if (!gather_types(import->GetFilename(), import_itr->second.get(), types)) {
err = AidlError::BAD_TYPE;
}
}
// check the referenced types in parsed_doc to make sure we've imported them
if (check_types(input_file_name, interface.get(), types) != 0) {
err = AidlError::BAD_TYPE;
}
if (err != AidlError::OK) {
return err;
}
// assign method ids and validate.
if (check_and_assign_method_ids(input_file_name.c_str(),
interface->GetMethods()) != 0) {
return AidlError::BAD_METHOD_ID;
}
if (!validate_constants(*interface)) {
return AidlError::BAD_CONSTANTS;
}
if (returned_interface)
*returned_interface = std::move(interface);
if (returned_imports)
p.ReleaseImports(returned_imports);
return AidlError::OK;
}
} // namespace internals
int compile_aidl_to_cpp(const CppOptions& options,
const IoDelegate& io_delegate) {
unique_ptr<AidlInterface> interface;
std::vector<std::unique_ptr<AidlImport>> imports;
unique_ptr<cpp::TypeNamespace> types(new cpp::TypeNamespace());
types->Init();
AidlError err = internals::load_and_validate_aidl(
std::vector<std::string>{}, // no preprocessed files
options.ImportPaths(),
options.InputFileName(),
io_delegate,
types.get(),
&interface,
&imports);
if (err != AidlError::OK) {
return 1;
}
if (!write_cpp_dep_file(options, *interface, imports, io_delegate)) {
return 1;
}
return (cpp::GenerateCpp(options, *types, *interface, io_delegate)) ? 0 : 1;
}
int compile_aidl_to_java(const JavaOptions& options,
const IoDelegate& io_delegate) {
unique_ptr<AidlInterface> interface;
std::vector<std::unique_ptr<AidlImport>> imports;
unique_ptr<java::JavaTypeNamespace> types(new java::JavaTypeNamespace());
types->Init();
AidlError aidl_err = internals::load_and_validate_aidl(
options.preprocessed_files_,
options.import_paths_,
options.input_file_name_,
io_delegate,
types.get(),
&interface,
&imports);
if (aidl_err == AidlError::FOUND_PARCELABLE && !options.fail_on_parcelable_) {
// We aborted code generation because this file contains parcelables.
// However, we were not told to complain if we find parcelables.
// Just generate a dep file and exit quietly. The dep file is for a legacy
// use case by the SDK.
write_java_dep_file(options, imports, io_delegate, "");
return 0;
}
if (aidl_err != AidlError::OK) {
return 1;
}
string output_file_name = options.output_file_name_;
// if needed, generate the output file name from the base folder
if (output_file_name.empty() && !options.output_base_folder_.empty()) {
output_file_name = generate_outputFileName(options, *interface);
}
// make sure the folders of the output file all exists
if (!io_delegate.CreatePathForFile(output_file_name)) {
return 1;
}
if (!write_java_dep_file(options, imports, io_delegate, output_file_name)) {
return 1;
}
return generate_java(output_file_name, options.input_file_name_.c_str(),
interface.get(), types.get(), io_delegate);
}
bool preprocess_aidl(const JavaOptions& options,
const IoDelegate& io_delegate) {
unique_ptr<CodeWriter> writer =
io_delegate.GetCodeWriter(options.output_file_name_);
for (const auto& file : options.files_to_preprocess_) {
Parser p{io_delegate};
if (!p.ParseFile(file))
return false;
AidlDocument* doc = p.GetDocument();
string line;
const AidlInterface* interface = doc->GetInterface();
if (interface != nullptr &&
!writer->Write("interface %s;\n",
interface->GetCanonicalName().c_str())) {
return false;
}
for (const auto& parcelable : doc->GetParcelables()) {
if (!writer->Write("parcelable %s;\n",
parcelable->GetCanonicalName().c_str())) {
return false;
}
}
}
return writer->Close();
}
} // namespace android
} // namespace aidl
| 30.343264 | 98 | 0.613917 | 00liujj |
cd77d64ff58bcd54cc6fd4ece1ce31e8ec2b701b | 2,741 | hpp | C++ | libraries/boost/include/boost/mp11/set.hpp | cucubao/eosio.cdt | 4985359a30da1f883418b7133593f835927b8046 | [
"MIT"
] | 918 | 2016-12-22T02:53:08.000Z | 2022-03-22T06:21:35.000Z | libraries/boost/include/boost/mp11/set.hpp | cucubao/eosio.cdt | 4985359a30da1f883418b7133593f835927b8046 | [
"MIT"
] | 594 | 2018-09-06T02:03:01.000Z | 2022-03-23T19:18:26.000Z | libraries/boost/include/boost/mp11/set.hpp | cucubao/eosio.cdt | 4985359a30da1f883418b7133593f835927b8046 | [
"MIT"
] | 349 | 2018-09-06T05:02:09.000Z | 2022-03-12T11:07:17.000Z | #ifndef BOOST_MP11_SET_HPP_INCLUDED
#define BOOST_MP11_SET_HPP_INCLUDED
// Copyright 2015 Peter Dimov.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <boost/mp11/utility.hpp>
#include <boost/mp11/detail/mp_list.hpp>
#include <type_traits>
namespace boost
{
namespace mp11
{
// mp_set_contains<S, V>
namespace detail
{
template<class S, class V> struct mp_set_contains_impl;
template<template<class...> class L, class... T, class V> struct mp_set_contains_impl<L<T...>, V>
{
using type = mp_to_bool<std::is_base_of<mp_identity<V>, mp_inherit<mp_identity<T>...>>>;
};
} // namespace detail
template<class S, class V> using mp_set_contains = typename detail::mp_set_contains_impl<S, V>::type;
// mp_set_push_back<S, T...>
namespace detail
{
template<class S, class... T> struct mp_set_push_back_impl;
template<template<class...> class L, class... U> struct mp_set_push_back_impl<L<U...>>
{
using type = L<U...>;
};
template<template<class...> class L, class... U, class T1, class... T> struct mp_set_push_back_impl<L<U...>, T1, T...>
{
using S = mp_if<mp_set_contains<L<U...>, T1>, L<U...>, L<U..., T1>>;
using type = typename mp_set_push_back_impl<S, T...>::type;
};
} // namespace detail
template<class S, class... T> using mp_set_push_back = typename detail::mp_set_push_back_impl<S, T...>::type;
// mp_set_push_front<S, T...>
namespace detail
{
template<class S, class... T> struct mp_set_push_front_impl;
template<template<class...> class L, class... U> struct mp_set_push_front_impl<L<U...>>
{
using type = L<U...>;
};
template<template<class...> class L, class... U, class T1> struct mp_set_push_front_impl<L<U...>, T1>
{
using type = mp_if<mp_set_contains<L<U...>, T1>, L<U...>, L<T1, U...>>;
};
template<template<class...> class L, class... U, class T1, class... T> struct mp_set_push_front_impl<L<U...>, T1, T...>
{
using S = typename mp_set_push_front_impl<L<U...>, T...>::type;
using type = typename mp_set_push_front_impl<S, T1>::type;
};
} // namespace detail
template<class S, class... T> using mp_set_push_front = typename detail::mp_set_push_front_impl<S, T...>::type;
// mp_is_set<S>
namespace detail
{
template<class S> struct mp_is_set_impl
{
using type = mp_false;
};
template<template<class...> class L, class... T> struct mp_is_set_impl<L<T...>>
{
using type = mp_to_bool<std::is_same<mp_list<T...>, mp_set_push_back<mp_list<>, T...>>>;
};
} // namespace detail
template<class S> using mp_is_set = typename detail::mp_is_set_impl<S>::type;
} // namespace mp11
} // namespace boost
#endif // #ifndef BOOST_MP11_SET_HPP_INCLUDED
| 26.355769 | 119 | 0.690259 | cucubao |
cd7a8303bf8d76d374813d0d463c93329f6c1104 | 1,306 | cpp | C++ | server/src/route_server/route_server.cpp | xiaominfc/TeamTalk | 20084010a9804d1ff0ed7bb5924fde7041b952eb | [
"Apache-2.0"
] | 65 | 2017-11-18T15:43:56.000Z | 2022-01-30T08:07:11.000Z | server/src/route_server/route_server.cpp | xiaominfc/TeamTalk | 20084010a9804d1ff0ed7bb5924fde7041b952eb | [
"Apache-2.0"
] | 3 | 2018-09-04T14:27:45.000Z | 2020-10-29T07:22:45.000Z | server/src/route_server/route_server.cpp | xiaominfc/TeamTalk | 20084010a9804d1ff0ed7bb5924fde7041b952eb | [
"Apache-2.0"
] | 36 | 2018-07-10T04:21:08.000Z | 2021-11-09T07:21:10.000Z | /*
* @Author: xiaominfc
* @Date: 2020-09-02 17:10:06
* @Description: main run for routeserver
*/
#include "RouteConn.h"
#include "netlib.h"
#include "ConfigFileReader.h"
#include "version.h"
#include "EventSocket.h"
int main(int argc, char* argv[])
{
PRINTSERVERVERSION()
signal(SIGPIPE, SIG_IGN);
srand(time(NULL));
CConfigFileReader config_file("routeserver.conf");
char* listen_ip = config_file.GetConfigName("ListenIP");
char* str_listen_msg_port = config_file.GetConfigName("ListenMsgPort");
if (!listen_ip || !str_listen_msg_port) {
log("config item missing, exit... ");
return -1;
}
uint16_t listen_msg_port = atoi(str_listen_msg_port);
int ret = netlib_init();
if (ret == NETLIB_ERROR)
return ret;
CStrExplode listen_ip_list(listen_ip, ';');
for (uint32_t i = 0; i < listen_ip_list.GetItemCnt(); i++) {
//ret = netlib_listen(listen_ip_list.GetItem(i), listen_msg_port, route_serv_callback, NULL);
ret = tcp_server_listen(listen_ip_list.GetItem(i), listen_msg_port,new IMConnEventDefaultFactory<CRouteConn>());
if (ret == NETLIB_ERROR)
return ret;
}
printf("server start listen on: %s:%d\n", listen_ip, listen_msg_port);
init_routeconn_timer_callback();
printf("now enter the event loop...\n");
writePid();
netlib_eventloop();
return 0;
}
| 22.517241 | 114 | 0.715161 | xiaominfc |
cd7d73f759922ffcefdf3bed814dffc7e3d9b9c1 | 721 | cpp | C++ | LeetCode/230 - Kth Smallest Element in a BST.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | LeetCode/230 - Kth Smallest Element in a BST.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | LeetCode/230 - Kth Smallest Element in a BST.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | // https://leetcode.com/problems/kth-smallest-element-in-a-bst/
// Honestly, this problem should be classified as easy.
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> s;
TreeNode* cur = root;
while(cur != NULL){
s.push(cur);
cur = cur->left;
}
while(k--){
cur = s.top();
s.pop();
if(k > 0 && cur->right != NULL){
s.push(cur->right);
cur = cur->right;
while(cur->left != NULL){
s.push(cur->left);
cur = cur->left;
}
}
}
return cur->val;
}
}; | 25.75 | 63 | 0.424411 | GokulVSD |
cd80bd2dcf925d2dfd4d4bcf05fd50de26f5b5b5 | 1,130 | hh | C++ | maxutils/maxbase/include/maxbase/watchedworker.hh | blylei/MaxScale | 2de10c9de12664e6d59f1ef879fd90d44b73d472 | [
"BSD-3-Clause"
] | null | null | null | maxutils/maxbase/include/maxbase/watchedworker.hh | blylei/MaxScale | 2de10c9de12664e6d59f1ef879fd90d44b73d472 | [
"BSD-3-Clause"
] | null | null | null | maxutils/maxbase/include/maxbase/watchedworker.hh | blylei/MaxScale | 2de10c9de12664e6d59f1ef879fd90d44b73d472 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2018 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2025-03-24
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#pragma once
#include <maxbase/ccdefs.hh>
#include <atomic>
#include <maxbase/worker.hh>
#include <maxbase/watchdognotifier.hh>
namespace maxbase
{
/**
* @class WatchedWorker
*
* Base-class for workers that should be watched, that is, monitored
* to ensure that they are processing epoll events.
*
* If a watched worker stops processing events it will cause the systemd
* watchdog notification *not* to be generated, with the effect that the
* process is killed and restarted.
*/
class WatchedWorker : public Worker,
public WatchdogNotifier::Dependent
{
public:
~WatchedWorker();
protected:
WatchedWorker(mxb::WatchdogNotifier* pNotifier);
private:
void call_epoll_tick() override final;
};
}
| 24.042553 | 75 | 0.723894 | blylei |
cd81a0755febba52e79794a767cdaabda45aba10 | 3,894 | cpp | C++ | src/modules/commander/Arming/PreFlightCheck/checks/imuConsistencyCheck.cpp | sundxfansky/Firmware | 0e70578052d938ea87c70837a15185b99dbb2309 | [
"BSD-3-Clause"
] | 10 | 2020-11-25T14:04:15.000Z | 2022-03-02T23:46:57.000Z | src/modules/commander/Arming/PreFlightCheck/checks/imuConsistencyCheck.cpp | choudhary0parivesh/Firmware | 02f4ad61ec8eb4f7906dd06b4eb1fd6abb994244 | [
"BSD-3-Clause"
] | 20 | 2017-11-30T09:49:45.000Z | 2018-02-12T07:56:29.000Z | src/modules/commander/Arming/PreFlightCheck/checks/imuConsistencyCheck.cpp | choudhary0parivesh/Firmware | 02f4ad61ec8eb4f7906dd06b4eb1fd6abb994244 | [
"BSD-3-Clause"
] | 10 | 2019-04-02T09:06:30.000Z | 2021-06-23T15:52:33.000Z | /****************************************************************************
*
* Copyright (c) 2019 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include "../PreFlightCheck.hpp"
#include <HealthFlags.h>
#include <lib/parameters/param.h>
#include <systemlib/mavlink_log.h>
#include <uORB/Subscription.hpp>
#include <uORB/topics/sensor_preflight.h>
#include <uORB/topics/subsystem_info.h>
bool PreFlightCheck::imuConsistencyCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status,
const bool report_status)
{
float test_limit = 1.0f; // pass limit re-used for each test
// Get sensor_preflight data if available and exit with a fail recorded if not
uORB::SubscriptionData<sensor_preflight_s> sensors_sub{ORB_ID(sensor_preflight)};
sensors_sub.update();
const sensor_preflight_s &sensors = sensors_sub.get();
// Use the difference between IMU's to detect a bad calibration.
// If a single IMU is fitted, the value being checked will be zero so this check will always pass.
param_get(param_find("COM_ARM_IMU_ACC"), &test_limit);
if (sensors.accel_inconsistency_m_s_s > test_limit) {
if (report_status) {
mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Accels inconsistent - Check Cal");
set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_ACC, false, status);
set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_ACC2, false, status);
}
return false;
} else if (sensors.accel_inconsistency_m_s_s > test_limit * 0.8f) {
if (report_status) {
mavlink_log_info(mavlink_log_pub, "Preflight Advice: Accels inconsistent - Check Cal");
}
}
// Fail if gyro difference greater than 5 deg/sec and notify if greater than 2.5 deg/sec
param_get(param_find("COM_ARM_IMU_GYR"), &test_limit);
if (sensors.gyro_inconsistency_rad_s > test_limit) {
if (report_status) {
mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Gyros inconsistent - Check Cal");
set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_GYRO, false, status);
set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_GYRO2, false, status);
}
return false;
} else if (sensors.gyro_inconsistency_rad_s > test_limit * 0.5f) {
if (report_status) {
mavlink_log_info(mavlink_log_pub, "Preflight Advice: Gyros inconsistent - Check Cal");
}
}
return true;
}
| 41.870968 | 99 | 0.736518 | sundxfansky |
cd81fecd4c9d9f99fcbe88efe5f5214345719f6c | 47,585 | cpp | C++ | gdal/ogr/ogrsf_frmts/libkml/ogrlibkmlfield.cpp | chambbj/gdal | 3d56aecb5b8e9890dae8f560acd099992e707d12 | [
"MIT"
] | 1 | 2015-02-16T16:51:38.000Z | 2015-02-16T16:51:38.000Z | gdal/ogr/ogrsf_frmts/libkml/ogrlibkmlfield.cpp | theduckylittle/gdal | 61be261cae524582ba28bceebb027cc1e967e0ab | [
"MIT"
] | null | null | null | gdal/ogr/ogrsf_frmts/libkml/ogrlibkmlfield.cpp | theduckylittle/gdal | 61be261cae524582ba28bceebb027cc1e967e0ab | [
"MIT"
] | null | null | null | /******************************************************************************
*
* Project: KML Translator
* Purpose: Implements OGRLIBKMLDriver
* Author: Brian Case, rush at winkey dot org
*
******************************************************************************
* Copyright (c) 2010, Brian Case
*
* 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 <ogrsf_frmts.h>
#include <ogr_feature.h>
#include "ogr_p.h"
#include <kml/dom.h>
#include <iostream>
using kmldom::ExtendedDataPtr;
using kmldom::SchemaPtr;
using kmldom::SchemaDataPtr;
using kmldom::SimpleDataPtr;
using kmldom::DataPtr;
using kmldom::TimeStampPtr;
using kmldom::TimeSpanPtr;
using kmldom::TimePrimitivePtr;
using kmldom::PointPtr;
using kmldom::LineStringPtr;
using kmldom::PolygonPtr;
using kmldom::MultiGeometryPtr;
using kmldom::GeometryPtr;
using kmldom::FeaturePtr;
using kmldom::GroundOverlayPtr;
using kmldom::IconPtr;
#include "ogr_libkml.h"
#include "ogrlibkmlfield.h"
void ogr2altitudemode_rec (
GeometryPtr poKmlGeometry,
int iAltitudeMode,
int isGX )
{
PointPtr poKmlPoint;
LineStringPtr poKmlLineString;
PolygonPtr poKmlPolygon;
MultiGeometryPtr poKmlMultiGeometry;
size_t nGeom;
size_t i;
switch ( poKmlGeometry->Type ( ) ) {
case kmldom::Type_Point:
poKmlPoint = AsPoint ( poKmlGeometry );
if ( !isGX )
poKmlPoint->set_altitudemode ( iAltitudeMode );
else
poKmlPoint->set_gx_altitudemode ( iAltitudeMode );
break;
case kmldom::Type_LineString:
poKmlLineString = AsLineString ( poKmlGeometry );
if ( !isGX )
poKmlLineString->set_altitudemode ( iAltitudeMode );
else
poKmlLineString->set_gx_altitudemode ( iAltitudeMode );
break;
case kmldom::Type_LinearRing:
break;
case kmldom::Type_Polygon:
poKmlPolygon = AsPolygon ( poKmlGeometry );
if ( !isGX )
poKmlPolygon->set_altitudemode ( iAltitudeMode );
else
poKmlPolygon->set_gx_altitudemode ( iAltitudeMode );
break;
case kmldom::Type_MultiGeometry:
poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry );
nGeom = poKmlMultiGeometry->get_geometry_array_size ( );
for ( i = 0; i < nGeom; i++ ) {
ogr2altitudemode_rec ( poKmlMultiGeometry->
get_geometry_array_at ( i ), iAltitudeMode,
isGX );
}
break;
default:
break;
}
}
void ogr2extrude_rec (
int nExtrude,
GeometryPtr poKmlGeometry )
{
PointPtr poKmlPoint;
LineStringPtr poKmlLineString;
PolygonPtr poKmlPolygon;
MultiGeometryPtr poKmlMultiGeometry;
size_t nGeom;
size_t i;
switch ( poKmlGeometry->Type ( ) ) {
case kmldom::Type_Point:
poKmlPoint = AsPoint ( poKmlGeometry );
poKmlPoint->set_extrude ( nExtrude );
break;
case kmldom::Type_LineString:
poKmlLineString = AsLineString ( poKmlGeometry );
poKmlLineString->set_extrude ( nExtrude );
break;
case kmldom::Type_LinearRing:
break;
case kmldom::Type_Polygon:
poKmlPolygon = AsPolygon ( poKmlGeometry );
poKmlPolygon->set_extrude ( nExtrude );
break;
case kmldom::Type_MultiGeometry:
poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry );
nGeom = poKmlMultiGeometry->get_geometry_array_size ( );
for ( i = 0; i < nGeom; i++ ) {
ogr2extrude_rec ( nExtrude,
poKmlMultiGeometry->
get_geometry_array_at ( i ) );
}
break;
default:
break;
}
}
void ogr2tessellate_rec (
int nTessellate,
GeometryPtr poKmlGeometry )
{
LineStringPtr poKmlLineString;
PolygonPtr poKmlPolygon;
MultiGeometryPtr poKmlMultiGeometry;
size_t nGeom;
size_t i;
switch ( poKmlGeometry->Type ( ) ) {
case kmldom::Type_Point:
break;
case kmldom::Type_LineString:
poKmlLineString = AsLineString ( poKmlGeometry );
poKmlLineString->set_tessellate ( nTessellate );
break;
case kmldom::Type_LinearRing:
break;
case kmldom::Type_Polygon:
poKmlPolygon = AsPolygon ( poKmlGeometry );
poKmlPolygon->set_tessellate ( nTessellate );
break;
case kmldom::Type_MultiGeometry:
poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry );
nGeom = poKmlMultiGeometry->get_geometry_array_size ( );
for ( i = 0; i < nGeom; i++ ) {
ogr2tessellate_rec ( nTessellate,
poKmlMultiGeometry->
get_geometry_array_at ( i ) );
}
break;
default:
break;
}
}
/************************************************************************/
/* OGRLIBKMLSanitizeUTF8String() */
/************************************************************************/
static char* OGRLIBKMLSanitizeUTF8String(const char* pszString)
{
if (!CPLIsUTF8(pszString, -1) &&
CSLTestBoolean(CPLGetConfigOption("OGR_FORCE_ASCII", "YES")))
{
static int bFirstTime = TRUE;
if (bFirstTime)
{
bFirstTime = FALSE;
CPLError(CE_Warning, CPLE_AppDefined,
"%s is not a valid UTF-8 string. Forcing it to ASCII.\n"
"If you still want the original string and change the XML file encoding\n"
"afterwards, you can define OGR_FORCE_ASCII=NO as configuration option.\n"
"This warning won't be issued anymore", pszString);
}
else
{
CPLDebug("OGR", "%s is not a valid UTF-8 string. Forcing it to ASCII",
pszString);
}
return CPLForceToASCII(pszString, -1, '?');
}
else
return CPLStrdup(pszString);
}
/******************************************************************************
function to output ogr fields in kml
args:
poOgrFeat pointer to the feature the field is in
poOgrLayer pointer to the layer the feature is in
poKmlFactory pointer to the libkml dom factory
poKmlPlacemark pointer to the placemark to add to
returns:
nothing
env vars:
LIBKML_TIMESTAMP_FIELD default: OFTDate or OFTDateTime named timestamp
LIBKML_TIMESPAN_BEGIN_FIELD default: OFTDate or OFTDateTime named begin
LIBKML_TIMESPAN_END_FIELD default: OFTDate or OFTDateTime named end
LIBKML_DESCRIPTION_FIELD default: none
LIBKML_NAME_FIELD default: OFTString field named name
******************************************************************************/
void field2kml (
OGRFeature * poOgrFeat,
OGRLIBKMLLayer * poOgrLayer,
KmlFactory * poKmlFactory,
PlacemarkPtr poKmlPlacemark )
{
int i;
SchemaDataPtr poKmlSchemaData = poKmlFactory->CreateSchemaData ( );
SchemaPtr poKmlSchema = poOgrLayer->GetKmlSchema ( );
/***** set the url to the schema *****/
if ( poKmlSchema && poKmlSchema->has_id ( ) ) {
std::string oKmlSchemaID = poKmlSchema->get_id ( );
std::string oKmlSchemaURL = "#";
oKmlSchemaURL.append ( oKmlSchemaID );
poKmlSchemaData->set_schemaurl ( oKmlSchemaURL );
}
/***** get the field config *****/
struct fieldconfig oFC;
get_fieldconfig( &oFC );
TimeSpanPtr poKmlTimeSpan = NULL;
int nFields = poOgrFeat->GetFieldCount ( );
int iSkip1 = -1;
int iSkip2 = -1;
for ( i = 0; i < nFields; i++ ) {
/***** if the field is set to skip, do so *****/
if ( i == iSkip1 || i == iSkip2 )
continue;
/***** if the field isn't set just bail now *****/
if ( !poOgrFeat->IsFieldSet ( i ) )
continue;
OGRFieldDefn *poOgrFieldDef = poOgrFeat->GetFieldDefnRef ( i );
OGRFieldType type = poOgrFieldDef->GetType ( );
const char *name = poOgrFieldDef->GetNameRef ( );
SimpleDataPtr poKmlSimpleData = NULL;
int year,
month,
day,
hour,
min,
sec,
tz;
switch ( type ) {
case OFTString: // String of ASCII chars
{
char* pszUTF8String = OGRLIBKMLSanitizeUTF8String(
poOgrFeat->GetFieldAsString ( i ));
if( pszUTF8String[0] == '\0' )
{
CPLFree( pszUTF8String );
continue;
}
/***** name *****/
if ( EQUAL ( name, oFC.namefield ) ) {
poKmlPlacemark->set_name ( pszUTF8String );
CPLFree( pszUTF8String );
continue;
}
/***** description *****/
else if ( EQUAL ( name, oFC.descfield ) ) {
poKmlPlacemark->set_description ( pszUTF8String );
CPLFree( pszUTF8String );
continue;
}
/***** altitudemode *****/
else if ( EQUAL ( name, oFC.altitudeModefield ) ) {
const char *pszAltitudeMode = pszUTF8String ;
int isGX = FALSE;
int iAltitudeMode = kmldom::ALTITUDEMODE_CLAMPTOGROUND;
if ( EQUAL ( pszAltitudeMode, "clampToGround" ) )
iAltitudeMode = kmldom::ALTITUDEMODE_CLAMPTOGROUND;
else if ( EQUAL ( pszAltitudeMode, "relativeToGround" ) )
iAltitudeMode = kmldom::ALTITUDEMODE_RELATIVETOGROUND;
else if ( EQUAL ( pszAltitudeMode, "absolute" ) )
iAltitudeMode = kmldom::ALTITUDEMODE_ABSOLUTE;
else if ( EQUAL ( pszAltitudeMode, "relativeToSeaFloor" ) ) {
iAltitudeMode =
kmldom::GX_ALTITUDEMODE_RELATIVETOSEAFLOOR;
isGX = TRUE;
}
else if ( EQUAL ( pszAltitudeMode, "clampToSeaFloor" ) ) {
iAltitudeMode =
kmldom::GX_ALTITUDEMODE_CLAMPTOSEAFLOOR;
isGX = TRUE;
}
if ( poKmlPlacemark->has_geometry ( ) ) {
GeometryPtr poKmlGeometry =
poKmlPlacemark->get_geometry ( );
ogr2altitudemode_rec ( poKmlGeometry, iAltitudeMode,
isGX );
}
CPLFree( pszUTF8String );
continue;
}
/***** timestamp *****/
else if ( EQUAL ( name, oFC.tsfield ) ) {
TimeStampPtr poKmlTimeStamp =
poKmlFactory->CreateTimeStamp ( );
poKmlTimeStamp->set_when ( pszUTF8String );
poKmlPlacemark->set_timeprimitive ( poKmlTimeStamp );
CPLFree( pszUTF8String );
continue;
}
/***** begin *****/
if ( EQUAL ( name, oFC.beginfield ) ) {
if ( !poKmlTimeSpan ) {
poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( );
poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan );
}
poKmlTimeSpan->set_begin ( pszUTF8String );
CPLFree( pszUTF8String );
continue;
}
/***** end *****/
else if ( EQUAL ( name, oFC.endfield ) ) {
if ( !poKmlTimeSpan ) {
poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( );
poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan );
}
poKmlTimeSpan->set_end ( pszUTF8String );
CPLFree( pszUTF8String );
continue;
}
/***** icon *****/
else if ( EQUAL ( name, oFC.iconfield ) ) {
CPLFree( pszUTF8String );
continue;
}
/***** other *****/
poKmlSimpleData = poKmlFactory->CreateSimpleData ( );
poKmlSimpleData->set_name ( name );
poKmlSimpleData->set_text ( pszUTF8String );
CPLFree( pszUTF8String );
break;
}
case OFTDate: // Date
{
poOgrFeat->GetFieldAsDateTime ( i, &year, &month, &day,
&hour, &min, &sec, &tz );
int iTimeField;
for ( iTimeField = i + 1; iTimeField < nFields; iTimeField++ ) {
if ( iTimeField == iSkip1 || iTimeField == iSkip2 )
continue;
OGRFieldDefn *poOgrFieldDef2 =
poOgrFeat->GetFieldDefnRef ( i );
OGRFieldType type2 = poOgrFieldDef2->GetType ( );
const char *name2 = poOgrFieldDef2->GetNameRef ( );
if ( EQUAL ( name2, name ) && type2 == OFTTime &&
( EQUAL ( name, oFC.tsfield ) ||
EQUAL ( name, oFC.beginfield ) ||
EQUAL ( name, oFC.endfield ) ) ) {
int year2,
month2,
day2,
hour2,
min2,
sec2,
tz2;
poOgrFeat->GetFieldAsDateTime ( iTimeField, &year2,
&month2, &day2, &hour2,
&min2, &sec2, &tz2 );
hour = hour2;
min = min2;
sec = sec2;
tz = tz2;
if ( 0 > iSkip1 )
iSkip1 = iTimeField;
else
iSkip2 = iTimeField;
}
}
goto Do_DateTime;
}
case OFTTime: // Time
{
poOgrFeat->GetFieldAsDateTime ( i, &year, &month, &day,
&hour, &min, &sec, &tz );
int iTimeField;
for ( iTimeField = i + 1; iTimeField < nFields; iTimeField++ ) {
if ( iTimeField == iSkip1 || iTimeField == iSkip2 )
continue;
OGRFieldDefn *poOgrFieldDef2 =
poOgrFeat->GetFieldDefnRef ( i );
OGRFieldType type2 = poOgrFieldDef2->GetType ( );
const char *name2 = poOgrFieldDef2->GetNameRef ( );
if ( EQUAL ( name2, name ) && type2 == OFTTime &&
( EQUAL ( name, oFC.tsfield ) ||
EQUAL ( name, oFC.beginfield ) ||
EQUAL ( name, oFC.endfield ) ) ) {
int year2,
month2,
day2,
hour2,
min2,
sec2,
tz2;
poOgrFeat->GetFieldAsDateTime ( iTimeField, &year2,
&month2, &day2, &hour2,
&min2, &sec2, &tz2 );
year = year2;
month = month2;
day = day2;
if ( 0 > iSkip1 )
iSkip1 = iTimeField;
else
iSkip2 = iTimeField;
}
}
goto Do_DateTime;
}
case OFTDateTime: // Date and Time
{
poOgrFeat->GetFieldAsDateTime ( i, &year, &month, &day,
&hour, &min, &sec, &tz );
Do_DateTime:
/***** timestamp *****/
if ( EQUAL ( name, oFC.tsfield ) ) {
char *timebuf = OGRGetXMLDateTime ( year, month, day, hour,
min, sec, tz );
TimeStampPtr poKmlTimeStamp =
poKmlFactory->CreateTimeStamp ( );
poKmlTimeStamp->set_when ( timebuf );
poKmlPlacemark->set_timeprimitive ( poKmlTimeStamp );
CPLFree( timebuf );
continue;
}
/***** begin *****/
if ( EQUAL ( name, oFC.beginfield ) ) {
char *timebuf = OGRGetXMLDateTime ( year, month, day, hour,
min, sec, tz );
if ( !poKmlTimeSpan ) {
poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( );
poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan );
}
poKmlTimeSpan->set_begin ( timebuf );
CPLFree( timebuf );
continue;
}
/***** end *****/
else if ( EQUAL ( name, oFC.endfield ) ) {
char *timebuf = OGRGetXMLDateTime ( year, month, day, hour,
min, sec, tz );
if ( !poKmlTimeSpan ) {
poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( );
poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan );
}
poKmlTimeSpan->set_end ( timebuf );
CPLFree( timebuf );
continue;
}
/***** other *****/
poKmlSimpleData = poKmlFactory->CreateSimpleData ( );
poKmlSimpleData->set_name ( name );
poKmlSimpleData->set_text ( poOgrFeat->
GetFieldAsString ( i ) );
break;
}
case OFTInteger: // Simple 32bit integer
/***** extrude *****/
if ( EQUAL ( name, oFC.extrudefield ) ) {
if ( poKmlPlacemark->has_geometry ( )
&& -1 < poOgrFeat->GetFieldAsInteger ( i ) ) {
GeometryPtr poKmlGeometry =
poKmlPlacemark->get_geometry ( );
ogr2extrude_rec ( poOgrFeat->GetFieldAsInteger ( i ),
poKmlGeometry );
}
continue;
}
/***** tessellate *****/
if ( EQUAL ( name, oFC.tessellatefield ) ) {
if ( poKmlPlacemark->has_geometry ( )
&& -1 < poOgrFeat->GetFieldAsInteger ( i ) ) {
GeometryPtr poKmlGeometry =
poKmlPlacemark->get_geometry ( );
ogr2tessellate_rec ( poOgrFeat->GetFieldAsInteger ( i ),
poKmlGeometry );
}
continue;
}
/***** visibility *****/
if ( EQUAL ( name, oFC.visibilityfield ) ) {
if ( -1 < poOgrFeat->GetFieldAsInteger ( i ) )
poKmlPlacemark->set_visibility ( poOgrFeat->
GetFieldAsInteger ( i ) );
continue;
}
/***** icon *****/
else if ( EQUAL ( name, oFC.drawOrderfield ) ) {
continue;
}
/***** other *****/
poKmlSimpleData = poKmlFactory->CreateSimpleData ( );
poKmlSimpleData->set_name ( name );
poKmlSimpleData->set_text ( poOgrFeat->GetFieldAsString ( i ) );
break;
case OFTReal: // Double Precision floating point
{
poKmlSimpleData = poKmlFactory->CreateSimpleData ( );
poKmlSimpleData->set_name ( name );
char* pszStr = CPLStrdup( poOgrFeat->GetFieldAsString ( i ) );
/* Use point as decimal separator */
char* pszComma = strchr(pszStr, ',');
if (pszComma)
*pszComma = '.';
poKmlSimpleData->set_text ( pszStr );
CPLFree(pszStr);
break;
}
case OFTStringList: // Array of strings
case OFTIntegerList: // List of 32bit integers
case OFTRealList: // List of doubles
case OFTBinary: // Raw Binary data
case OFTWideStringList: // deprecated
default:
/***** other *****/
poKmlSimpleData = poKmlFactory->CreateSimpleData ( );
poKmlSimpleData->set_name ( name );
poKmlSimpleData->set_text ( poOgrFeat->GetFieldAsString ( i ) );
break;
}
poKmlSchemaData->add_simpledata ( poKmlSimpleData );
}
/***** dont add it to the placemark unless there is data *****/
if ( poKmlSchemaData->get_simpledata_array_size ( ) > 0 ) {
ExtendedDataPtr poKmlExtendedData =
poKmlFactory->CreateExtendedData ( );
poKmlExtendedData->add_schemadata ( poKmlSchemaData );
poKmlPlacemark->set_extendeddata ( poKmlExtendedData );
}
return;
}
/******************************************************************************
recursive function to read altitude mode from the geometry
******************************************************************************/
int kml2altitudemode_rec (
GeometryPtr poKmlGeometry,
int *pnAltitudeMode,
int *pbIsGX )
{
PointPtr poKmlPoint;
LineStringPtr poKmlLineString;
PolygonPtr poKmlPolygon;
MultiGeometryPtr poKmlMultiGeometry;
size_t nGeom;
size_t i;
switch ( poKmlGeometry->Type ( ) ) {
case kmldom::Type_Point:
poKmlPoint = AsPoint ( poKmlGeometry );
if ( poKmlPoint->has_altitudemode ( ) ) {
*pnAltitudeMode = poKmlPoint->get_altitudemode ( );
return TRUE;
}
else if ( poKmlPoint->has_gx_altitudemode ( ) ) {
*pnAltitudeMode = poKmlPoint->get_gx_altitudemode ( );
*pbIsGX = TRUE;
return TRUE;
}
break;
case kmldom::Type_LineString:
poKmlLineString = AsLineString ( poKmlGeometry );
if ( poKmlLineString->has_altitudemode ( ) ) {
*pnAltitudeMode = poKmlLineString->get_altitudemode ( );
return TRUE;
}
else if ( poKmlLineString->has_gx_altitudemode ( ) ) {
*pnAltitudeMode = poKmlLineString->get_gx_altitudemode ( );
*pbIsGX = TRUE;
return TRUE;
}
break;
case kmldom::Type_LinearRing:
break;
case kmldom::Type_Polygon:
poKmlPolygon = AsPolygon ( poKmlGeometry );
if ( poKmlPolygon->has_altitudemode ( ) ) {
*pnAltitudeMode = poKmlPolygon->get_altitudemode ( );
return TRUE;
}
else if ( poKmlPolygon->has_gx_altitudemode ( ) ) {
*pnAltitudeMode = poKmlPolygon->get_gx_altitudemode ( );
*pbIsGX = TRUE;
return TRUE;
}
break;
case kmldom::Type_MultiGeometry:
poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry );
nGeom = poKmlMultiGeometry->get_geometry_array_size ( );
for ( i = 0; i < nGeom; i++ ) {
if ( kml2altitudemode_rec ( poKmlMultiGeometry->
get_geometry_array_at ( i ),
pnAltitudeMode, pbIsGX ) )
return TRUE;
}
break;
default:
break;
}
return FALSE;
}
/******************************************************************************
recursive function to read extrude from the geometry
******************************************************************************/
int kml2extrude_rec (
GeometryPtr poKmlGeometry,
int *pnExtrude )
{
PointPtr poKmlPoint;
LineStringPtr poKmlLineString;
PolygonPtr poKmlPolygon;
MultiGeometryPtr poKmlMultiGeometry;
size_t nGeom;
size_t i;
switch ( poKmlGeometry->Type ( ) ) {
case kmldom::Type_Point:
poKmlPoint = AsPoint ( poKmlGeometry );
if ( poKmlPoint->has_extrude ( ) ) {
*pnExtrude = poKmlPoint->get_extrude ( );
return TRUE;
}
break;
case kmldom::Type_LineString:
poKmlLineString = AsLineString ( poKmlGeometry );
if ( poKmlLineString->has_extrude ( ) ) {
*pnExtrude = poKmlLineString->get_extrude ( );
return TRUE;
}
break;
case kmldom::Type_LinearRing:
break;
case kmldom::Type_Polygon:
poKmlPolygon = AsPolygon ( poKmlGeometry );
if ( poKmlPolygon->has_extrude ( ) ) {
*pnExtrude = poKmlPolygon->get_extrude ( );
return TRUE;
}
break;
case kmldom::Type_MultiGeometry:
poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry );
nGeom = poKmlMultiGeometry->get_geometry_array_size ( );
for ( i = 0; i < nGeom; i++ ) {
if ( kml2extrude_rec ( poKmlMultiGeometry->
get_geometry_array_at ( i ), pnExtrude ) )
return TRUE;
}
break;
default:
break;
}
return FALSE;
}
/******************************************************************************
recursive function to read tessellate from the geometry
******************************************************************************/
int kml2tessellate_rec (
GeometryPtr poKmlGeometry,
int *pnTessellate )
{
LineStringPtr poKmlLineString;
PolygonPtr poKmlPolygon;
MultiGeometryPtr poKmlMultiGeometry;
size_t nGeom;
size_t i;
switch ( poKmlGeometry->Type ( ) ) {
case kmldom::Type_Point:
break;
case kmldom::Type_LineString:
poKmlLineString = AsLineString ( poKmlGeometry );
if ( poKmlLineString->has_tessellate ( ) ) {
*pnTessellate = poKmlLineString->get_tessellate ( );
return TRUE;
}
break;
case kmldom::Type_LinearRing:
break;
case kmldom::Type_Polygon:
poKmlPolygon = AsPolygon ( poKmlGeometry );
if ( poKmlPolygon->has_tessellate ( ) ) {
*pnTessellate = poKmlPolygon->get_tessellate ( );
return TRUE;
}
break;
case kmldom::Type_MultiGeometry:
poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry );
nGeom = poKmlMultiGeometry->get_geometry_array_size ( );
for ( i = 0; i < nGeom; i++ ) {
if ( kml2tessellate_rec ( poKmlMultiGeometry->
get_geometry_array_at ( i ),
pnTessellate ) )
return TRUE;
}
break;
default:
break;
}
return FALSE;
}
/******************************************************************************
function to read kml into ogr fields
******************************************************************************/
void kml2field (
OGRFeature * poOgrFeat,
FeaturePtr poKmlFeature )
{
/***** get the field config *****/
struct fieldconfig oFC;
get_fieldconfig( &oFC );
/***** name *****/
if ( poKmlFeature->has_name ( ) ) {
const std::string oKmlName = poKmlFeature->get_name ( );
int iField = poOgrFeat->GetFieldIndex ( oFC.namefield );
if ( iField > -1 )
poOgrFeat->SetField ( iField, oKmlName.c_str ( ) );
}
/***** description *****/
if ( poKmlFeature->has_description ( ) ) {
const std::string oKmlDesc = poKmlFeature->get_description ( );
int iField = poOgrFeat->GetFieldIndex ( oFC.descfield );
if ( iField > -1 )
poOgrFeat->SetField ( iField, oKmlDesc.c_str ( ) );
}
if ( poKmlFeature->has_timeprimitive ( ) ) {
TimePrimitivePtr poKmlTimePrimitive =
poKmlFeature->get_timeprimitive ( );
/***** timestamp *****/
if ( poKmlTimePrimitive->IsA ( kmldom::Type_TimeStamp ) ) {
TimeStampPtr poKmlTimeStamp = AsTimeStamp ( poKmlTimePrimitive );
if ( poKmlTimeStamp->has_when ( ) ) {
const std::string oKmlWhen = poKmlTimeStamp->get_when ( );
int iField = poOgrFeat->GetFieldIndex ( oFC.tsfield );
if ( iField > -1 ) {
int nYear,
nMonth,
nDay,
nHour,
nMinute,
nTZ;
float fSecond;
if ( OGRParseXMLDateTime
( oKmlWhen.c_str ( ), &nYear, &nMonth, &nDay, &nHour,
&nMinute, &fSecond, &nTZ ) )
poOgrFeat->SetField ( iField, nYear, nMonth, nDay,
nHour, nMinute, ( int )fSecond,
nTZ );
}
}
}
/***** timespan *****/
if ( poKmlTimePrimitive->IsA ( kmldom::Type_TimeSpan ) ) {
TimeSpanPtr poKmlTimeSpan = AsTimeSpan ( poKmlTimePrimitive );
/***** begin *****/
if ( poKmlTimeSpan->has_begin ( ) ) {
const std::string oKmlWhen = poKmlTimeSpan->get_begin ( );
int iField = poOgrFeat->GetFieldIndex ( oFC.beginfield );
if ( iField > -1 ) {
int nYear,
nMonth,
nDay,
nHour,
nMinute,
nTZ;
float fSecond;
if ( OGRParseXMLDateTime
( oKmlWhen.c_str ( ), &nYear, &nMonth, &nDay, &nHour,
&nMinute, &fSecond, &nTZ ) )
poOgrFeat->SetField ( iField, nYear, nMonth, nDay,
nHour, nMinute, ( int )fSecond,
nTZ );
}
}
/***** end *****/
if ( poKmlTimeSpan->has_end ( ) ) {
const std::string oKmlWhen = poKmlTimeSpan->get_end ( );
int iField = poOgrFeat->GetFieldIndex ( oFC.endfield );
if ( iField > -1 ) {
int nYear,
nMonth,
nDay,
nHour,
nMinute,
nTZ;
float fSecond;
if ( OGRParseXMLDateTime
( oKmlWhen.c_str ( ), &nYear, &nMonth, &nDay, &nHour,
&nMinute, &fSecond, &nTZ ) )
poOgrFeat->SetField ( iField, nYear, nMonth, nDay,
nHour, nMinute, ( int )fSecond,
nTZ );
}
}
}
}
/***** placemark *****/
PlacemarkPtr poKmlPlacemark = AsPlacemark ( poKmlFeature );
GroundOverlayPtr poKmlGroundOverlay = AsGroundOverlay ( poKmlFeature );
if ( poKmlPlacemark && poKmlPlacemark->has_geometry ( ) ) {
GeometryPtr poKmlGeometry = poKmlPlacemark->get_geometry ( );
/***** altitudeMode *****/
int bIsGX = FALSE;
int nAltitudeMode = -1;
int iField = poOgrFeat->GetFieldIndex ( oFC.altitudeModefield );
if ( iField > -1 ) {
if ( kml2altitudemode_rec ( poKmlGeometry,
&nAltitudeMode, &bIsGX ) ) {
if ( !bIsGX ) {
switch ( nAltitudeMode ) {
case kmldom::ALTITUDEMODE_CLAMPTOGROUND:
poOgrFeat->SetField ( iField, "clampToGround" );
break;
case kmldom::ALTITUDEMODE_RELATIVETOGROUND:
poOgrFeat->SetField ( iField, "relativeToGround" );
break;
case kmldom::ALTITUDEMODE_ABSOLUTE:
poOgrFeat->SetField ( iField, "absolute" );
break;
}
}
else {
switch ( nAltitudeMode ) {
case kmldom::GX_ALTITUDEMODE_RELATIVETOSEAFLOOR:
poOgrFeat->SetField ( iField, "relativeToSeaFloor" );
break;
case kmldom::GX_ALTITUDEMODE_CLAMPTOSEAFLOOR:
poOgrFeat->SetField ( iField, "clampToSeaFloor" );
break;
}
}
}
}
/***** tessellate *****/
int nTessellate = -1;
kml2tessellate_rec ( poKmlGeometry, &nTessellate );
iField = poOgrFeat->GetFieldIndex ( oFC.tessellatefield );
if ( iField > -1 )
poOgrFeat->SetField ( iField, nTessellate );
/***** extrude *****/
int nExtrude = -1;
kml2extrude_rec ( poKmlGeometry, &nExtrude );
iField = poOgrFeat->GetFieldIndex ( oFC.extrudefield );
if ( iField > -1 )
poOgrFeat->SetField ( iField, nExtrude );
}
/***** ground overlay *****/
else if ( poKmlGroundOverlay ) {
/***** icon *****/
int iField = poOgrFeat->GetFieldIndex ( oFC.iconfield );
if ( iField > -1 ) {
if ( poKmlGroundOverlay->has_icon ( ) ) {
IconPtr icon = poKmlGroundOverlay->get_icon ( );
if ( icon->has_href ( ) ) {
poOgrFeat->SetField ( iField, icon->get_href ( ).c_str ( ) );
}
}
}
/***** drawOrder *****/
iField = poOgrFeat->GetFieldIndex ( oFC.drawOrderfield );
if ( iField > -1 ) {
if ( poKmlGroundOverlay->has_draworder ( ) ) {
poOgrFeat->SetField ( iField, poKmlGroundOverlay->get_draworder ( ) );
}
}
/***** altitudeMode *****/
iField = poOgrFeat->GetFieldIndex ( oFC.altitudeModefield );
if ( iField > -1 ) {
if ( poKmlGroundOverlay->has_altitudemode ( ) ) {
switch ( poKmlGroundOverlay->get_altitudemode ( ) ) {
case kmldom::ALTITUDEMODE_CLAMPTOGROUND:
poOgrFeat->SetField ( iField, "clampToGround" );
break;
case kmldom::ALTITUDEMODE_RELATIVETOGROUND:
poOgrFeat->SetField ( iField, "relativeToGround" );
break;
case kmldom::ALTITUDEMODE_ABSOLUTE:
poOgrFeat->SetField ( iField, "absolute" );
break;
}
} else if ( poKmlGroundOverlay->has_gx_altitudemode ( ) ) {
switch ( poKmlGroundOverlay->get_gx_altitudemode ( ) ) {
case kmldom::GX_ALTITUDEMODE_RELATIVETOSEAFLOOR:
poOgrFeat->SetField ( iField, "relativeToSeaFloor" );
break;
case kmldom::GX_ALTITUDEMODE_CLAMPTOSEAFLOOR:
poOgrFeat->SetField ( iField, "clampToSeaFloor" );
break;
}
}
}
}
/***** visibility *****/
int nVisibility = -1;
if ( poKmlFeature->has_visibility ( ) )
nVisibility = poKmlFeature->get_visibility ( );
int iField = poOgrFeat->GetFieldIndex ( oFC.visibilityfield );
if ( iField > -1 )
poOgrFeat->SetField ( iField, nVisibility );
ExtendedDataPtr poKmlExtendedData = NULL;
if ( poKmlFeature->has_extendeddata ( ) ) {
poKmlExtendedData = poKmlFeature->get_extendeddata ( );
/***** loop over the schemadata_arrays *****/
size_t nSchemaData = poKmlExtendedData->get_schemadata_array_size ( );
size_t iSchemaData;
for ( iSchemaData = 0; iSchemaData < nSchemaData; iSchemaData++ ) {
SchemaDataPtr poKmlSchemaData =
poKmlExtendedData->get_schemadata_array_at ( iSchemaData );
/***** loop over the simpledata array *****/
size_t nSimpleData =
poKmlSchemaData->get_simpledata_array_size ( );
size_t iSimpleData;
for ( iSimpleData = 0; iSimpleData < nSimpleData; iSimpleData++ ) {
SimpleDataPtr poKmlSimpleData =
poKmlSchemaData->get_simpledata_array_at ( iSimpleData );
/***** find the field index *****/
int iField = -1;
if ( poKmlSimpleData->has_name ( ) ) {
const string oName = poKmlSimpleData->get_name ( );
const char *pszName = oName.c_str ( );
iField = poOgrFeat->GetFieldIndex ( pszName );
}
/***** if it has trxt set the field *****/
if ( iField > -1 && poKmlSimpleData->has_text ( ) ) {
string oText = poKmlSimpleData->get_text ( );
/* SerializePretty() adds a new line before the data */
/* ands trailing spaces. I believe this is wrong */
/* as it breaks round-tripping */
/* Trim trailing spaces */
while (oText.size() != 0 && oText[oText.size()-1] == ' ')
oText.resize(oText.size()-1);
/* Skip leading newline and spaces */
const char* pszText = oText.c_str ( );
if (pszText[0] == '\n')
pszText ++;
while (pszText[0] == ' ')
pszText ++;
poOgrFeat->SetField ( iField, pszText );
}
}
}
if (nSchemaData == 0 && poKmlExtendedData->get_data_array_size() > 0 )
{
int bLaunderFieldNames =
CSLTestBoolean(CPLGetConfigOption("LIBKML_LAUNDER_FIELD_NAMES", "YES"));
size_t nDataArraySize = poKmlExtendedData->get_data_array_size();
for(size_t i=0; i < nDataArraySize; i++)
{
const DataPtr& data = poKmlExtendedData->get_data_array_at(i);
if (data->has_name() && data->has_value())
{
CPLString osName = data->get_name();
if (bLaunderFieldNames)
osName = OGRLIBKMLLayer::LaunderFieldNames(osName);
int iField = poOgrFeat->GetFieldIndex ( osName );
if (iField >= 0)
{
poOgrFeat->SetField ( iField, data->get_value().c_str() );
}
}
}
}
}
}
/******************************************************************************
function create a simplefield from a FieldDefn
******************************************************************************/
SimpleFieldPtr FieldDef2kml (
OGRFieldDefn * poOgrFieldDef,
KmlFactory * poKmlFactory )
{
SimpleFieldPtr poKmlSimpleField = poKmlFactory->CreateSimpleField ( );
const char *pszFieldName = poOgrFieldDef->GetNameRef ( );
poKmlSimpleField->set_name ( pszFieldName );
/***** get the field config *****/
struct fieldconfig oFC;
get_fieldconfig( &oFC );
SimpleDataPtr poKmlSimpleData = NULL;
switch ( poOgrFieldDef->GetType ( ) ) {
case OFTInteger:
case OFTIntegerList:
if ( EQUAL ( pszFieldName, oFC.tessellatefield ) ||
EQUAL ( pszFieldName, oFC.extrudefield ) ||
EQUAL ( pszFieldName, oFC.visibilityfield ) ||
EQUAL ( pszFieldName, oFC.drawOrderfield ) )
break;
poKmlSimpleField->set_type ( "int" );
return poKmlSimpleField;
case OFTReal:
case OFTRealList:
poKmlSimpleField->set_type ( "float" );
return poKmlSimpleField;
case OFTBinary:
poKmlSimpleField->set_type ( "bool" );
return poKmlSimpleField;
case OFTString:
case OFTStringList:
if ( EQUAL ( pszFieldName, oFC.namefield ) ||
EQUAL ( pszFieldName, oFC.descfield ) ||
EQUAL ( pszFieldName, oFC.altitudeModefield ) ||
EQUAL ( pszFieldName, oFC.iconfield ) )
break;
poKmlSimpleField->set_type ( "string" );
return poKmlSimpleField;
/***** kml has these types but as timestamp/timespan *****/
case OFTDate:
case OFTTime:
case OFTDateTime:
if ( EQUAL ( pszFieldName, oFC.tsfield )
|| EQUAL ( pszFieldName, oFC.beginfield )
|| EQUAL ( pszFieldName, oFC.endfield ) )
break;
default:
poKmlSimpleField->set_type ( "string" );
return poKmlSimpleField;
}
return NULL;
}
/******************************************************************************
function to add the simpleFields in a schema to a featuredefn
******************************************************************************/
void kml2FeatureDef (
SchemaPtr poKmlSchema,
OGRFeatureDefn * poOgrFeatureDefn )
{
size_t nSimpleFields = poKmlSchema->get_simplefield_array_size ( );
size_t iSimpleField;
for ( iSimpleField = 0; iSimpleField < nSimpleFields; iSimpleField++ ) {
SimpleFieldPtr poKmlSimpleField =
poKmlSchema->get_simplefield_array_at ( iSimpleField );
const char *pszType = "string";
string osName = "Unknown";
string osType;
if ( poKmlSimpleField->has_type ( ) ) {
osType = poKmlSimpleField->get_type ( );
pszType = osType.c_str ( );
}
/* FIXME? We cannot set displayname as the field name because in kml2field() we make the */
/* lookup on fields based on their name. We would need some map if we really */
/* want to use displayname, but that might not be a good idea because displayname */
/* may have HTML formatting, which makes it impractical when converting to other */
/* drivers or to make requests */
/* Example: http://www.jasonbirch.com/files/newt_combined.kml */
/*if ( poKmlSimpleField->has_displayname ( ) ) {
osName = poKmlSimpleField->get_displayname ( );
}
else*/ if ( poKmlSimpleField->has_name ( ) ) {
osName = poKmlSimpleField->get_name ( );
}
if ( EQUAL ( pszType, "bool" ) ||
EQUAL ( pszType, "int" ) ||
EQUAL ( pszType, "short" ) ||
EQUAL ( pszType, "ushort" ) ) {
OGRFieldDefn oOgrFieldName ( osName.c_str(), OFTInteger );
poOgrFeatureDefn->AddFieldDefn ( &oOgrFieldName );
}
else if ( EQUAL ( pszType, "float" ) ||
EQUAL ( pszType, "double" ) ||
/* a too big uint wouldn't fit in a int, so we map it to OFTReal for now ... */
EQUAL ( pszType, "uint" ) ) {
OGRFieldDefn oOgrFieldName ( osName.c_str(), OFTReal );
poOgrFeatureDefn->AddFieldDefn ( &oOgrFieldName );
}
else /* string, or any other unrecognized type */
{
OGRFieldDefn oOgrFieldName ( osName.c_str(), OFTString );
poOgrFeatureDefn->AddFieldDefn ( &oOgrFieldName );
}
}
return;
}
/*******************************************************************************
* function to fetch the field config options
*
*******************************************************************************/
void get_fieldconfig( struct fieldconfig *oFC) {
oFC->namefield = CPLGetConfigOption ( "LIBKML_NAME_FIELD",
"Name" );
oFC->descfield = CPLGetConfigOption ( "LIBKML_DESCRIPTION_FIELD",
"description" );
oFC->tsfield = CPLGetConfigOption ( "LIBKML_TIMESTAMP_FIELD",
"timestamp" );
oFC->beginfield = CPLGetConfigOption ( "LIBKML_BEGIN_FIELD",
"begin" );
oFC->endfield = CPLGetConfigOption ( "LIBKML_END_FIELD",
"end" );
oFC->altitudeModefield = CPLGetConfigOption ( "LIBKML_ALTITUDEMODE_FIELD",
"altitudeMode" );
oFC->tessellatefield = CPLGetConfigOption ( "LIBKML_TESSELLATE_FIELD",
"tessellate" );
oFC->extrudefield = CPLGetConfigOption ( "LIBKML_EXTRUDE_FIELD",
"extrude" );
oFC->visibilityfield = CPLGetConfigOption ( "LIBKML_VISIBILITY_FIELD",
"visibility" );
oFC->drawOrderfield = CPLGetConfigOption ( "LIBKML_DRAWORDER_FIELD",
"drawOrder" );
oFC->iconfield = CPLGetConfigOption ( "LIBKML_ICON_FIELD",
"icon" );
}
| 31.575979 | 99 | 0.482484 | chambbj |
cd83150fc6d12a4b0ed589589c985cd461a0f936 | 2,768 | cpp | C++ | OpenGLExample_21/OpenGLExample_21/src/CreateWindow.cpp | SnowyLake/OpenGL_Learn | ae389cb45992eb90595482e0b4eca41b967e63b3 | [
"MIT"
] | 4 | 2020-11-27T14:20:28.000Z | 2022-03-12T03:11:04.000Z | OpenGLExample_21/OpenGLExample_21/src/CreateWindow.cpp | SnowyLake/OpenGL_Learn | ae389cb45992eb90595482e0b4eca41b967e63b3 | [
"MIT"
] | null | null | null | OpenGLExample_21/OpenGLExample_21/src/CreateWindow.cpp | SnowyLake/OpenGL_Learn | ae389cb45992eb90595482e0b4eca41b967e63b3 | [
"MIT"
] | null | null | null | #include"CreateWindow.h"
//setting
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
//camera
GLCamera camera(glm::vec3(0.0f, 0.0f, 6.0f));
float lastX = SCR_WIDTH / 2.0f;
float lastY = SCR_HEIGHT / 2.0f;
bool firstMouse = true;
//timing
float deltaTime = 0.0f; // time between current frame and last frame
float lastTime = 0.0f;
GLFWwindow* CreateWindow(unsigned int width, unsigned int height, const char* Title)
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef _APPLE_
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif // _APPLE_
//glfw:create window
GLFWwindow* window = glfwCreateWindow(width, height, Title, NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return nullptr;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, FrameBufferSizeCallback);
glfwSetCursorPosCallback(window, MouseCallback);
glfwSetScrollCallback(window, ScrollCallback);
//tell GLFW to capture our mouse
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
//glad
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return nullptr;
}
return window;
}
void ProcessInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
camera.ProcessKeyboard(FORWARD, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
camera.ProcessKeyboard(BACKWARD, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
camera.ProcessKeyboard(LEFT, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
camera.ProcessKeyboard(RIGHT, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
{
camera.ProcessKeyboard(RISE, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_CAPS_LOCK) == GLFW_PRESS)
{
camera.ProcessKeyboard(FALL, deltaTime);
}
}
void FrameBufferSizeCallback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
void MouseCallback(GLFWwindow* window, double xPos, double yPos)
{
if (firstMouse)
{
lastX = xPos;
lastY = yPos;
firstMouse = false;
}
float xoffset = xPos - lastX;
float yoffset = lastY - yPos;
lastX = xPos;
lastY = yPos;
camera.ProcessMouseMovement(xoffset, yoffset);
}
void ScrollCallback(GLFWwindow* window, double xOffset, double yOffset)
{
camera.ProcessMouseScroll(yOffset);
}
| 26.113208 | 85 | 0.717847 | SnowyLake |
cd8344de5018d08c30e74df0f59e0eeaadfa5a1e | 1,841 | cpp | C++ | CG_AUEB_LAB_4/Lab4/Source/SceneGraph/Node.cpp | kvarcg/opengl_course | 9f6613a0e165f44630de553051eb8722387b7ac8 | [
"MIT"
] | null | null | null | CG_AUEB_LAB_4/Lab4/Source/SceneGraph/Node.cpp | kvarcg/opengl_course | 9f6613a0e165f44630de553051eb8722387b7ac8 | [
"MIT"
] | null | null | null | CG_AUEB_LAB_4/Lab4/Source/SceneGraph/Node.cpp | kvarcg/opengl_course | 9f6613a0e165f44630de553051eb8722387b7ac8 | [
"MIT"
] | null | null | null | //----------------------------------------------------//
// //
// File: Node.cpp //
// This scene graph is a basic example for the //
// object relational management of the scene //
// This is the basic node class //
// //
// Author: //
// Kostas Vardis //
// //
// These files are provided as part of the BSc course //
// of Computer Graphics at the Athens University of //
// Economics and Business (AUEB) //
// //
//----------------------------------------------------//
// includes ////////////////////////////////////////
#include "../HelpLib.h" // - Library for including GL libraries, checking for OpenGL errors, writing to Output window, etc.
#include "Node.h" // - Header file for the Node class
// defines /////////////////////////////////////////
// Constructor
Node::Node(const char* name):
m_name(name),
m_parent(nullptr)
{
}
// Destructor
Node::~Node()
{
}
void Node::SetName(const char * str)
{
if (!str)
return;
m_name = std::string(str);
}
void Node::Init()
{
}
void Node::Update()
{
}
void Node::Draw()
{
}
const char * Node::GetName()
{
return m_name.c_str();
}
glm::mat4x4 Node::GetTransform()
{
if (m_parent)
return m_parent->GetTransform();
else
return glm::mat4x4(1);
}
glm::vec3 Node::GetWorldPosition()
{
glm::vec4 p4(0,0,0,1);
glm::vec4 result = GetTransform()*p4;
return glm::vec3(result/result.w);
}
// eof ///////////////////////////////// class Node | 22.728395 | 123 | 0.415535 | kvarcg |
cd85fac14b7d699039f12d0621ae3469ae582e2d | 4,632 | cpp | C++ | scout_webots_sim/src/scout_webots_runner.cpp | westonrobot/scout_navigation | 7e8c79cb41205b98a33a81e87bdea6bd6411bca3 | [
"BSD-3-Clause"
] | 14 | 2020-09-02T14:05:14.000Z | 2021-08-31T02:19:37.000Z | scout_webots_sim/src/scout_webots_runner.cpp | westonrobot/scout_navigation | 7e8c79cb41205b98a33a81e87bdea6bd6411bca3 | [
"BSD-3-Clause"
] | 4 | 2020-09-18T12:50:15.000Z | 2021-10-16T13:06:16.000Z | scout_webots_sim/src/scout_webots_runner.cpp | westonrobot/scout_navigation | 7e8c79cb41205b98a33a81e87bdea6bd6411bca3 | [
"BSD-3-Clause"
] | 4 | 2020-10-16T06:31:28.000Z | 2021-08-31T02:21:50.000Z | /*
* scout_webots_runner.cpp
*
* Created on: Sep 18, 2020 11:13
* Description:
*
* Copyright (c) 2020 Ruixiang Du (rdu)
*/
#include <signal.h>
#include <webots_ros/set_float.h>
#include "scout_base/scout_messenger.hpp"
#include "scout_webots_sim/scout_webots_runner.hpp"
#include "scout_webots_sim/scout_webots_interface.hpp"
namespace westonrobot {
ScoutWebotsRunner::ScoutWebotsRunner(ros::NodeHandle *nh, ros::NodeHandle *pnh)
: nh_(nh), pnh_(pnh) {
std::cout << "Creating runner" << std::endl;
}
void ScoutWebotsRunner::AddExtension(
std::shared_ptr<WebotsExtension> extension) {
extensions_.push_back(extension);
}
int ScoutWebotsRunner::Run() {
// get the list of availables controllers
std::string controllerName;
ros::Subscriber name_sub = nh_->subscribe(
"model_name", 100, &ScoutWebotsRunner::ControllerNameCallback, this);
while (controller_count_ == 0 ||
controller_count_ < name_sub.getNumPublishers()) {
ros::spinOnce();
ros::spinOnce();
ros::spinOnce();
}
ros::spinOnce();
// if there is more than one controller available, it let the user choose
if (controller_count_ == 1)
controllerName = controller_list_[0];
else {
int wantedController = 0;
std::cout << "Choose the # of the controller you want to use:\n";
std::cin >> wantedController;
if (1 <= wantedController && wantedController <= controller_count_)
controllerName = controller_list_[wantedController - 1];
else {
ROS_ERROR("Invalid number for controller choice.");
return 1;
}
}
ROS_INFO("Using controller: '%s'", controllerName.c_str());
name_sub.shutdown();
// fetch parameters before connecting to robot
std::string port_name;
std::string odom_frame;
std::string base_frame;
std::string odom_topic_name;
bool is_omni_wheel = false;
bool is_simulated = false;
int sim_rate = 50;
bool is_scout_mini = false;
pnh_->param<std::string>("port_name", port_name, std::string("can0"));
pnh_->param<std::string>("odom_frame", odom_frame, std::string("odom"));
pnh_->param<std::string>("base_frame", base_frame, std::string("base_link"));
pnh_->param<bool>("is_omni_wheel", is_omni_wheel, false);
pnh_->param<bool>("simulated_robot", is_simulated, true);
pnh_->param<int>("control_rate", sim_rate, 50);
pnh_->param<std::string>("odom_topic_name", odom_topic_name,
std::string("odom"));
pnh_->param<bool>("is_scout_mini", is_scout_mini, false);
std::shared_ptr<ScoutWebotsInterface> robot =
std::make_shared<ScoutWebotsInterface>(nh_);
// init robot components
robot->Initialize(controllerName);
if (!extensions_.empty()) {
for (auto &ext : extensions_)
ext->Setup(nh_, controllerName, static_broadcaster_);
}
std::unique_ptr<ScoutMessenger<ScoutWebotsInterface>> messenger =
std::unique_ptr<ScoutMessenger<ScoutWebotsInterface>>(
new ScoutMessenger<ScoutWebotsInterface>(robot, nh_));
messenger->SetOdometryFrame(odom_frame);
messenger->SetBaseFrame(base_frame);
messenger->SetOdometryTopicName(odom_topic_name);
messenger->SetSimulationMode();
messenger->SetupSubscription();
const uint32_t time_step = 1000 / sim_rate;
ROS_INFO(
"Chosen time step: '%d', make sure you set the same time step in Webots \"basicTimeStep\""
"scene",
time_step);
ROS_INFO("Entering ROS main loop...");
// main loop
time_step_client_ = nh_->serviceClient<webots_ros::set_int>(
"/" + controllerName + "/robot/time_step");
time_step_srv_.request.value = time_step;
ros::Rate loop_rate(sim_rate);
ros::AsyncSpinner spinner(2);
spinner.start();
while (ros::ok()) {
if (time_step_client_.call(time_step_srv_) &&
time_step_srv_.response.success) {
messenger->Update();
} else {
static int32_t error_cnt = 0;
ROS_ERROR("Failed to call service time_step for next step.");
if (++error_cnt > 50) break;
}
// ros::spinOnce();
loop_rate.sleep();
}
time_step_srv_.request.value = 0;
time_step_client_.call(time_step_srv_);
spinner.stop();
ros::shutdown();
return 0;
}
void ScoutWebotsRunner::Stop() {
ROS_INFO("User stopped the 'scout_webots_node'.");
time_step_srv_.request.value = 0;
time_step_client_.call(time_step_srv_);
ros::shutdown();
}
void ScoutWebotsRunner::ControllerNameCallback(
const std_msgs::String::ConstPtr &name) {
controller_count_++;
controller_list_.push_back(name->data);
ROS_INFO("Controller #%d: %s.", controller_count_,
controller_list_.back().c_str());
}
} // namespace westonrobot | 31.087248 | 96 | 0.696244 | westonrobot |
cd8a3b795b2ef7c574629303bc5eab4eb050a8af | 18,686 | cc | C++ | library/impl/gviz/gvznode.cc | flyfire100/dot-editor | 76fedb74bfdd51f7740d66befe8f868eb0ecff28 | [
"BSD-3-Clause"
] | 3 | 2016-04-09T18:23:40.000Z | 2021-11-23T10:34:44.000Z | library/impl/gviz/gvznode.cc | flyfire100/dot-editor | 76fedb74bfdd51f7740d66befe8f868eb0ecff28 | [
"BSD-3-Clause"
] | 7 | 2017-03-10T08:19:20.000Z | 2021-10-21T13:02:37.000Z | library/impl/gviz/gvznode.cc | flyfire100/dot-editor | 76fedb74bfdd51f7740d66befe8f868eb0ecff28 | [
"BSD-3-Clause"
] | 2 | 2015-08-21T09:52:26.000Z | 2021-07-22T08:14:08.000Z | /* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
\file gvznode.cc
\date May 2012
\author TNick
\brief Contains the implementation of GVzNode class
*//*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please read COPYING and README files in root folder
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/* INCLUDES ------------------------------------------------------------ */
#ifdef DE_WITH_GRAPHVIZ
#include <dot-editor.h>
#include <QDebug>
#include <QPainter>
#include <QBrush>
#include <QPen>
#include <QFont>
#include <QStyleOptionGraphicsItem>
#include <impl/gviz/gvzedge.h>
#include "gvznode.h"
/* INCLUDES ============================================================ */
//
//
//
//
/* DEFINITIONS --------------------------------------------------------- */
/* DEFINITIONS ========================================================= */
//
//
//
//
/* DATA ---------------------------------------------------------------- */
/* related to NdShape */
const char * GVzNode::shape_names[] = {
"Mcircle",
"Mdiamond",
"Msquare",
"box",
"box3d",
"circle",
"component",
"diamond",
"doublecircle",
"doubleoctagon",
"egg",
"ellipse",
"folder",
"hexagon",
"house",
"invhouse",
"invtrapezium",
"invtriangle",
"none",
"note",
"octagon",
"oval",
"parallelogram",
"pentagon",
"plaintext",
"point",
"polygon",
"rect",
"rectangle",
"septagon",
"square",
"tab",
"trapezium",
"triangle",
"tripleoctagon",
0
};
/* DATA ================================================================ */
//
//
//
//
/* CLASS --------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
GVzNode::GVzNode (
QGraphicsItem * fth_g, Agnode_t * node, GVzNode * parent_n )
: QGraphicsItem( fth_g )
{
setFlags( ItemIsMovable | ItemIsSelectable | ItemIsFocusable);
dot_n_ = node;
fth_ = parent_n;
st_lst_ = STNONE;
updateCachedData();
}
/* ========================================================================= */
/* ------------------------------------------------------------------------- */
GVzNode::~GVzNode ()
{
edg_l_.clear();
}
/* ========================================================================= */
/* ------------------------------------------------------------------------- */
QString GVzNode::label () const
{
if (dot_n_ == NULL)
return QString();
textlabel_t * tl = ND_label (dot_n_);
if (tl == NULL)
return QString();
return tl->text;
}
/* ========================================================================= */
/* ------------------------------------------------------------------------- */
QRectF GVzNode::boundingRect () const
{
qreal penWidth = 1;
qreal w = ND_width( dot_n_ ) * 72;
qreal h = ND_height( dot_n_ ) * 72;
return QRectF(
- ( w / 2 + penWidth / 2 ),
- ( h / 2 + penWidth / 2 ),
w + penWidth,
h + penWidth
);
}
/* ========================================================================= */
/* ------------------------------------------------------------------------- */
void octogonInRect (QRectF & r, QPointF * pts)
{
/* 9 POINTS EXPECTED */
qreal x_3 = r.width() / 3;
qreal y_3 = r.height() / 3;
qreal x_2_3 = x_3 * 2;
qreal y_2_3 = y_3 * 2;
pts[0].setX (r.left() ); pts[0].setY( r.top() + y_3);
pts[1].setX (r.left() + x_3 ); pts[1].setY( r.top());
pts[2].setX (r.left() + x_2_3 ); pts[2].setY( r.top());
pts[3].setX (r.right() ); pts[3].setY( r.top() + y_3);
pts[4].setX (r.right() ); pts[4].setY( r.top() + y_2_3);
pts[5].setX (r.left() + x_2_3 ); pts[5].setY( r.bottom());
pts[6].setX (r.left() + x_3 ); pts[6].setY( r.bottom());
pts[7].setX (r.left() ); pts[7].setY( r.top() + y_2_3);
pts[8] = pts[0];
}
/* ========================================================================= */
#define q_agfindattr(a,b) agfindattr( a, const_cast<char *>( b ) )
/* ------------------------------------------------------------------------- */
void GVzNode::paint(
QPainter * painter, const QStyleOptionGraphicsItem * option,
QWidget * widget )
{
Q_UNUSED (option);
Q_UNUSED (widget);
QPointF pts[16];
QRectF bb2;
qreal a;
if (dot_n_ == NULL)
return;
Agsym_t * atr_clr = q_agfindattr (dot_n_, "color");
Agsym_t * atr_fillclr = q_agfindattr (dot_n_, "fillcolor");
Agsym_t * atr_bgcolor = q_agfindattr (dot_n_, "bgcolor");
Agsym_t * atr_style = q_agfindattr (dot_n_, "style");
// Agsym_t * atr_fontcolor = q_agfindattr (dot_n_, "fontcolor");
// Agsym_t * atr_fontname = q_agfindattr (dot_n_, "fontname");
// Agsym_t * atr_fontsize = q_agfindattr (dot_n_, "fontsize");
// Agsym_t * atr_label = q_agfindattr (dot_n_, "label");
char * vl;
if (atr_clr != NULL){
vl = agxget (dot_n_, atr_clr->index);
painter->setPen (QColor( vl ).toRgb());
}
if (atr_fillclr != NULL){
QBrush brs;
vl = agxget (dot_n_, atr_fillclr->index);
brs.setColor (QColor( vl ));
brs.setStyle (Qt:: SolidPattern);
painter->setBrush (brs);
}
if (atr_bgcolor != NULL){
/* ? where to use this? */
vl = agxget (dot_n_, atr_bgcolor->index);
}
if (atr_style != NULL){
/* ? where to use this? */
vl = agxget (dot_n_, atr_style->index);
}
QRectF bb = boundingRect();
if (isHighlited())
{
painter->setPen (QColor( Qt::red ));
painter->setBrush (QBrush( QColor( 0x00, 0xf5, 0xf5, 0x50 ) ));
}
/* draw based on provided shape */
switch ( shp_ ) {
case SHP_RECT:
case SHP_RECTANGLE:
case SHP_SQUARE:
case SHP_BOX:
painter->drawRect (bb);
break;
case SHP_NONE:
break;
case SHP_MCIRCLE: {
a = bb.height() / 8;
bb2 = bb.adjusted( a, a, -a, -a);
painter->drawEllipse (bb);
painter->drawRect (bb2);
break;}
case SHP_MDIAMOND:
case SHP_MSQUARE: {
painter->drawRect (bb);
pts[0].setX (bb.left() ); pts[0].setY( bb.top()+bb.height()/2);
pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top());
pts[2].setX (bb.right() ); pts[2].setY( pts[0].y());
pts[3].setX (pts[1].x() ); pts[3].setY( bb.bottom());
painter->drawConvexPolygon (&pts[0], 4);
break;}
case SHP_CIRCLE:
case SHP_ELLIPSE:
case SHP_OVAL:
case SHP_EGG:
painter->drawEllipse (bb);
break;
case SHP_DOUBLECIRCLE: {
a = 2;//bb.width() / 10;
bb2 = bb.adjusted( a, a, -a, -a);
painter->drawEllipse (bb);
painter->drawEllipse (bb2);
break;}
case SHP_BOX3D: {
a = bb.width() / 8;
bb2 = bb.adjusted (0, a, -a, 0);
painter->drawRect (bb2);
pts[0].setX (bb2.left() ); pts[0].setY( bb2.top());
pts[1].setX (bb2.left()+a ); pts[1].setY( bb.top());
pts[2].setX (bb.right() ); pts[2].setY( bb.top());
pts[3].setX (bb.right() ); pts[3].setY( bb2.bottom()-a);
pts[4].setX (bb2.right() ); pts[4].setY( bb2.bottom());
painter->drawPolyline (&pts[0], 5);
painter->drawLine (pts[2], bb2.topRight());
break;}
case SHP_COMPONENT: {
a = bb.width() / 12;
bb2 = bb.adjusted (a, 0, 0, 0);
painter->drawRect (bb2);
bb2 = QRectF (bb.left(), bb.top()+a, a*2, a);
painter->drawRect (bb2);
bb2.translate (0, bb.height() - a*3);
painter->drawRect (bb2);
break;}
case SHP_DIAMOND: {
pts[0].setX (bb.left() ); pts[0].setY( bb.top()+bb.height()/2);
pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top());
pts[2].setX (bb.right() ); pts[2].setY( pts[0].y());
pts[3].setX (pts[1].x() ); pts[3].setY( bb.bottom());
painter->drawConvexPolygon (&pts[0], 4);
break;}
case SHP_TRIPLEOCTAGON: {
a = bb.height() / 16;
bb2 = bb.adjusted (a, a, -a, -a);
octogonInRect (bb, &pts[0]);
painter->drawPolyline (&pts[0], 9);
octogonInRect (bb2, &pts[0]);
painter->drawPolyline (&pts[0], 9);
bb2 = bb2.adjusted (a, a, -a, -a);
octogonInRect (bb2, &pts[0]);
painter->drawConvexPolygon (&pts[0], 8);
break;}
case SHP_DOUBLEOCTAGON: {
a = bb.height() / 16;
bb2 = bb.adjusted (a, a, -a, -a);
octogonInRect (bb, &pts[0]);
painter->drawPolyline (&pts[0], 9);
octogonInRect (bb2, &pts[0]);
painter->drawConvexPolygon (&pts[0], 8);
break;}
case SHP_OCTAGON: {
octogonInRect (bb, &pts[0]);
painter->drawConvexPolygon (&pts[0], 8);
break;}
case SHP_HEXAGON: {
a = bb.height() / 2;
pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a);
pts[1].setX (bb.left()+a ); pts[1].setY( bb.top());
pts[2].setX (bb.right()-a ); pts[2].setY( bb.top());
pts[3].setX (bb.right() ); pts[3].setY( bb.top()+a);
pts[4].setX (bb.right()-a ); pts[4].setY( bb.bottom());
pts[5].setX (bb.left()+a ); pts[5].setY( bb.bottom());
painter->drawConvexPolygon (&pts[0], 6);
break;}
case SHP_HOUSE: {
a = bb.height() / 3;
pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a);
pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top());
pts[2].setX (bb.right() ); pts[2].setY( bb.top()+a);
pts[3].setX (bb.right() ); pts[3].setY( bb.bottom());
pts[4].setX (bb.left() ); pts[4].setY( bb.bottom());
painter->drawConvexPolygon (&pts[0], 5);
break;}
case SHP_INVHOUSE: {
a = bb.height() / 3;
pts[0].setX (bb.left() ); pts[0].setY( bb.bottom()-a);
pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.bottom());
pts[2].setX (bb.right() ); pts[2].setY( bb.bottom()-a);
pts[3].setX (bb.right() ); pts[3].setY( bb.top());
pts[4].setX (bb.left() ); pts[4].setY( bb.top());
painter->drawConvexPolygon (&pts[0], 5);
break;}
case SHP_TRIANGLE: {
pts[0].setX (bb.left() ); pts[0].setY( bb.bottom());
pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top());
pts[2].setX (bb.right() ); pts[2].setY( bb.bottom());
painter->drawConvexPolygon (&pts[0], 3);
break;}
case SHP_INVTRIANGLE: {
pts[0].setX (bb.left() ); pts[0].setY( bb.top());
pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.bottom());
pts[2].setX (bb.right() ); pts[2].setY( bb.top());
painter->drawConvexPolygon (&pts[0], 3);
break;}
case SHP_TRAPEZIUM: {
a = bb.width() / 8;
pts[0].setX (bb.left() ); pts[0].setY( bb.bottom());
pts[1].setX (bb.left()+a ); pts[1].setY( bb.top());
pts[2].setX (bb.right()-a ); pts[2].setY( bb.top());
pts[3].setX (bb.right() ); pts[3].setY( bb.bottom());
pts[4] = pts[0];
painter->drawConvexPolygon (&pts[0], 4);
break;}
case SHP_INVTRAPEZIUM: {
a = bb.width() / 8;
pts[0].setX (bb.left() ); pts[0].setY( bb.top());
pts[1].setX (bb.left()+a ); pts[1].setY( bb.bottom());
pts[2].setX (bb.right()-a ); pts[2].setY( bb.bottom());
pts[3].setX (bb.right() ); pts[3].setY( bb.top());
painter->drawConvexPolygon (&pts[0], 4);
break;}
case SHP_NOTE: {
a = bb.width() / 8;
pts[0].setX (bb.left() ); pts[0].setY( bb.top());
pts[1].setX (bb.right()-a ); pts[1].setY( bb.top());
pts[2].setX (bb.right() ); pts[2].setY( bb.top()+a);
pts[3].setX (bb.right() ); pts[3].setY( bb.bottom());
pts[4].setX (bb.left() ); pts[4].setY( bb.bottom());
painter->drawConvexPolygon (&pts[0], 5);
pts[3] = pts[2];
pts[2].setX (pts[1].x()); /* y already == to 3.y) */
painter->drawPolyline (&pts[1], 3);
break;}
case SHP_PLAINTEXT:
break;
case SHP_PARALLELOGRAM: {
a = bb.width() / 8;
pts[0].setX (bb.left() ); pts[0].setY( bb.bottom());
pts[1].setX (bb.left()+a ); pts[1].setY( bb.top());
pts[2].setX (bb.right() ); pts[2].setY( bb.top());
pts[3].setX (bb.right()-a ); pts[3].setY( bb.bottom());
painter->drawConvexPolygon (&pts[0], 4);
break;}
case SHP_POLYGON:
case SHP_SEPTAGON: {
qreal a_1_3 = bb.height() / 3;
qreal a_2_3 = a_1_3 * 2;
pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a_2_3);
pts[1].setX (bb.left()+a_1_3/2 ); pts[1].setY( bb.top()+a_1_3/2);
pts[2].setX (bb.left()+bb.width()/2 ); pts[2].setY( bb.top());
pts[3].setX (bb.right()-a_1_3/2 ); pts[3].setY( pts[1].y());
pts[4].setX (bb.right() ); pts[4].setY( pts[0].y());
pts[5].setX (bb.right()-a_1_3 ); pts[5].setY( bb.bottom());
pts[6].setX (bb.left()+a_1_3 ); pts[6].setY( bb.bottom());
painter->drawConvexPolygon (&pts[0], 7);
break;}
case SHP_POINT: {
painter->drawEllipse (bb);
break;}
case SHP_PENTAGON: {
a = bb.height() / 3;
pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a);
pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top());
pts[2].setX (bb.right() ); pts[2].setY( bb.top()+a);
pts[3].setX (bb.right()-a ); pts[3].setY( bb.bottom());
pts[4].setX (bb.left()+a ); pts[4].setY( bb.bottom());
painter->drawConvexPolygon (&pts[0], 5);
break;}
case SHP_FOLDER: {
qreal a = bb.width() / 8;
QRectF bb2 (bb.right()-a*2, bb.top(), a*2, a);
painter->drawRect (bb);
painter->drawRect (bb2);
break;}
case SHP_TAB: {
qreal a = bb.width() / 8;
QRectF bb2 (bb.left(), bb.top(), a*2, a);
painter->drawRect (bb);
painter->drawRect (bb2);
break;}
default:
painter->drawRoundedRect (bb, 5, 5);
}
/* the label */
textlabel_t * tl = ND_label (dot_n_);
QString lbl = tl->text;
if (tl->html)
{
/** @todo html rendering */
}
else
{
}
if (lbl.isEmpty() == false)
{
painter->setPen (QColor( tl->fontcolor ).toRgb());
QFont f = painter->font();
f.setFamily (tl->fontname);
f.setPointSize (tl->fontsize);
painter->setFont (f);
QTextOption to;
to.setWrapMode (QTextOption::WordWrap);
Qt::AlignmentFlag align;
switch ( tl->valign ) {
case 't':
align = Qt::AlignTop;
break;
case 'b':
align = Qt::AlignBottom;
break;
default:
align = Qt::AlignVCenter;
}
/* stuuuuuupid */
align = (Qt::AlignmentFlag) (0x0004 | align);
to.setAlignment (align);
lbl.replace ("\\N", "\n", Qt::CaseInsensitive);
lbl.replace ("\\T", "\t", Qt::CaseInsensitive);
lbl.replace ("\\R", "\r", Qt::CaseInsensitive);
lbl.replace ("\\\\", "\\");
painter->drawText (bb, lbl, to);
}
// if (atr_label != NULL){
// vl = agxget (dot_n_, atr_label->index);
// if (atr_fontcolor != NULL){
// vl = agxget (dot_n_, atr_fontcolor->index);
// painter->setPen (QColor( vl ).toRgb());
// }
// if (atr_fontname != NULL){
// vl = agxget (dot_n_, atr_fontname->index);
// QFont f = painter->font();
// f.setFamily (vl);
// painter->setFont (f);
// }
// if (atr_fontsize != NULL){
// vl = agxget (dot_n_, atr_fontsize->index);
// QFont f = painter->font();
// a = QString (vl ).toDouble( &b_ok);
// if (b_ok && ( a > 1 ))
// {
// f.setPointSize (a);
// painter->setFont (f);
// }
// }
}
/* ========================================================================= */
/* ------------------------------------------------------------------------- */
void GVzNode::updateCachedData ()
{
if (dot_n_ == NULL)
return;
/* position */
pointf center = ND_coord (dot_n_);
setPos (center.x, -center.y);
/* shape */
shape_desc * shp = ND_shape (dot_n_);
shp_ = SHP_UDEF;
if (shp->usershape == false)
{
int i;
int j;
for ( i = 0; ; i++ )
{
if (shape_names[i] == NULL)
{
break;
}
j = strcmp (shape_names[i], shp->name);
if (j == 0)
{
shp_ = (NdShape)i;
break;
}
else if (j > 0)
{
break;
}
}
}
}
/* ========================================================================= */
/* ------------------------------------------------------------------------- */
QList<GVzNode*> GVzNode::nodes () const
{
QList<GVzNode*> l_nodes;
GVzEdge * edg;
foreach( edg, edg_l_ ) {
GVzNode * nd = edg->destination();
if (nd != NULL)
{
l_nodes.append (nd);
}
}
return l_nodes;
}
/* ========================================================================= */
/* ------------------------------------------------------------------------- */
void GVzNode::setHighlite (bool b_sts)
{
if (b_sts)
{
st_lst_ = (States) (st_lst_ | ST_HIGHLITE);
}
else
{
st_lst_ = (States) (st_lst_ & (~ST_HIGHLITE));
}
update();
}
/* ========================================================================= */
#endif // DE_WITH_GRAPHVIZ
/* CLASS =============================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
/* graph with color */
/*
digraph graph_name {
node [
style = filled
fillcolor = "#FCE975"
color ="#ff007f"
fontcolor="#005500"
]
a -> b
}
*/
/* test graph for node shapes */
/*
digraph shapes_test {
node_Mcircle [
shape=Mcircle
label="Mcircle"
]
node_Mdiamond [
shape=Mdiamond
label="Mdiamond"
]
node_Msquare [
shape=Msquare
label="Msquare"
]
node_box [
shape=box
label="box"
]
node_box3d [
shape=box3d
label="box3d"
]
node_circle [
shape=circle
label="circle"
]
node_component [
shape=component
label="component"
]
node_diamond [
shape=diamond
label="diamond"
]
node_doublecircle [
shape=doublecircle
label="doublecircle"
]
node_doubleoctagon [
shape=doubleoctagon
label="doubleoctagon"
]
node_egg [
shape=egg
label="egg"
]
node_ellipse [
shape=ellipse
label="ellipse"
]
node_folder [
shape=folder
label="folder"
]
node_hexagon [
shape=hexagon
label="hexagon"
]
node_house [
shape=house
label="house"
]
node_invhouse [
shape=invhouse
label="invhouse"
]
node_invtrapezium [
shape=invtrapezium
label="invtrapezium"
]
node_invtriangle [
shape=invtriangle
label="invtriangle"
]
node_none [
shape=none
label="none"
]
node_note [
shape=note
label="note"
]
node_octagon [
shape=octagon
label="octagon"
]
node_oval [
shape=oval
label="oval"
]
node_parallelogram [
shape=parallelogram
label="parallelogram"
]
node_pentagon [
shape=pentagon
label="pentagon"
]
node_plaintext [
shape=plaintext
label="plaintext"
]
node_point [
shape=point
label="point"
]
node_polygon [
shape=polygon
label="polygon"
]
node_rect [
shape=rect
label="rect"
]
node_rectangle [
shape=rectangle
label="rectangle"
]
node_septagon [
shape=septagon
label="septagon"
]
node_square [
shape=square
label="square"
]
node_tab [
shape=tab
label="tab"
]
node_trapezium [
shape=trapezium
label="trapezium"
]
node_triangle [
shape=triangle
label="triangle"
]
node_tripleoctagon [
shape=tripleoctagon
label="tripleoctagon"
]
}
*/
| 22.009423 | 79 | 0.505031 | flyfire100 |
cd8b1e066b48e12c8309f635958842cfc37e95c6 | 5,902 | cpp | C++ | apps/interpolate_generator/interpolate_generator.cpp | Neo-Vincent/Halide | 50c40dc185b040b93f1a90b6373a82744312cfd6 | [
"MIT"
] | null | null | null | apps/interpolate_generator/interpolate_generator.cpp | Neo-Vincent/Halide | 50c40dc185b040b93f1a90b6373a82744312cfd6 | [
"MIT"
] | null | null | null | apps/interpolate_generator/interpolate_generator.cpp | Neo-Vincent/Halide | 50c40dc185b040b93f1a90b6373a82744312cfd6 | [
"MIT"
] | null | null | null | #include "Halide.h"
namespace {
class Interpolate : public Halide::Generator<Interpolate> {
public:
GeneratorParam<int> levels_{"levels", 10};
Input<Buffer<float>> input_{"input", 3};
Output<Buffer<float>> output_{"output", 3};
void generate() {
Var x("x"), y("y"), c("c");
const int levels = levels_;
// Input must have four color channels - rgba
input_.dim(2).set_bounds(0, 4);
Func downsampled[levels];
Func downx[levels];
Func interpolated[levels];
Func upsampled[levels];
Func upsampledx[levels];
Func clamped = Halide::BoundaryConditions::repeat_edge(input_);
downsampled[0](x, y, c) = select(c < 3, clamped(x, y, c) * clamped(x, y, 3), clamped(x, y, 3));
for (int l = 1; l < levels; ++l) {
Func prev = downsampled[l-1];
if (l == 4) {
// Also add a boundary condition at a middle pyramid level
// to prevent the footprint of the downsamplings to extend
// too far off the base image. Otherwise we look 512
// pixels off each edge.
Expr w = input_.width()/(1 << l);
Expr h = input_.height()/(1 << l);
prev = lambda(x, y, c, prev(clamp(x, 0, w), clamp(y, 0, h), c));
}
downx[l](x, y, c) = (prev(x*2-1, y, c) +
2.0f * prev(x*2, y, c) +
prev(x*2+1, y, c)) * 0.25f;
downsampled[l](x, y, c) = (downx[l](x, y*2-1, c) +
2.0f * downx[l](x, y*2, c) +
downx[l](x, y*2+1, c)) * 0.25f;
}
interpolated[levels-1](x, y, c) = downsampled[levels-1](x, y, c);
for (int l = levels-2; l >= 0; --l) {
upsampledx[l](x, y, c) = (interpolated[l+1](x/2, y, c) +
interpolated[l+1]((x+1)/2, y, c)) / 2.0f;
upsampled[l](x, y, c) = (upsampledx[l](x, y/2, c) +
upsampledx[l](x, (y+1)/2, c)) / 2.0f;
interpolated[l](x, y, c) = downsampled[l](x, y, c) + (1.0f - downsampled[l](x, y, 3)) * upsampled[l](x, y, c);
}
Func normalize("normalize");
normalize(x, y, c) = interpolated[0](x, y, c) / interpolated[0](x, y, 3);
// Schedule
if (auto_schedule) {
output_ = normalize;
} else {
Var yo, yi, xo, xi, ci;
if (get_target().has_gpu_feature()) {
// Some gpus don't have enough memory to process the entire
// image, so we process the image in tiles.
// We can't compute the entire output stage at once on the GPU
// - it takes too much GPU memory on some of our build bots,
// so we wrap the final stage in a CPU stage.
Func cpu_wrapper = normalize.in();
cpu_wrapper
.reorder(c, x, y)
.bound(c, 0, 3)
.tile(x, y, xo, yo, xi, yi, input_.width()/4, input_.height()/4)
.vectorize(xi, 8);
normalize
.compute_at(cpu_wrapper, xo)
.reorder(c, x, y)
.gpu_tile(x, y, xi, yi, 16, 16)
.unroll(c);
// Start from level 1 to save memory - level zero will be computed on demand
for (int l = 1; l < levels; ++l) {
int tile_size = 32 >> l;
if (tile_size < 1) tile_size = 1;
if (tile_size > 8) tile_size = 8;
downsampled[l]
.compute_root()
.gpu_tile(x, y, c, xi, yi, ci, tile_size, tile_size, 4);
if (l == 1 || l == 4) {
interpolated[l]
.compute_at(cpu_wrapper, xo)
.gpu_tile(x, y, c, xi, yi, ci, 8, 8, 4);
} else {
int parent = l > 4 ? 4 : 1;
interpolated[l]
.compute_at(interpolated[parent], x)
.gpu_threads(x, y, c);
}
}
// The cpu wrapper is our new output Func
output_ = cpu_wrapper;
} else {
for (int l = 1; l < levels-1; ++l) {
downsampled[l]
.compute_root()
.parallel(y, 8)
.vectorize(x, 4);
interpolated[l]
.compute_root()
.parallel(y, 8)
.unroll(x, 2)
.unroll(y, 2)
.vectorize(x, 8);
}
normalize
.reorder(c, x, y)
.bound(c, 0, 3)
.unroll(c)
.tile(x, y, xi, yi, 2, 2)
.unroll(xi)
.unroll(yi)
.parallel(y, 8)
.vectorize(x, 8)
.bound(x, 0, input_.width())
.bound(y, 0, input_.height());
output_ = normalize;
}
}
// Estimates (for autoscheduler; ignored otherwise)
{
input_.dim(0).set_bounds_estimate(0, 1536)
.dim(1).set_bounds_estimate(0, 2560)
.dim(2).set_bounds_estimate(0, 4);
output_.dim(0).set_bounds_estimate(0, 1536)
.dim(1).set_bounds_estimate(0, 2560)
.dim(2).set_bounds_estimate(0, 3);
}
}
};
} // namespace
HALIDE_REGISTER_GENERATOR(Interpolate, interpolate)
| 38.575163 | 122 | 0.420535 | Neo-Vincent |
cd8c5901bf224cd114a7c090461f91041992d6d8 | 2,340 | cpp | C++ | nntrainer/layers/addition_layer.cpp | JuYeong0413/nntrainer | 37b7c2234dd591a994148d14dd399037702ccd31 | [
"Apache-2.0"
] | null | null | null | nntrainer/layers/addition_layer.cpp | JuYeong0413/nntrainer | 37b7c2234dd591a994148d14dd399037702ccd31 | [
"Apache-2.0"
] | null | null | null | nntrainer/layers/addition_layer.cpp | JuYeong0413/nntrainer | 37b7c2234dd591a994148d14dd399037702ccd31 | [
"Apache-2.0"
] | null | null | null | // SPDX-License-Identifier: Apache-2.0
/**
* Copyright (C) 2020 Parichay Kapoor <pk.kapoor@samsung.com>
*
* @file addition_layer.cpp
* @date 30 July 2020
* @see https://github.com/nnstreamer/nntrainer
* @author Parichay Kapoor <pk.kapoor@samsung.com>
* @bug No known bugs except for NYI items
* @brief This is Addition Layer Class for Neural Network
*
*/
#include <addition_layer.h>
#include <layer_internal.h>
#include <nntrainer_error.h>
#include <nntrainer_log.h>
#include <parse_util.h>
#include <util_func.h>
namespace nntrainer {
int AdditionLayer::initialize(Manager &manager) {
int status = ML_ERROR_NONE;
if (getNumInputs() == 0) {
ml_loge("Error: number of inputs are not initialized");
return ML_ERROR_INVALID_PARAMETER;
}
for (unsigned int idx = 0; idx < getNumInputs(); ++idx) {
if (input_dim[idx].getDataLen() == 1) {
ml_logw("Warning: the length of previous layer dimension is one");
}
}
/** input dimension indicates the dimension for all the inputs to follow */
output_dim[0] = input_dim[0];
return status;
}
void AdditionLayer::forwarding(bool training) {
Tensor &hidden_ = net_hidden[0]->getVariableRef();
TensorDim &in_dim = input_dim[0];
/** @todo check possibility for in-place of addition layer */
for (unsigned int idx = 0; idx < getNumInputs(); ++idx) {
if (in_dim != net_input[idx]->getDim())
throw std::invalid_argument("Error: addition layer requires same "
"shape from all input layers");
if (!idx) {
hidden_.fill(net_input[idx]->getVariableRef(), false);
} else {
hidden_.add_i(net_input[idx]->getVariableRef());
}
}
}
void AdditionLayer::calcDerivative() {
for (unsigned int i = 0; i < getNumInputs(); ++i) {
net_input[i]->getGradientRef() = net_hidden[0]->getGradientRef();
}
}
void AdditionLayer::setProperty(const PropertyType type,
const std::string &value) {
int status = ML_ERROR_NONE;
switch (type) {
case PropertyType::num_inputs: {
if (!value.empty()) {
unsigned int num_inputs;
status = setUint(num_inputs, value);
throw_status(status);
setNumInputs(num_inputs);
}
} break;
default:
LayerV1::setProperty(type, value);
break;
}
}
} /* namespace nntrainer */
| 27.209302 | 77 | 0.654274 | JuYeong0413 |
cd9205524109317c1bb2fbc2e4aa4c485289ae60 | 22,138 | cxx | C++ | PWGHF/vertexingHF/AliNormalizationCounter.cxx | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | null | null | null | PWGHF/vertexingHF/AliNormalizationCounter.cxx | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | null | null | null | PWGHF/vertexingHF/AliNormalizationCounter.cxx | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | null | null | null | /**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//*************************************************************************
// Class AliNormalizationCounter
// Class to store the informations relevant for the normalization in the
// barrel for each run
// Authors: G. Ortona, ortona@to.infn.it
// D. Caffarri, davide.caffarri@pd.to.infn.it
// with many thanks to P. Pillot
/////////////////////////////////////////////////////////////
#include "AliLog.h"
#include "AliNormalizationCounter.h"
#include <AliESDEvent.h>
#include <AliESDtrack.h>
#include <AliAODEvent.h>
#include <AliAODVZERO.h>
#include <AliVParticle.h>
#include <AliTriggerAnalysis.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TList.h>
#include <TObjArray.h>
#include <TString.h>
#include <TCanvas.h>
#include <AliPhysicsSelection.h>
#include <AliMultiplicity.h>
/// \cond CLASSIMP
ClassImp(AliNormalizationCounter);
/// \endcond
//____________________________________________
AliNormalizationCounter::AliNormalizationCounter():
TNamed(),
fCounters(),
fESD(kFALSE),
fMultiplicity(kFALSE),
fMultiplicityEtaRange(1.0),
fSpherocity(kFALSE),
fSpherocitySteps(100.),
fHistTrackFilterEvMult(0),
fHistTrackAnaEvMult(0),
fHistTrackFilterSpdMult(0),
fHistTrackAnaSpdMult(0)
{
// empty constructor
}
//__________________________________________________
AliNormalizationCounter::AliNormalizationCounter(const char *name):
TNamed(name,name),
fCounters(name),
fESD(kFALSE),
fMultiplicity(kFALSE),
fMultiplicityEtaRange(1.0),
fSpherocity(kFALSE),
fSpherocitySteps(100.),
fHistTrackFilterEvMult(0),
fHistTrackAnaEvMult(0),
fHistTrackFilterSpdMult(0),
fHistTrackAnaSpdMult(0)
{
;
}
//______________________________________________
AliNormalizationCounter::~AliNormalizationCounter()
{
//destructor
if(fHistTrackFilterEvMult){
delete fHistTrackFilterEvMult;
fHistTrackFilterEvMult =0;
}
if(fHistTrackAnaEvMult){
delete fHistTrackAnaEvMult;
fHistTrackAnaEvMult=0;
}
if(fHistTrackFilterSpdMult){
delete fHistTrackFilterSpdMult;
fHistTrackFilterSpdMult=0;
}
if(fHistTrackAnaSpdMult){
delete fHistTrackAnaSpdMult;
fHistTrackAnaSpdMult=0;
}
}
//______________________________________________
void AliNormalizationCounter::Init()
{
//variables initialization
fCounters.AddRubric("Event","triggered/V0AND/PileUp/PbPbC0SMH-B-NOPF-ALLNOTRD/Candles0.3/PrimaryV/countForNorm/noPrimaryV/zvtxGT10/!V0A&Candle03/!V0A&PrimaryV/Candid(Filter)/Candid(Analysis)/NCandid(Filter)/NCandid(Analysis)");
if(fMultiplicity) fCounters.AddRubric("Multiplicity", 5000);
if(fSpherocity) fCounters.AddRubric("Spherocity", (Int_t)fSpherocitySteps+1);
fCounters.AddRubric("Run", 1000000);
fCounters.Init();
fHistTrackFilterEvMult=new TH2F("FiltCandidvsTracksinEv","FiltCandidvsTracksinEv",10000,-0.5,9999.5,200,-0.5,199.5);
fHistTrackFilterEvMult->GetYaxis()->SetTitle("NCandidates");
fHistTrackFilterEvMult->GetXaxis()->SetTitle("NTracksinEvent");
fHistTrackAnaEvMult=new TH2F("AnaCandidvsTracksinEv","AnaCandidvsTracksinEv",10000,-0.5,9999.5,100,-0.5,99.5);
fHistTrackAnaEvMult->GetYaxis()->SetTitle("NCandidates");
fHistTrackAnaEvMult->GetXaxis()->SetTitle("NTracksinEvent");
fHistTrackFilterSpdMult=new TH2F("FilterCandidvsSpdMult","FilterCandidvsSpdMult",5000,-0.5,4999.5,200,-0.5,199.5);
fHistTrackFilterSpdMult->GetYaxis()->SetTitle("NCandidates");
fHistTrackFilterSpdMult->GetXaxis()->SetTitle("NSPDTracklets");
fHistTrackAnaSpdMult=new TH2F("AnaCandidvsSpdMult","AnaCandidvsSpdMult",5000,-0.5,4999.5,100,-0.5,99.5);
fHistTrackAnaSpdMult->GetYaxis()->SetTitle("NCandidates");
fHistTrackAnaSpdMult->GetXaxis()->SetTitle("NSPDTracklets");
}
//______________________________________________
Long64_t AliNormalizationCounter::Merge(TCollection* list){
if (!list) return 0;
if (list->IsEmpty()) return 0;//(Long64_t)fCounters.Merge(list);
TIter next(list);
const TObject* obj = 0x0;
while ((obj = next())) {
// check that "obj" is an object of the class AliNormalizationCounter
const AliNormalizationCounter* counter = dynamic_cast<const AliNormalizationCounter*>(obj);
if (!counter) {
AliError(Form("object named %s is not AliNormalizationCounter! Skipping it.", counter->GetName()));
continue;
}
Add(counter);
}
return (Long64_t)1;//(Long64_t)fCounters->GetEntries();
}
//_______________________________________
void AliNormalizationCounter::Add(const AliNormalizationCounter *norm){
fCounters.Add(&(norm->fCounters));
fHistTrackFilterEvMult->Add(norm->fHistTrackFilterEvMult);
fHistTrackAnaEvMult->Add(norm->fHistTrackAnaEvMult);
fHistTrackFilterSpdMult->Add(norm->fHistTrackFilterSpdMult);
fHistTrackAnaSpdMult->Add(norm->fHistTrackAnaSpdMult);
}
//_______________________________________
/*
Stores the variables used for normalization as function of run number
returns kTRUE if the event is to be counted for normalization
(pass event selection cuts OR has no primary vertex)
*/
void AliNormalizationCounter::StoreEvent(AliVEvent *event,AliRDHFCuts *rdCut,Bool_t mc, Int_t multiplicity, Double_t spherocity){
//
Bool_t isEventSelected = rdCut->IsEventSelected(event);
// events not passing physics selection. do nothing
if(rdCut->IsEventRejectedDuePhysicsSelection()) return;
Bool_t v0A=kFALSE;
Bool_t v0B=kFALSE;
Bool_t flag03=kFALSE;
Bool_t flagPV=kFALSE;
//Run Number
Int_t runNumber = event->GetRunNumber();
// Evaluate the multiplicity
if(fMultiplicity && multiplicity==-9999) Multiplicity(event);
//Find CINT1B
AliESDEvent *eventESD = (AliESDEvent*)event;
if(!eventESD){AliError("ESD event not available");return;}
if(mc&&event->GetEventType() != 0)return;
//event must be either physics or MC
if(!(event->GetEventType() == 7||event->GetEventType() == 0))return;
FillCounters("triggered",runNumber,multiplicity,spherocity);
//Find V0AND
AliTriggerAnalysis trAn; /// Trigger Analysis
AliAODVZERO* aodV0 = (AliAODVZERO*)event->GetVZEROData();
Bool_t isPP2012 = kFALSE;
if(runNumber>=176326 && runNumber<=193766) isPP2012=kTRUE;
if(aodV0 && !isPP2012){
v0B = trAn.IsOfflineTriggerFired(eventESD , AliTriggerAnalysis::kV0C);
v0A = trAn.IsOfflineTriggerFired(eventESD , AliTriggerAnalysis::kV0A);
}
if(v0A&&v0B) FillCounters("V0AND",runNumber,multiplicity,spherocity);
//FindPrimary vertex
// AliVVertex *vtrc = (AliVVertex*)event->GetPrimaryVertex();
// if(vtrc && vtrc->GetNContributors()>0){
// fCounters.Count(Form("Event:PrimaryV/Run:%d",runNumber));
// flagPV=kTRUE;
// }
//trigger
AliAODEvent *eventAOD = (AliAODEvent*)event;
TString trigclass=eventAOD->GetFiredTriggerClasses();
if(trigclass.Contains("C0SMH-B-NOPF-ALLNOTRD")||trigclass.Contains("C0SMH-B-NOPF-ALL")){
FillCounters("PbPbC0SMH-B-NOPF-ALLNOTRD",runNumber,multiplicity,spherocity);
}
//FindPrimary vertex
if(isEventSelected){
FillCounters("PrimaryV",runNumber,multiplicity,spherocity);
flagPV=kTRUE;
}else{
if(rdCut->GetWhyRejection()==0){
FillCounters("noPrimaryV",runNumber,multiplicity,spherocity);
}
//find good vtx outside range
if(rdCut->GetWhyRejection()==6){
FillCounters("zvtxGT10",runNumber,multiplicity,spherocity);
FillCounters("PrimaryV",runNumber,multiplicity,spherocity);
flagPV=kTRUE;
}
if(rdCut->GetWhyRejection()==1){
FillCounters("PileUp",runNumber,multiplicity,spherocity);
}
}
//to be counted for normalization
if(rdCut->CountEventForNormalization()){
FillCounters("countForNorm",runNumber,multiplicity,spherocity);
}
//Find Candle
Int_t trkEntries = (Int_t)event->GetNumberOfTracks();
for(Int_t i=0;i<trkEntries&&!flag03;i++){
AliAODTrack *track=(AliAODTrack*)event->GetTrack(i);
if((track->Pt()>0.3)&&(!flag03)){
FillCounters("Candles0.3",runNumber,multiplicity,spherocity);
flag03=kTRUE;
break;
}
}
if(!(v0A&&v0B)&&(flag03)){
FillCounters("!V0A&Candle03",runNumber,multiplicity,spherocity);
}
if(!(v0A&&v0B)&&flagPV){
FillCounters("!V0A&PrimaryV",runNumber,multiplicity,spherocity);
}
return;
}
//_____________________________________________________________________
void AliNormalizationCounter::StoreCandidates(AliVEvent *event,Int_t nCand,Bool_t flagFilter){
Int_t ntracks=event->GetNumberOfTracks();
if(flagFilter)fHistTrackFilterEvMult->Fill(ntracks,nCand);
else fHistTrackAnaEvMult->Fill(ntracks,nCand);
Int_t nSPD=0;
if(fESD){
AliESDEvent *ESDevent=(AliESDEvent*)event;
const AliMultiplicity *alimult = ESDevent->GetMultiplicity();
nSPD = alimult->GetNumberOfTracklets();
}else{
AliAODEvent *aodEvent =(AliAODEvent*)event;
AliAODTracklets *trklets=aodEvent->GetTracklets();
nSPD = trklets->GetNumberOfTracklets();
}
if(flagFilter)fHistTrackFilterSpdMult->Fill(nSPD,nCand);
else fHistTrackAnaSpdMult->Fill(nSPD,nCand);
Int_t runNumber = event->GetRunNumber();
Int_t multiplicity = Multiplicity(event);
if(nCand==0)return;
if(flagFilter){
if(fMultiplicity)
fCounters.Count(Form("Event:Candid(Filter)/Run:%d/Multiplicity:%d",runNumber,multiplicity));
else
fCounters.Count(Form("Event:Candid(Filter)/Run:%d",runNumber));
for(Int_t i=0;i<nCand;i++){
if(fMultiplicity)
fCounters.Count(Form("Event:NCandid(Filter)/Run:%d/Multiplicity:%d",runNumber,multiplicity));
else
fCounters.Count(Form("Event:NCandid(Filter)/Run:%d",runNumber));
}
}else{
if(fMultiplicity)
fCounters.Count(Form("Event:Candid(Analysis)/Run:%d/Multiplicity:%d",runNumber,multiplicity));
else
fCounters.Count(Form("Event:Candid(Analysis)/Run:%d",runNumber));
for(Int_t i=0;i<nCand;i++){
if(fMultiplicity)
fCounters.Count(Form("Event:NCandid(Analysis)/Run:%d/Multiplicity:%d",runNumber,multiplicity));
else
fCounters.Count(Form("Event:NCandid(Analysis)/Run:%d",runNumber));
}
}
return;
}
//_______________________________________________________________________
TH1D* AliNormalizationCounter::DrawAgainstRuns(TString candle,Bool_t drawHist){
//
fCounters.SortRubric("Run");
TString selection;
selection.Form("event:%s",candle.Data());
TH1D* histoneD = fCounters.Get("run",selection.Data());
histoneD->Sumw2();
if(drawHist)histoneD->DrawClone();
return histoneD;
}
//___________________________________________________________________________
TH1D* AliNormalizationCounter::DrawRatio(TString candle1,TString candle2){
//
fCounters.SortRubric("Run");
TString name;
name.Form("%s/%s",candle1.Data(),candle2.Data());
TH1D* num=DrawAgainstRuns(candle1.Data(),kFALSE);
TH1D* den=DrawAgainstRuns(candle2.Data(),kFALSE);
den->SetTitle(candle2.Data());
den->SetName(candle2.Data());
num->Divide(num,den,1,1,"B");
num->SetTitle(name.Data());
num->SetName(name.Data());
num->DrawClone();
return num;
}
//___________________________________________________________________________
void AliNormalizationCounter::PrintRubrics(){
fCounters.PrintKeyWords();
}
//___________________________________________________________________________
Double_t AliNormalizationCounter::GetSum(TString candle){
TString selection="event:";
selection.Append(candle);
return fCounters.GetSum(selection.Data());
}
//___________________________________________________________________________
TH2F* AliNormalizationCounter::GetHist(Bool_t filtercuts,Bool_t spdtracklets,Bool_t drawHist){
if(filtercuts){
if(spdtracklets){
if(drawHist)fHistTrackFilterSpdMult->DrawCopy("LEGO2Z 0");
return fHistTrackFilterSpdMult;
}else{
if(drawHist)fHistTrackFilterEvMult->DrawCopy("LEGO2Z 0");
return fHistTrackFilterEvMult;
}
}else{
if(spdtracklets){
if(drawHist)fHistTrackAnaSpdMult->DrawCopy("LEGO2Z 0");
return fHistTrackAnaSpdMult;
}else{
if(drawHist)fHistTrackAnaEvMult->DrawCopy("LEGO2Z 0");
return fHistTrackAnaEvMult;
}
}
}
//___________________________________________________________________________
Double_t AliNormalizationCounter::GetNEventsForNorm(){
Double_t noVtxzGT10=GetSum("noPrimaryV")*GetSum("zvtxGT10")/GetSum("PrimaryV");
return GetSum("countForNorm")-noVtxzGT10;
}
//___________________________________________________________________________
Double_t AliNormalizationCounter::GetNEventsForNorm(Int_t runnumber){
TString listofruns = fCounters.GetKeyWords("RUN");
if(!listofruns.Contains(Form("%d",runnumber))){
printf("WARNING: %d is not a valid run number\n",runnumber);
fCounters.Print("Run","",kTRUE);
return 0.;
}
TString suffix;suffix.Form("/RUN:%d",runnumber);
TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data());
TString noPV;noPV.Form("noPrimaryV%s",suffix.Data());
TString pV;pV.Form("PrimaryV%s",suffix.Data());
TString tbc;tbc.Form("countForNorm%s",suffix.Data());
Double_t noVtxzGT10=GetSum(noPV.Data())*GetSum(zvtx.Data())/GetSum(pV.Data());
return GetSum(tbc.Data())-noVtxzGT10;
}
//___________________________________________________________________________
Double_t AliNormalizationCounter::GetNEventsForNorm(Int_t minmultiplicity, Int_t maxmultiplicity){
if(!fMultiplicity) {
AliInfo("Sorry, you didn't activate the multiplicity in the counter!");
return 0.;
}
TString listofruns = fCounters.GetKeyWords("Multiplicity");
Int_t nmultbins = maxmultiplicity - minmultiplicity;
Double_t sumnoPV=0., sumZvtx=0., sumPv=0., sumEvtNorm=0.;
for (Int_t ibin=0; ibin<=nmultbins; ibin++) {
// cout << " Looking at bin "<< ibin+minmultiplicity<<endl;
if(!listofruns.Contains(Form("%d",ibin+minmultiplicity))){
// AliInfo(Form("WARNING: %d is not a valid multiplicity number. \n",ibin+minmultiplicity));
continue;
}
TString suffix;suffix.Form("/Multiplicity:%d",ibin+minmultiplicity);
TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data());
TString noPV;noPV.Form("noPrimaryV%s",suffix.Data());
TString pV;pV.Form("PrimaryV%s",suffix.Data());
TString tbc;tbc.Form("countForNorm%s",suffix.Data());
sumnoPV += GetSum(noPV.Data());
sumZvtx += GetSum(zvtx.Data());
sumPv += GetSum(pV.Data());
sumEvtNorm += GetSum(tbc.Data());
}
Double_t noVtxzGT10 = sumPv>0. ? sumnoPV * sumZvtx / sumPv : 0.;
return sumEvtNorm - noVtxzGT10;
}
//___________________________________________________________________________
Double_t AliNormalizationCounter::GetNEventsForNorm(Int_t minmultiplicity, Int_t maxmultiplicity, Double_t minspherocity, Double_t maxspherocity){
if(!fMultiplicity || !fSpherocity) {
AliInfo("You must activate both multiplicity and spherocity in the counters to use this method!");
return 0.;
}
TString listofruns = fCounters.GetKeyWords("Multiplicity");
TString listofruns2 = fCounters.GetKeyWords("Spherocity");
TObjArray* arr=listofruns2.Tokenize(",");
Int_t nSphVals=arr->GetEntries();
Int_t nmultbins = maxmultiplicity - minmultiplicity;
Int_t minSphToInteger=minspherocity*fSpherocitySteps;
Int_t maxSphToInteger=maxspherocity*fSpherocitySteps;
Int_t nstbins = maxSphToInteger - minSphToInteger;
Double_t sumnoPV=0., sumZvtx=0., sumPv=0., sumEvtNorm=0.;
for (Int_t ibin=0; ibin<=nmultbins; ibin++) {
if(!listofruns.Contains(Form("%d",ibin+minmultiplicity))) continue;
for (Int_t ibins=0; ibins<nstbins; ibins++) {
Bool_t analyze=kFALSE;
for(Int_t j=0; j<nSphVals; j++) if((((TObjString*)arr->At(j))->String()).Atoi()==(ibins+minSphToInteger)) analyze=kTRUE;
if(!analyze) continue;
if(listofruns2.Contains(",") && !listofruns2.Contains(Form("%d",ibins+minSphToInteger))) continue;
TString suffix;suffix.Form("/Multiplicity:%d/Spherocity:%d",ibin+minmultiplicity,ibins+minSphToInteger);
TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data());
TString noPV;noPV.Form("noPrimaryV%s",suffix.Data());
TString pV;pV.Form("PrimaryV%s",suffix.Data());
TString tbc;tbc.Form("countForNorm%s",suffix.Data());
sumnoPV += GetSum(noPV.Data());
sumZvtx += GetSum(zvtx.Data());
sumPv += GetSum(pV.Data());
sumEvtNorm += GetSum(tbc.Data());
}
}
delete arr;
Double_t noVtxzGT10 = sumPv>0. ? sumnoPV * sumZvtx / sumPv : 0.;
return sumEvtNorm - noVtxzGT10;
}
//___________________________________________________________________________
Double_t AliNormalizationCounter::GetNEventsForNormSpheroOnly(Double_t minspherocity, Double_t maxspherocity){
if(!fSpherocity) {
AliInfo("Sorry, you didn't activate the sphericity in the counter!");
return 0.;
}
TString listofruns = fCounters.GetKeyWords("Spherocity");
TObjArray* arr=listofruns.Tokenize(",");
Int_t nSphVals=arr->GetEntries();
Int_t minSphToInteger=minspherocity*fSpherocitySteps;
Int_t maxSphToInteger=maxspherocity*fSpherocitySteps;
Int_t nstbins = maxSphToInteger - minSphToInteger;
Double_t sumnoPV=0., sumZvtx=0., sumPv=0., sumEvtNorm=0.;
for (Int_t ibin=0; ibin<nstbins; ibin++) {
Bool_t analyze=kFALSE;
for(Int_t j=0; j<nSphVals; j++) if((((TObjString*)arr->At(j))->String()).Atoi()==(ibin+minSphToInteger)) analyze=kTRUE;
if(!analyze) continue;
TString suffix;suffix.Form("/Spherocity:%d",ibin+minSphToInteger);
TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data());
TString noPV;noPV.Form("noPrimaryV%s",suffix.Data());
TString pV;pV.Form("PrimaryV%s",suffix.Data());
TString tbc;tbc.Form("countForNorm%s",suffix.Data());
sumnoPV += GetSum(noPV.Data());
sumZvtx += GetSum(zvtx.Data());
sumPv += GetSum(pV.Data());
sumEvtNorm += GetSum(tbc.Data());
}
delete arr;
Double_t noVtxzGT10 = sumPv>0. ? sumnoPV * sumZvtx / sumPv : 0.;
return sumEvtNorm - noVtxzGT10;
}
//___________________________________________________________________________
Double_t AliNormalizationCounter::GetSum(TString candle,Int_t minmultiplicity, Int_t maxmultiplicity){
// counts events of given type in a given multiplicity range
if(!fMultiplicity) {
AliInfo("Sorry, you didn't activate the multiplicity in the counter!");
return 0.;
}
TString listofruns = fCounters.GetKeyWords("Multiplicity");
Double_t sum=0.;
for (Int_t ibin=minmultiplicity; ibin<=maxmultiplicity; ibin++) {
// cout << " Looking at bin "<< ibin+minmultiplicity<<endl;
if(!listofruns.Contains(Form("%d",ibin))){
// AliInfo(Form("WARNING: %d is not a valid multiplicity number. \n",ibin));
continue;
}
TString suffix=Form("/Multiplicity:%d",ibin);
TString name=Form("%s%s",candle.Data(),suffix.Data());
sum += GetSum(name.Data());
}
return sum;
}
//___________________________________________________________________________
TH1D* AliNormalizationCounter::DrawNEventsForNorm(Bool_t drawRatio){
//usare algebra histos
fCounters.SortRubric("Run");
TString selection;
selection.Form("event:noPrimaryV");
TH1D* hnoPrimV = fCounters.Get("run",selection.Data());
hnoPrimV->Sumw2();
selection.Form("event:zvtxGT10");
TH1D* hzvtx= fCounters.Get("run",selection.Data());
hzvtx->Sumw2();
selection.Form("event:PrimaryV");
TH1D* hPrimV = fCounters.Get("run",selection.Data());
hPrimV->Sumw2();
hzvtx->Multiply(hnoPrimV);
hzvtx->Divide(hPrimV);
selection.Form("event:countForNorm");
TH1D* hCountForNorm = fCounters.Get("run",selection.Data());
hCountForNorm->Sumw2();
hCountForNorm->Add(hzvtx,-1.);
if(drawRatio){
selection.Form("event:triggered");
TH1D* htriggered = fCounters.Get("run",selection.Data());
htriggered->Sumw2();
hCountForNorm->Divide(htriggered);
}
hCountForNorm->DrawClone();
return hCountForNorm;
}
//___________________________________________________________________________
Int_t AliNormalizationCounter::Multiplicity(AliVEvent* event){
Int_t multiplicity = 0;
AliAODEvent *eventAOD = (AliAODEvent*)event;
AliAODTracklets * aodTracklets = (AliAODTracklets*)eventAOD->GetTracklets();
Int_t ntracklets = (Int_t)aodTracklets->GetNumberOfTracklets();
for(Int_t i=0;i<ntracklets; i++){
Double_t theta = aodTracklets->GetTheta(i);
Double_t eta = -TMath::Log( TMath::Tan(theta/2.) ); // check the formula
if(TMath::Abs(eta)<fMultiplicityEtaRange){ // set the proper cut on eta
multiplicity++;
}
}
return multiplicity;
}
//___________________________________________________________________________
void AliNormalizationCounter::FillCounters(TString name, Int_t runNumber, Int_t multiplicity, Double_t spherocity){
Int_t sphToInteger=spherocity*fSpherocitySteps;
if(fMultiplicity && !fSpherocity)
fCounters.Count(Form("Event:%s/Run:%d/Multiplicity:%d",name.Data(),runNumber,multiplicity));
else if(fMultiplicity && fSpherocity)
fCounters.Count(Form("Event:%s/Run:%d/Multiplicity:%d/Spherocity:%d",name.Data(),runNumber,multiplicity,sphToInteger));
else if(!fMultiplicity && fSpherocity)
fCounters.Count(Form("Event:%s/Run:%d/Spherocity:%d",name.Data(),runNumber,sphToInteger));
else
fCounters.Count(Form("Event:%s/Run:%d",name.Data(),runNumber));
return;
}
| 37.39527 | 229 | 0.718087 | wiechula |
cd9593b4fa1fe9c662a604485f9e66d17c879764 | 2,710 | cpp | C++ | control/group_utils.cpp | TheMrButcher/offline-mentor | 15c362710fc993b21ed2d23adfc98e797e2380db | [
"MIT"
] | null | null | null | control/group_utils.cpp | TheMrButcher/offline-mentor | 15c362710fc993b21ed2d23adfc98e797e2380db | [
"MIT"
] | 101 | 2017-03-11T19:09:46.000Z | 2017-09-04T17:37:55.000Z | control/group_utils.cpp | TheMrButcher/offline-mentor | 15c362710fc993b21ed2d23adfc98e797e2380db | [
"MIT"
] | 1 | 2018-03-13T03:47:15.000Z | 2018-03-13T03:47:15.000Z | #include "group_utils.h"
#include "solution_utils.h"
#include "settings.h"
#include <QDir>
namespace {
QList<Group> groups;
QHash<QUuid, const Group*> groupMap;
QHash<QString, QList<const Group*>> userToGroupMap;
const Group BAD_GROUP;
const QList<const Group*> EMPTY_GROUP_LIST;
void updateAll()
{
groupMap.clear();
userToGroupMap.clear();
for (auto& group : groups) {
groupMap[group.id] = &group;
if (group.sortedUserNames.size() != group.userNames.size())
group.sort();
for (const auto& userName : group.userNames)
userToGroupMap[userName].append(&group);
}
updateUserNamesWithoutGroup();
}
void saveGroups()
{
updateAll();
const auto& settings = Settings::instance();
Group::save(groups, settings.localGroupsPath());
if (!settings.groupsPath.isEmpty())
Group::save(groups, settings.groupsPath);
}
}
void loadGroups()
{
groups.clear();
const auto& settings = Settings::instance();
if (!settings.groupsPath.isEmpty()) {
QHash<QUuid, Group> allGroupMap;
if (QDir().exists(settings.groupsPath)) {
QList<Group> remoteGroups = Group::load(settings.groupsPath);
for (const auto& group : remoteGroups)
allGroupMap[group.id] = group;
}
if (QFile(settings.localGroupsPath()).exists()) {
QList<Group> localGroups = Group::load(settings.localGroupsPath());
for (const auto& group : localGroups)
allGroupMap[group.id] = group;
}
groups = allGroupMap.values();
saveGroups();
return;
}
if (QFile(settings.localGroupsPath()).exists())
groups = Group::load(settings.localGroupsPath());
updateAll();
}
const QList<Group>& getGroups()
{
return groups;
}
const Group& getGroup(const QUuid& id)
{
auto it = groupMap.find(id);
if (it == groupMap.end())
return BAD_GROUP;
return *it.value();
}
void removeGroup(const QUuid& id)
{
for (auto it = groups.begin(); it != groups.end(); ++it) {
if (it->id == id) {
groups.erase(it);
saveGroups();
return;
}
}
}
void addGroup(const Group& group)
{
for (auto it = groups.begin(); it != groups.end(); ++it) {
if (it->id == group.id) {
*it = group;
it->sortedUserNames.clear();
saveGroups();
return;
}
}
groups.append(group);
saveGroups();
}
const QList<const Group*>& getGroupsByUserName(QString userName)
{
auto it = userToGroupMap.find(userName);
if (it == userToGroupMap.end())
return EMPTY_GROUP_LIST;
return it.value();
}
| 25.327103 | 79 | 0.597048 | TheMrButcher |
cd98b9ee25b889d835f5249f248b390bbe62a9e3 | 309 | cpp | C++ | Source/Minigame/src/source/ui/Image.cpp | marcspoon07/Project1_Minigame | d8da2892fc97cc2e8310cf9c042d75dcbad4a6ba | [
"MIT"
] | null | null | null | Source/Minigame/src/source/ui/Image.cpp | marcspoon07/Project1_Minigame | d8da2892fc97cc2e8310cf9c042d75dcbad4a6ba | [
"MIT"
] | null | null | null | Source/Minigame/src/source/ui/Image.cpp | marcspoon07/Project1_Minigame | d8da2892fc97cc2e8310cf9c042d75dcbad4a6ba | [
"MIT"
] | null | null | null | #include "../../headers/ui/Image.h"
#include "../../headers/Renderer2D.h"
Image::Image(const char * path, int x, int y)
{
pImageId = Resources::getInstance()->Load<Sprite>(path);
px = x;
py = y;
}
Image::~Image()
{
}
void Image::Render()
{
Renderer2D::getInstance()->RenderGraphic(pImageId, px, py);
} | 16.263158 | 60 | 0.63754 | marcspoon07 |
cd9ae0cdb42387c379c25e46709d5762a5031852 | 2,485 | hpp | C++ | src/container/containerBase.hpp | myrabiedermann/rsmd | 97ccc65dbb3d9d16e5e6a88f256d97a36c511740 | [
"Apache-2.0"
] | 2 | 2021-01-30T00:30:32.000Z | 2021-04-20T11:54:53.000Z | src/container/containerBase.hpp | myrabiedermann/rsmd | 97ccc65dbb3d9d16e5e6a88f256d97a36c511740 | [
"Apache-2.0"
] | null | null | null | src/container/containerBase.hpp | myrabiedermann/rsmd | 97ccc65dbb3d9d16e5e6a88f256d97a36c511740 | [
"Apache-2.0"
] | null | null | null | /************************************************
* *
* rs@md *
* (reactive steps @ molecular dynamics ) *
* *
************************************************/
/*
Copyright 2020 Myra Biedermann
Licensed under the Apache License, Version 2.0
Parts of the code within this file was modified from "container_class_base.hpp"
within github repository https://github.com/simonraschke/vesicle2.git,
licensed under Apache License Version 2.0
Myra Biedermann thankfully acknowledges support
from Simon Raschke.
*/
#pragma once
#include <iterator>
//
// a container base class to derive from
//
// implements all iterator-related functions like begin() / end() etc.
// for use in loops
// as well as container-related operators like [] and ()
//
template<typename T>
struct ContainerBase
{
T data {};
inline auto& operator()(std::size_t i) { return data[i]; };
inline constexpr auto& operator()(std::size_t i) const { return data[i]; };
inline auto& operator[](std::size_t i) { return data[i]; };
inline constexpr auto& operator[](std::size_t i) const { return data[i]; };
inline auto begin() { return std::begin(data); };
inline auto end() { return std::end(data); };
inline auto begin() const { return std::begin(data); };
inline auto end() const { return std::end(data); };
inline auto cbegin() const { return std::cbegin(data); };
inline auto cend() const { return std::cend(data); };
inline auto rbegin() { return std::rbegin(data); };
inline auto rend() { return std::rend(data); };
inline auto rbegin() const { return std::rbegin(data); };
inline auto rend() const { return std::rend(data); };
inline auto crbegin() const { return std::crbegin(data); };
inline auto crend() const { return std::crend(data); };
inline auto size() const { return data.size(); };
inline auto& front() { return *this->begin(); }
inline const auto& front() const { return *this->begin(); }
inline auto& back() { auto tmp = this->end(); --tmp; return *tmp; }
inline const auto& back() const { auto tmp = this->end(); --tmp; return *tmp; }
virtual ~ContainerBase() = default;
protected:
ContainerBase() = default;
}; | 34.513889 | 86 | 0.557344 | myrabiedermann |
cdb7ef72726dc5ee1391185155d0b9b34a71f269 | 13,734 | hpp | C++ | 309551047_np_project3/cgi_server.hpp | Ksld154/Network-Programming | 9b92ba9118ecd11de801e1ac4f062ebcce8386f0 | [
"MIT"
] | 1 | 2021-09-16T01:15:33.000Z | 2021-09-16T01:15:33.000Z | 309551047_np_project3/cgi_server.hpp | Ksld154/Network-Programming | 9b92ba9118ecd11de801e1ac4f062ebcce8386f0 | [
"MIT"
] | null | null | null | 309551047_np_project3/cgi_server.hpp | Ksld154/Network-Programming | 9b92ba9118ecd11de801e1ac4f062ebcce8386f0 | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <boost/asio.hpp>
#include <boost/algorithm/string.hpp>
#define PANEL_ENTRY_NUM 5
#define SERVER_NUM 12
#define TESTCASE_NUM 10
#define ONE_SECOND 1000000
#define MAX_CONSOLE_RESULT_LEN 15000
using boost::asio::ip::tcp;
using namespace std;
string get_server_list() {
string server_list = "";
string domain = ".cs.nctu.edu.tw";
for(int i = 0; i < SERVER_NUM; i++) {
string host = "nplinux" + to_string(i+1);
server_list = server_list + "\"<option value=\"" + host + domain + "\">" + host + "</option>";
}
return server_list;
}
string get_testcase_list() {
string testcase_list = "";
for(int i = 0; i < TESTCASE_NUM; i++) {
string testcase_file = "t" + to_string(i+1) + ".txt";
testcase_list += "<option value=\"" + testcase_file + "\">" + testcase_file + "</option>";
}
return testcase_list;
}
string get_panel_html() {
string panel_http = "";
panel_http = panel_http \
+ "Content-type: text/html\r\n\r\n"
+ "<!DOCTYPE html>"
+ "<html lang=\"en\">"
+ " <head>"
+ " <title>NP Project 3 Panel</title>"
+ " <link"
+ " rel=\"stylesheet\""
+ " href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css\""
+ " integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\""
+ " crossorigin=\"anonymous\""
+ " />"
+ " <link"
+ " href=\"https://fonts.googleapis.com/css?family=Source+Code+Pro\""
+ " rel=\"stylesheet\""
+ " />"
+ " <link"
+ " rel=\"icon\""
+ " type=\"image/png\""
+ " href=\"https://cdn4.iconfinder.com/data/icons/iconsimple-setting-time/512/dashboard-512.png\""
+ " />"
+ " <style>"
+ " * {"
+ " font-family: \'Source Code Pro\', monospace;"
+ " }"
+ " </style>"
+ " </head>"
+ " <body class=\"bg-secondary pt-5\">";
panel_http = panel_http \
+ " <form action=\"console.cgi\" method=\"GET\">"
+ " <table class=\"table mx-auto bg-light\" style=\"width: inherit\">"
+ " <thead class=\"thead-dark\">"
+ " <tr>"
+ " <th scope=\"col\">#</th>"
+ " <th scope=\"col\">Host</th>"
+ " <th scope=\"col\">Port</th>"
+ " <th scope=\"col\">Input File</th>"
+ " </tr>"
+ " </thead>"
+ " <tbody>";
for(int i = 0; i < PANEL_ENTRY_NUM; i++) {
panel_http = panel_http \
+ " <tr>"
+ " <th scope=\"row\" class=\"align-middle\">Session " + to_string(i+1) + "</th>"
+ " <td>"
+ " <div class=\"input-group\">"
+ " <select name=\"h" + to_string(i) + "\" class=\"custom-select\">"
+ " <option></option>";
panel_http += get_server_list();
panel_http = panel_http \
+ " </select>"
+ " <div class=\"input-group-append\">"
+ " <span class=\"input-group-text\">.cs.nctu.edu.tw</span>"
+ " </div>"
+ " </div>"
+ " </td>"
+ " <td>"
+ "<input name=\"p" + to_string(i) + "\" type=\"text\" class=\"form-control\" size=\"5\" />"
+ "</td>"
+ " <td>"
+ "<select name=\"f" + to_string(i) + "\" class=\"custom-select\">"
+ "<option></option>";
panel_http += get_testcase_list();
}
panel_http = panel_http \
+ " <tr>"
+ " <td colspan=\"3\"></td>"
+ " <td>"
+ " <button type=\"submit\" class=\"btn btn-info btn-block\">Run</button>"
+ " </td>"
+ " </tr>"
+ " </tbody>"
+ " </table>"
+ " </form>"
+ " </body>"
+ "</html>";
return panel_http;
}
struct query {
string server_id;
string hostname;
string port;
string input_file;
string server_endpoint;
};
vector<query> parse_query_str(string query_str) {
vector<query> queryList;
cout << query_str << endl;
vector<string> args;
boost::split(args, query_str, boost::is_any_of("&"));
for(int i = 0; i < args.size(); i+=3) {
query q;
q.hostname = args.at(i).substr(args.at(i).find("=") + 1);
q.port = args.at(i+1).substr(args.at(i+1).find("=") + 1);
q.input_file = args.at(i+2).substr(args.at(i+2).find("=") + 1);
// q.server_endpoint = "";
// cout << q.hostname << endl;
// cout << q.port << endl;
// cout << q.input_file << endl;
if(q.hostname != "" && q.port != ""){
queryList.push_back(q);
}
}
return queryList;
}
string get_console_html(vector<query>& queryList) {
string payload = "";
payload = payload \
+ "Content-type: text/html\r\n\r\n"
+ "<!DOCTYPE html>\n"
+ "<html lang=\"en\">\n"
+ " <head>\n"
+ " <meta charset=\"UTF-8\" />\n"
+ " <title>NP Project 3 Sample Console</title>\n"
+ " <link\n"
+ " rel=\"stylesheet\"\n"
+ " href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css\"\n"
+ " integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\"\n"
+ " crossorigin=\"anonymous\"\n"
+ " />\n"
+ " <link\n"
+ " href=\"https://fonts.googleapis.com/css?family=Source+Code+Pro\"\n"
+ " rel=\"stylesheet\"\n"
+ " />\n"
+ " <link\n"
+ " rel=\"icon\"\n"
+ " type=\"image/png\"\n"
+ " href=\"https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678068-terminal-512.png\"\n"
+ " />\n"
+ " <style>\n"
+ " * {\n"
+ " font-family: 'Source Code Pro', monospace;\n"
+ " font-size: 1rem !important;\n"
+ " }\n"
+ " body {\n"
+ " background-color: #212529;\n"
+ " }\n"
+ " pre {\n"
+ " color: #cccccc;\n"
+ " }\n"
+ " b {\n"
+ " color: #01b468;\n"
+ " }\n"
+ " </style>\n"
+ " </head>\n";
payload = payload \
+ "<body>\n"
+ " <table class=\"table table-dark table-bordered\">\n"
+ " <thead>\n"
+ " <tr>\n";
for(vector<query>::iterator q = queryList.begin(); q != queryList.end(); q++) {
string server = q->hostname + ":" + q->port;
payload = payload + " <th scope=\"col\">" + server + "</th>\n";
}
payload = payload \
+ " </tr>\n"
+ " </thead>\n"
+ " <tbody>\n"
+ " <tr>\n";
for(int i = 0; i < queryList.size(); i++) {
string server_id = "s" + to_string(i);
queryList[i].server_id = server_id;
payload = payload + " <td><pre id=\"" + server_id + "\" class=\"mb-0\"></pre></td>\n";
}
payload = payload \
+ " </tr>\n"
+ " </tbody>\n"
+ " </table>\n"
+ " </body>\n"
+ "</html>\n";
return payload;
}
class client
: public std::enable_shared_from_this<client> {
public:
client(boost::asio::io_context& io_context, tcp::socket& browser_socket, string server_id, string input_file)
: socket_(io_context),
browser_socket_(browser_socket),
server_id_(server_id),
input_file_stream_("./test_case/" + input_file),
stopped_(false)
{
memset(recv_data_buf_, '\0', MAX_CONSOLE_RESULT_LEN);
}
void start(tcp::resolver::results_type endpoints) {
endpoints_ = endpoints;
do_connect(endpoints_.begin());
}
void stop() {
stopped_ = true;
input_file_stream_.close();
boost::system::error_code ignore_ec;
socket_.close(ignore_ec);
}
private:
void do_connect(tcp::resolver::results_type::iterator endpoint_iter) {
auto self(shared_from_this());
if(endpoint_iter != endpoints_.end()) {
socket_.async_connect(endpoint_iter->endpoint(),
[this, self](boost::system::error_code ec) {
if(stopped_) return;
else if(!ec) {
do_read();
} else {
printf("Coneect error: <script>console.log(\"%s\")</script>", ec.message().c_str());
fflush(stdout);
socket_.close();
// do_connect();
}
}
);
}
else {
stop();
}
}
void do_read() {
auto self(shared_from_this());
socket_.async_read_some(boost::asio::buffer(recv_data_buf_, MAX_CONSOLE_RESULT_LEN),
[this, self](boost::system::error_code ec, std::size_t length) {
if(stopped_) return;
if(!ec) {
string recv_data = recv_data_buf_;
outputShell(recv_data);
memset(recv_data_buf_, '\0', MAX_CONSOLE_RESULT_LEN);
// If recv_data contains the prompt, then we can start sending next cmd to golden_server
if(recv_data.find("% ") != recv_data.npos) {
do_write();
} else { // otherwise we continue to read server output from current cmd
do_read();
}
} else {
printf("<script>console.log(\"%s\")</script>\n", ec.message().c_str());
fflush(stdout);
stop();
}
}
);
}
void do_write() {
getline(input_file_stream_, cmd_buf_);
cmd_buf_ += '\n';
outputCommand(cmd_buf_);
// usleep(0.2 * ONE_SECOND);
// write cmd to golden_server
auto self(shared_from_this());
boost::asio::async_write(socket_, boost::asio::buffer(cmd_buf_, cmd_buf_.length()),
[this, self](const boost::system::error_code& ec, std::size_t) {
if(stopped_) return;
if(!ec) {
cmd_buf_.clear();
do_read();
} else {
printf("write error: <script>console.log(\"%s\")</script>", ec.message().c_str());
fflush(stdout);
stop();
}
}
);
}
// print cmd_result/welcome_msg to browser's screen
void outputShell(string recv_content) {
char html_content[100000];
string formatted_recv_content = help_format_into_html(recv_content);
sprintf(html_content, "<script>document.getElementById(\'%s\').innerHTML += \'%s\';</script>", server_id_.c_str(), formatted_recv_content.c_str());
string html_string = html_content;
help_print_to_browser(html_string);
}
// print cmd to browser's screen
void outputCommand(string cmd) {
char html_cmd[100000];
string formatted_cmd = help_format_into_html(cmd);
sprintf(html_cmd, "<script>document.getElementById(\'%s\').innerHTML += \'<b>%s</b>\';</script>", server_id_.c_str(), formatted_cmd.c_str());
string html_string = html_cmd;
help_print_to_browser(html_string);
}
string help_format_into_html(string raw_str) {
string formatted_str = raw_str;
boost::replace_all(formatted_str, "\r", "");
boost::replace_all(formatted_str, "&", "&");
boost::replace_all(formatted_str, "\n", "
");
boost::replace_all(formatted_str, "<", "<");
boost::replace_all(formatted_str, ">", ">");
boost::replace_all(formatted_str, "\"", """);
boost::replace_all(formatted_str, "\'", "'");
return formatted_str;
}
void help_print_to_browser(string data) {
boost::asio::async_write(browser_socket_, boost::asio::buffer(data, data.length()),
[this](boost::system::error_code ec, std::size_t) {
if(stopped_) return;
if(!ec) {
}
}
);
}
tcp::resolver::results_type endpoints_;
tcp::socket socket_;
tcp::socket& browser_socket_;
bool stopped_;
char recv_data_buf_[MAX_CONSOLE_RESULT_LEN];
string cmd_buf_;
string server_id_;
ifstream input_file_stream_;
}; | 34.507538 | 156 | 0.457623 | Ksld154 |
cdbb439abbbb903703facacce7234ff385c54718 | 7,122 | cpp | C++ | Tuvok/IO/StkConverter.cpp | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | Tuvok/IO/StkConverter.cpp | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | Tuvok/IO/StkConverter.cpp | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/**
\file StkConverter.cpp
\author Tom Fogal
SCI Institute
University of Utah
*/
#ifndef TUVOK_NO_IO
# include "3rdParty/tiff/tiffio.h"
#else
struct TIFF;
#endif
#include "StkConverter.h"
#include "../Basics/SysTools.h"
#include "../Controller/Controller.h"
using namespace tuvok;
struct stk {
uint32_t x,y,z; ///< dimensions
uint16_t bpp; ///< bits per pixel
uint16_t samples; ///< number of components per pixel
};
static bool stk_read_metadata(TIFF*, struct stk&);
static void stk_read_write_strips(TIFF*, LargeRAWFile&);
StkConverter::StkConverter()
{
m_vConverterDesc = L"Stk Volume (Metamorph)";
#ifndef TUVOK_NO_IO
m_vSupportedExt.push_back(L"STK");
#endif
}
bool
StkConverter::ConvertToRAW(const std::wstring& strSourceFilename,
const std::wstring& strTempDir,
bool, uint64_t& iHeaderSkip,
unsigned& iComponentSize,
uint64_t& iComponentCount,
bool& bConvertEndianess, bool& bSigned,
bool& bIsFloat, UINT64VECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect,
std::wstring& strTitle,
std::wstring& strIntermediateFile,
bool& bDeleteIntermediateFile)
{
#ifdef TUVOK_NO_IO
T_ERROR("Tuvok was not built with IO support!");
return false;
#else
MESSAGE("Attempting to convert stk file: %s", SysTools::toNarrow(strSourceFilename).c_str());
TIFF *tif = TIFFOpen(SysTools::toNarrow(strSourceFilename).c_str(), "r");
if(tif == NULL) {
T_ERROR("Could not open %s", SysTools::toNarrow(strSourceFilename).c_str());
return false;
}
struct stk metadata;
if(!stk_read_metadata(tif, metadata)) {
return false;
}
MESSAGE("%ux%ux%u %s", metadata.x, metadata.y, metadata.z,
SysTools::toNarrow(m_vConverterDesc).c_str());
MESSAGE("%hu bits per component.", metadata.bpp);
MESSAGE("%hu component%s.", metadata.samples,
(metadata.samples == 1) ? "" : "s");
// copy that metadata into Tuvok variables.
iComponentSize = metadata.bpp;
iComponentCount = metadata.samples;
vVolumeSize[0] = metadata.x;
vVolumeSize[1] = metadata.y;
vVolumeSize[2] = metadata.z;
// IIRC libtiff handles all the endian issues for us.
bConvertEndianess = false;
// One might consider setting the values below explicitly (as opposed
// to reading them from somewhere) to be bugs, but we're not quite
// sure where to read these from. In any case, we don't have any
// data for which these settings are invalid.
bSigned = false;
bIsFloat = false;
vVolumeAspect[0] = 1;
vVolumeAspect[1] = 1;
vVolumeAspect[2] = 1;
strTitle = L"STK Volume";
// Create an intermediate file to hold the data.
iHeaderSkip = 0;
strIntermediateFile = strTempDir +
SysTools::GetFilename(strSourceFilename) + L".binary";
LargeRAWFile binary(strIntermediateFile);
binary.Create(iComponentSize/8 * iComponentCount * vVolumeSize.volume());
if(!binary.IsOpen()) {
T_ERROR("Could not create binary file %s", SysTools::toNarrow(strIntermediateFile).c_str());
TIFFClose(tif);
return false;
}
// Populate the intermediate file. We just run through each strip and write
// it out; technically, this is not kosher for Tuvok, since a single strip
// might exceed INCORESIZE. That said, I've never seen a strip which is
// larger than 8192 bytes.
stk_read_write_strips(tif, binary);
bDeleteIntermediateFile = true;
binary.Close();
TIFFClose(tif);
return true;
#endif
}
// unimplemented!
bool
StkConverter::ConvertToNative(const std::wstring&, const std::wstring&,
uint64_t, unsigned, uint64_t, bool, bool, UINT64VECTOR3,
FLOATVECTOR3, bool, bool)
{
return false;
}
static bool
stk_read_metadata(TIFF* tif, struct stk& metadata)
{
#ifdef TUVOK_NO_IO
return false;
#else
// read the number of bits per component from the tiff tag.
TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &metadata.bpp);
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &metadata.x);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &metadata.y);
// It's common for Stk files not to easily give the depth.
if(TIFFGetField(tif, TIFFTAG_IMAGEDEPTH, &metadata.z) == 0) {
// Depth not available as a tag; have to read it from the stk metadata.
// In particular, we'll look up the UIC3Tag and count the number of values
// in there.
const ttag_t uic3tag = (ttag_t) 33630; // the tag is private.
uint32_t count;
void *data;
if(TIFFGetField(tif, uic3tag, &count, &data) == 0) {
return false; // UIC3 tag does not exist; this is not a stk.
}
// The data actually gives the per-slice spacing .. but we just ignore
// that. All we care about is how many slices there are.
metadata.z = count;
}
metadata.samples = 1;
TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &metadata.samples);
return true;
#endif
}
static void
stk_read_write_strips(TIFF* tif, LargeRAWFile& raw)
{
#ifndef TUVOK_NO_IO
const tstrip_t n_strips = TIFFNumberOfStrips(tif);
tdata_t buf = static_cast<tdata_t>(_TIFFmalloc(TIFFStripSize(tif)));
for(tstrip_t s=0; s < n_strips; ++s) {
/// @todo FIXME: don't assume the strip is raw; could be encoded.
/// There's a `compression scheme' tag which probably details this.
tsize_t n_bytes = TIFFReadRawStrip(tif, s, buf, static_cast<tsize_t>(-1));
raw.WriteRAW(static_cast<unsigned char*>(buf), n_bytes);
}
_TIFFfree(buf);
#endif
}
| 35.788945 | 97 | 0.663016 | JensDerKrueger |
cdbd521d24966c84c7653910de392753f21ad316 | 301 | cpp | C++ | list9_9/main.cpp | rimever/SuraSuraCPlus | acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899 | [
"MIT"
] | null | null | null | list9_9/main.cpp | rimever/SuraSuraCPlus | acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899 | [
"MIT"
] | null | null | null | list9_9/main.cpp | rimever/SuraSuraCPlus | acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
using namespace std;
int main() {
string s;
ifstream fin("myFile.txt");
if (!fin.is_open()) {
cout << "ファイルをオープンできません!";
return 1;
}
while (getline(fin, s)) {
cout << s << endl;
}
fin.close();
return 0;
} | 16.722222 | 34 | 0.521595 | rimever |
cdbeb95aaab15164aa4bfea1701a86cd6bf4de32 | 4,674 | cpp | C++ | 2018/2018050703.cpp | maku693/daily-snippets | 53e3a516eeb293b3c11055db1b87d54284e6ac52 | [
"MIT"
] | null | null | null | 2018/2018050703.cpp | maku693/daily-snippets | 53e3a516eeb293b3c11055db1b87d54284e6ac52 | [
"MIT"
] | null | null | null | 2018/2018050703.cpp | maku693/daily-snippets | 53e3a516eeb293b3c11055db1b87d54284e6ac52 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <utility>
#include <variant>
#include <vector>
enum class token_type {
paren_open,
paren_close,
period,
literal_number,
symbol,
};
std::ostream &operator<<(std::ostream &os, const token_type &type) noexcept {
switch (type) {
case token_type::paren_open:
os << "paren_open";
break;
case token_type::paren_close:
os << "paren_close";
break;
case token_type::period:
os << "period";
break;
case token_type::literal_number:
os << "literal_number";
break;
case token_type::symbol:
os << "symbol";
break;
default:
break;
}
return os;
}
struct token {
token_type type;
std::string str;
};
std::ostream &operator<<(std::ostream &os, const token &token) noexcept {
return os << "type: " << token.type << ",\tstr: " << token.str;
}
class tokenizer {
public:
tokenizer() = delete;
explicit tokenizer(std::string &&) noexcept;
std::vector<token> tokenize() noexcept;
private:
const std::string src;
std::string::const_iterator head;
std::string buf;
std::vector<token> tokens;
bool is_whitespace() noexcept;
bool is_paren_open() noexcept;
bool is_paren_close() noexcept;
bool is_period() noexcept;
bool is_digit() noexcept;
bool is_symbol() noexcept;
void whitespace() noexcept;
void paren_open() noexcept;
void paren_close() noexcept;
void period() noexcept;
void literal_number() noexcept;
void symbol() noexcept;
char peek() noexcept;
void consume() noexcept;
void flush() noexcept;
};
tokenizer::tokenizer(std::string &&src_) noexcept
: src(src_), head(src.cbegin()) {}
std::vector<token> tokenizer::tokenize() noexcept {
while (head < src.cend()) {
whitespace();
paren_open();
paren_close();
period();
literal_number();
symbol();
}
return tokens;
}
bool tokenizer::is_whitespace() noexcept {
std::array<char, 10> candidates{' ', '\f', '\n', '\r', '\t', '\v'};
const auto result = std::find(candidates.cbegin(), candidates.cend(), peek());
return result != candidates.cend();
}
bool tokenizer::is_paren_open() noexcept { return peek() == '('; }
bool tokenizer::is_paren_close() noexcept { return peek() == ')'; }
bool tokenizer::is_period() noexcept { return peek() == '.'; }
bool tokenizer::is_digit() noexcept {
std::array<char, 10> candidates{'0', '1', '2', '3', '4',
'5', '6', '7', '8', '9'};
const auto result = std::find(candidates.cbegin(), candidates.cend(), peek());
return result != candidates.cend();
}
bool tokenizer::is_symbol() noexcept {
return !is_whitespace() && !is_paren_open() && !is_paren_close() &&
!is_digit();
}
void tokenizer::whitespace() noexcept {
while (is_whitespace()) {
consume();
}
if (!buf.empty()) {
flush();
}
}
void tokenizer::paren_open() noexcept {
if (is_paren_open()) {
consume();
tokens.emplace_back(token{token_type::paren_open, buf});
flush();
}
}
void tokenizer::paren_close() noexcept {
if (is_paren_close()) {
consume();
tokens.emplace_back(token{token_type::paren_close, buf});
flush();
}
}
void tokenizer::period() noexcept {
if (is_period()) {
consume();
tokens.emplace_back(token{token_type::period, buf});
flush();
}
}
void tokenizer::literal_number() noexcept {
while (is_digit()) {
consume();
}
if (!buf.empty()) {
tokens.emplace_back(token{token_type::literal_number, buf});
flush();
}
}
void tokenizer::symbol() noexcept {
while (is_symbol()) {
consume();
}
if (!buf.empty()) {
tokens.emplace_back(token{token_type::symbol, buf});
flush();
}
}
char tokenizer::peek() noexcept { return *head; }
void tokenizer::consume() noexcept {
buf.push_back(peek());
head++;
}
void tokenizer::flush() noexcept { buf.clear(); }
std::vector<token> tokenize(std::string &&str) noexcept {
tokenizer tokenizer(std::forward<std::string>(str));
return tokenizer.tokenize();
}
// class list;
// class atom;
// using expression = std::variant<list, atom>;
// class parser {
// public:
// parser() = delete;
// explicit parser(std::vector<token> &&) noexcept;
// private:
// std::vector<token>::const_iterator head;
// };
// std::vector<expression> parse(std::string &&str) noexcept { return {}; }
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cerr << "error: no program provided\n";
return 1;
}
const auto tokenize_result = tokenize(argv[1]);
std::cerr << "tokens: " << std::endl;
for (const auto &token : tokenize_result) {
std::cerr << token << std::endl;
}
}
| 21.638889 | 80 | 0.633077 | maku693 |
cdc02ba4eb63cdf0f9ef1210a7169eb0f98b89e5 | 1,950 | hpp | C++ | EasySDL-objects.hpp | dido11/EasySDL | dda4e325fb1735ae03f13dd75d4a2c53fba36a97 | [
"MIT"
] | 1 | 2021-03-29T05:47:18.000Z | 2021-03-29T05:47:18.000Z | EasySDL-objects.hpp | dido11/EasySDL | dda4e325fb1735ae03f13dd75d4a2c53fba36a97 | [
"MIT"
] | null | null | null | EasySDL-objects.hpp | dido11/EasySDL | dda4e325fb1735ae03f13dd75d4a2c53fba36a97 | [
"MIT"
] | null | null | null | #ifndef EASYSDL_OBJECTS_H
#define EASYSDL_OBJECTS_H
#include "EasySDL.hpp"
namespace objects
{
struct Area
{
int h;
int w;
int x=0, y=0;
map<string, double> values;
SDL_Surface * area=NULL;
void areaPlace(SDL_Surface *surf, bool autoDestroySurface, int x, int y, int x0=x_left, int y0=y_top, double angle=0, double scale=1);;
void place();
void place(int x0, int y0, double angle=0, double scale=1);
Area();
void init(int _w, int _h);
Area(int _h, int _w);
~Area();
void ignoreColor(int r, int g, int b);
};
struct BasicArea : Area
{
bool isFocused(int _x, int _y);
BasicArea(int _h, int _w);
BasicArea();
};
struct Button : Area
{
bool over=false;
string txt="";
void (*action)(int, int)=NULL; // x, y
void (*drawContent)(Button*)=NULL;
bool isFocused(int _x, int _y);
void build();
void press(int screenX, int screenY);
};
/**
This is a structure for a button.
It use a "customPart" struct made by you
the "customPart" struct must contain :
- bool isInside(int x, int y) where (0, 0) is the top-left corner of the window/container
this func must tell if the x and y coords are inside the button
- void show()
this func will be used by the container to blit it.
It must blit something on "dest" his x0 will be in x, and his y0 will be in y.
- void clic(int x, int y) where (0, 0) is the top-left corner of the window/container
**/
/*template<class customPart> struct Button : customPart
{
bool over=false;
int x, y;
int h, w;
int x0, y0;
SDL_Surface *dest;
//bool isInside(int screenX, int screenY);
//void show();
//void clic(int screenX, int screenY);
};*/
struct Scrollable : Area
{
BasicArea content;
int deltaY=0;
int defilementSpeed=5;
bool isFocused(int _x, int _y);
void initContent(int _h);
void shiftDown();
void shiftUp();
void build();
Scrollable();
};
}
#endif // EASYSDL_OBJECTS_H
| 21.910112 | 137 | 0.65641 | dido11 |
02cb3aad25d526cb47685b3fbb34bb04b32c4f37 | 579 | cpp | C++ | Assignment 4/Assingnment 4/Assingnment 4/NegateBlue.cpp | justin-harper/cs122 | 83949bc097cf052ffe6b8bd82002377af4d9cede | [
"MIT"
] | null | null | null | Assignment 4/Assingnment 4/Assingnment 4/NegateBlue.cpp | justin-harper/cs122 | 83949bc097cf052ffe6b8bd82002377af4d9cede | [
"MIT"
] | null | null | null | Assignment 4/Assingnment 4/Assingnment 4/NegateBlue.cpp | justin-harper/cs122 | 83949bc097cf052ffe6b8bd82002377af4d9cede | [
"MIT"
] | null | null | null | /*
Assignment: 4
Description: Paycheck Calculator
Author: Justin Harper
WSU ID: 10696738 Completion Time: 4hrs
In completing this program, I received help from the following people:
myself
version 1.0 (major relese) I am happy with this version!
*/
#include "NegateBlue.h"
using namespace std;
//image processor to negate blue
void NegateBlue::processImage(vector<Point>& points)
{
//pretty stright forward just set the blue value of each pixle to 255 - blue value
for (int i = 0; i < points.size(); i++)
{
points[i].setBlue(255 - points[i].getBlue());
}
return;
} | 19.965517 | 83 | 0.727116 | justin-harper |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.