hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2aa45eb5782d7f52fe663b4119150edaa5203635 | 4,918 | hpp | C++ | cannon/ml/piecewise_lstd.hpp | cannontwo/cannon | 4be79f3a6200d1a3cd26c28c8f2250dbdf08f267 | [
"MIT"
] | null | null | null | cannon/ml/piecewise_lstd.hpp | cannontwo/cannon | 4be79f3a6200d1a3cd26c28c8f2250dbdf08f267 | [
"MIT"
] | 46 | 2021-01-12T23:03:52.000Z | 2021-10-01T17:29:01.000Z | cannon/ml/piecewise_lstd.hpp | cannontwo/cannon | 4be79f3a6200d1a3cd26c28c8f2250dbdf08f267 | [
"MIT"
] | null | null | null | #ifndef CANNON_ML_PIECEWISE_LSTD_H
#define CANNON_ML_PIECEWISE_LSTD_H
/*!
* \file cannon/ml/piecewise_lstd.hpp
* \brief File containing PiecewiseLSTDFilter class definition.
*/
#include <Eigen/Core>
using namespace Eigen;
namespace cannon {
namespace ml {
/*!
* \brief Class representing a Least-Squares Temporal Difference (LSTD)
* approximator using a feature set that produces a piecewise-affine value
* function approximation. This is for use in reinforcement learning algorithms.
*/
class PiecewiseLSTDFilter {
public:
PiecewiseLSTDFilter() = delete;
/*!
* \brief Constructor taking state space dimension, number of affine
* regions, and discount factor.
*/
PiecewiseLSTDFilter(unsigned int in_dim, unsigned int num_refs,
double discount_factor, double alpha = 1.0)
: in_dim_(in_dim + 1), param_dim_(in_dim_ * num_refs),
num_refs_(num_refs), discount_factor_(discount_factor),
alpha_(alpha),
a_inv_(MatrixXd::Identity(param_dim_, param_dim_) * alpha_),
b_(VectorXd::Zero(param_dim_)),
theta_(VectorXd::Zero(param_dim_)) {}
/*!
* \brief Update this approximation in light of a single data point,
* which is a transition from one state to another with associated
* reward.
*
* \param in_vec Feature vector for first state.
* \param next_in_vec Feature vector for next state.
* \param idx Region index for first state.
* \param next_idx Region index for next state.
* \param reward Reward associated with this state transition.
*/
void process_datum(const VectorXd &in_vec, const VectorXd &next_in_vec,
unsigned int idx, unsigned int next_idx,
double reward);
/*!
* \brief Get the matrix representing the linear portion of the local,
* affine approximation in the region with for the input index.
*
* \param idx Region index
*
* \returns Estimated local linear approximation parameter matrix.
*/
VectorXd get_mat(unsigned int idx);
/*!
* \brief Predict the value of the input state using the estimated
* piecewise-affine value function.
*
* \param in_vec Feature vector for the state.
* \param idx Region index of the state.
*
* \returns Value function prediction.
*/
double predict(const VectorXd& in_vec, unsigned int idx);
/*!
* \brief Reset this value function approximation.
*/
void reset();
private:
/*!
* \brief Make internal feature vector for the input state in the
* region with the input index.
*
* \param in_vec Input features for state.
* \param idx Region index for the state.
*
* \returns Internal feature representation leading to piecewise-affine
* function.
*/
RowVectorXd make_feature_vec_(VectorXd in_vec, unsigned int idx) const;
/*!
* \brief Update approximation of the linear portion of the LSTD filter
* given a particular state transition.
*
* \param feat Internal feature vector of the first state.
* \param next_feat Internal feature vector of the next state.
*/
void update_a_inv_(const RowVectorXd& feat, const RowVectorXd& next_feat);
/*!
* \brief Update approximation of the vector portion of the LSTD filter.
*
* \param feat Internal feature vector of the first state.
* \param next_feat Internal feature vector of the next state.
*/
void update_b_(const RowVectorXd& feat, double reward);
/*!
* \brief Update parameter vector theta, if necessary. This lazy
* evaluation can save time if multiple value function updates occur
* between predictions.
*/
void check_theta_();
// Parameters
unsigned int in_dim_; //!< Dimension of input
unsigned int param_dim_; //!< Dimension of internal feature space
unsigned int num_refs_; //!< Number of linear regions
double discount_factor_; //!< Discount factor for value function
double alpha_; //!< L2 regularization parameter
// Matrices
MatrixXd a_inv_; //!< Linear portion of LSTD filter
VectorXd b_; //!< Vector portion of LSTD filter
VectorXd theta_; //!< Parameters of value function approximation
bool theta_updated_ = false; //!< Whether theta has been updated since last A, b update
};
} // namespace ml
} // namespace cannon
#endif /* ifndef CANNON_ML_PIECEWISE_LSTD_H */
| 36.977444 | 95 | 0.618747 | [
"vector"
] |
2aa723619b75d2e254a870e377ec83e6d9df9127 | 37,330 | cpp | C++ | src/gpu/gl/GrGLProgram.cpp | coltorchen/android-skia | 91bb0c6f4224715ab78e3f64ba471a42d5d5a307 | [
"BSD-3-Clause"
] | 2 | 2017-05-19T08:53:12.000Z | 2017-08-28T11:59:26.000Z | src/gpu/gl/GrGLProgram.cpp | coltorchen/android-skia | 91bb0c6f4224715ab78e3f64ba471a42d5d5a307 | [
"BSD-3-Clause"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | src/gpu/gl/GrGLProgram.cpp | coltorchen/android-skia | 91bb0c6f4224715ab78e3f64ba471a42d5d5a307 | [
"BSD-3-Clause"
] | 2 | 2017-08-09T09:03:23.000Z | 2020-05-26T09:14:49.000Z | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrGLProgram.h"
#include "GrAllocator.h"
#include "GrEffect.h"
#include "GrGLEffect.h"
#include "GrGpuGL.h"
#include "GrGLShaderVar.h"
#include "GrBackendEffectFactory.h"
#include "SkTrace.h"
#include "SkXfermode.h"
#include "SkRTConf.h"
SK_DEFINE_INST_COUNT(GrGLProgram)
#define GL_CALL(X) GR_GL_CALL(fContextInfo.interface(), X)
#define GL_CALL_RET(R, X) GR_GL_CALL_RET(fContextInfo.interface(), R, X)
SK_CONF_DECLARE(bool, c_PrintShaders, "gpu.printShaders", false, "Print the source code for all shaders generated.");
#define COL_ATTR_NAME "aColor"
#define COV_ATTR_NAME "aCoverage"
#define EDGE_ATTR_NAME "aEdge"
namespace {
inline void tex_attr_name(int coordIdx, SkString* s) {
*s = "aTexCoord";
s->appendS32(coordIdx);
}
inline const char* declared_color_output_name() { return "fsColorOut"; }
inline const char* dual_source_output_name() { return "dualSourceOut"; }
}
GrGLProgram* GrGLProgram::Create(const GrGLContextInfo& gl,
const Desc& desc,
const GrEffectStage* stages[]) {
GrGLProgram* program = SkNEW_ARGS(GrGLProgram, (gl, desc, stages));
if (!program->succeeded()) {
delete program;
program = NULL;
}
return program;
}
GrGLProgram::GrGLProgram(const GrGLContextInfo& gl,
const Desc& desc,
const GrEffectStage* stages[])
: fContextInfo(gl)
, fUniformManager(gl) {
fDesc = desc;
fVShaderID = 0;
fGShaderID = 0;
fFShaderID = 0;
fProgramID = 0;
fViewMatrix = SkMatrix::InvalidMatrix();
fViewportSize.set(-1, -1);
fColor = GrColor_ILLEGAL;
fColorFilterColor = GrColor_ILLEGAL;
fRTHeight = -1;
for (int s = 0; s < GrDrawState::kNumStages; ++s) {
fEffects[s] = NULL;
}
this->genProgram(stages);
}
GrGLProgram::~GrGLProgram() {
if (fVShaderID) {
GL_CALL(DeleteShader(fVShaderID));
}
if (fGShaderID) {
GL_CALL(DeleteShader(fGShaderID));
}
if (fFShaderID) {
GL_CALL(DeleteShader(fFShaderID));
}
if (fProgramID) {
GL_CALL(DeleteProgram(fProgramID));
}
for (int i = 0; i < GrDrawState::kNumStages; ++i) {
delete fEffects[i];
}
}
void GrGLProgram::abandon() {
fVShaderID = 0;
fGShaderID = 0;
fFShaderID = 0;
fProgramID = 0;
}
void GrGLProgram::overrideBlend(GrBlendCoeff* srcCoeff,
GrBlendCoeff* dstCoeff) const {
switch (fDesc.fDualSrcOutput) {
case Desc::kNone_DualSrcOutput:
break;
// the prog will write a coverage value to the secondary
// output and the dst is blended by one minus that value.
case Desc::kCoverage_DualSrcOutput:
case Desc::kCoverageISA_DualSrcOutput:
case Desc::kCoverageISC_DualSrcOutput:
*dstCoeff = (GrBlendCoeff)GrGpu::kIS2C_GrBlendCoeff;
break;
default:
GrCrash("Unexpected dual source blend output");
break;
}
}
namespace {
// given two blend coeffecients determine whether the src
// and/or dst computation can be omitted.
inline void need_blend_inputs(SkXfermode::Coeff srcCoeff,
SkXfermode::Coeff dstCoeff,
bool* needSrcValue,
bool* needDstValue) {
if (SkXfermode::kZero_Coeff == srcCoeff) {
switch (dstCoeff) {
// these all read the src
case SkXfermode::kSC_Coeff:
case SkXfermode::kISC_Coeff:
case SkXfermode::kSA_Coeff:
case SkXfermode::kISA_Coeff:
*needSrcValue = true;
break;
default:
*needSrcValue = false;
break;
}
} else {
*needSrcValue = true;
}
if (SkXfermode::kZero_Coeff == dstCoeff) {
switch (srcCoeff) {
// these all read the dst
case SkXfermode::kDC_Coeff:
case SkXfermode::kIDC_Coeff:
case SkXfermode::kDA_Coeff:
case SkXfermode::kIDA_Coeff:
*needDstValue = true;
break;
default:
*needDstValue = false;
break;
}
} else {
*needDstValue = true;
}
}
/**
* Create a blend_coeff * value string to be used in shader code. Sets empty
* string if result is trivially zero.
*/
inline void blend_term_string(SkString* str, SkXfermode::Coeff coeff,
const char* src, const char* dst,
const char* value) {
switch (coeff) {
case SkXfermode::kZero_Coeff: /** 0 */
*str = "";
break;
case SkXfermode::kOne_Coeff: /** 1 */
*str = value;
break;
case SkXfermode::kSC_Coeff:
str->printf("(%s * %s)", src, value);
break;
case SkXfermode::kISC_Coeff:
str->printf("((%s - %s) * %s)", GrGLSLOnesVecf(4), src, value);
break;
case SkXfermode::kDC_Coeff:
str->printf("(%s * %s)", dst, value);
break;
case SkXfermode::kIDC_Coeff:
str->printf("((%s - %s) * %s)", GrGLSLOnesVecf(4), dst, value);
break;
case SkXfermode::kSA_Coeff: /** src alpha */
str->printf("(%s.a * %s)", src, value);
break;
case SkXfermode::kISA_Coeff: /** inverse src alpha (i.e. 1 - sa) */
str->printf("((1.0 - %s.a) * %s)", src, value);
break;
case SkXfermode::kDA_Coeff: /** dst alpha */
str->printf("(%s.a * %s)", dst, value);
break;
case SkXfermode::kIDA_Coeff: /** inverse dst alpha (i.e. 1 - da) */
str->printf("((1.0 - %s.a) * %s)", dst, value);
break;
default:
GrCrash("Unexpected xfer coeff.");
break;
}
}
/**
* Adds a line to the fragment shader code which modifies the color by
* the specified color filter.
*/
void add_color_filter(SkString* fsCode, const char * outputVar,
SkXfermode::Coeff uniformCoeff,
SkXfermode::Coeff colorCoeff,
const char* filterColor,
const char* inColor) {
SkString colorStr, constStr;
blend_term_string(&colorStr, colorCoeff, filterColor, inColor, inColor);
blend_term_string(&constStr, uniformCoeff, filterColor, inColor, filterColor);
fsCode->appendf("\t%s = ", outputVar);
GrGLSLAdd4f(fsCode, colorStr.c_str(), constStr.c_str());
fsCode->append(";\n");
}
}
bool GrGLProgram::genEdgeCoverage(SkString* coverageVar,
GrGLShaderBuilder* builder) const {
if (fDesc.fVertexLayout & GrDrawState::kEdge_VertexLayoutBit) {
const char *vsName, *fsName;
builder->addVarying(kVec4f_GrSLType, "Edge", &vsName, &fsName);
builder->fVSAttrs.push_back().set(kVec4f_GrSLType,
GrGLShaderVar::kAttribute_TypeModifier,
EDGE_ATTR_NAME);
builder->fVSCode.appendf("\t%s = " EDGE_ATTR_NAME ";\n", vsName);
switch (fDesc.fVertexEdgeType) {
case GrDrawState::kHairLine_EdgeType:
builder->fFSCode.appendf("\tfloat edgeAlpha = abs(dot(vec3(%s.xy,1), %s.xyz));\n", builder->fragmentPosition(), fsName);
builder->fFSCode.append("\tedgeAlpha = max(1.0 - edgeAlpha, 0.0);\n");
break;
case GrDrawState::kQuad_EdgeType:
builder->fFSCode.append("\tfloat edgeAlpha;\n");
// keep the derivative instructions outside the conditional
builder->fFSCode.appendf("\tvec2 duvdx = dFdx(%s.xy);\n", fsName);
builder->fFSCode.appendf("\tvec2 duvdy = dFdy(%s.xy);\n", fsName);
builder->fFSCode.appendf("\tif (%s.z > 0.0 && %s.w > 0.0) {\n", fsName, fsName);
// today we know z and w are in device space. We could use derivatives
builder->fFSCode.appendf("\t\tedgeAlpha = min(min(%s.z, %s.w) + 0.5, 1.0);\n", fsName, fsName);
builder->fFSCode.append ("\t} else {\n");
builder->fFSCode.appendf("\t\tvec2 gF = vec2(2.0*%s.x*duvdx.x - duvdx.y,\n"
"\t\t 2.0*%s.x*duvdy.x - duvdy.y);\n",
fsName, fsName);
builder->fFSCode.appendf("\t\tedgeAlpha = (%s.x*%s.x - %s.y);\n", fsName, fsName, fsName);
builder->fFSCode.append("\t\tedgeAlpha = clamp(0.5 - edgeAlpha / length(gF), 0.0, 1.0);\n"
"\t}\n");
if (kES2_GrGLBinding == fContextInfo.binding()) {
builder->fHeader.printf("#extension GL_OES_standard_derivatives: enable\n");
}
break;
case GrDrawState::kHairQuad_EdgeType:
builder->fFSCode.appendf("\tvec2 duvdx = dFdx(%s.xy);\n", fsName);
builder->fFSCode.appendf("\tvec2 duvdy = dFdy(%s.xy);\n", fsName);
builder->fFSCode.appendf("\tvec2 gF = vec2(2.0*%s.x*duvdx.x - duvdx.y,\n"
"\t 2.0*%s.x*duvdy.x - duvdy.y);\n",
fsName, fsName);
builder->fFSCode.appendf("\tfloat edgeAlpha = (%s.x*%s.x - %s.y);\n", fsName, fsName, fsName);
builder->fFSCode.append("\tedgeAlpha = sqrt(edgeAlpha*edgeAlpha / dot(gF, gF));\n");
builder->fFSCode.append("\tedgeAlpha = max(1.0 - edgeAlpha, 0.0);\n");
if (kES2_GrGLBinding == fContextInfo.binding()) {
builder->fHeader.printf("#extension GL_OES_standard_derivatives: enable\n");
}
break;
case GrDrawState::kCircle_EdgeType:
builder->fFSCode.append("\tfloat edgeAlpha;\n");
builder->fFSCode.appendf("\tfloat d = distance(%s.xy, %s.xy);\n", builder->fragmentPosition(), fsName);
builder->fFSCode.appendf("\tfloat outerAlpha = smoothstep(d - 0.5, d + 0.5, %s.z);\n", fsName);
builder->fFSCode.appendf("\tfloat innerAlpha = %s.w == 0.0 ? 1.0 : smoothstep(%s.w - 0.5, %s.w + 0.5, d);\n", fsName, fsName, fsName);
builder->fFSCode.append("\tedgeAlpha = outerAlpha * innerAlpha;\n");
break;
case GrDrawState::kEllipse_EdgeType:
builder->fFSCode.append("\tfloat edgeAlpha;\n");
builder->fFSCode.appendf("\tvec2 offset = (%s.xy - %s.xy);\n", builder->fragmentPosition(), fsName);
builder->fFSCode.appendf("\toffset.y *= %s.w;\n", fsName);
builder->fFSCode.append("\tfloat d = length(offset);\n");
builder->fFSCode.appendf("\tedgeAlpha = smoothstep(d - 0.5, d + 0.5, %s.z);\n", fsName);
break;
default:
GrCrash("Unknown Edge Type!");
break;
}
if (fDesc.fDiscardIfOutsideEdge) {
builder->fFSCode.appendf("\tif (edgeAlpha <= 0.0) {\n\t\tdiscard;\n\t}\n");
}
*coverageVar = "edgeAlpha";
return true;
} else {
coverageVar->reset();
return false;
}
}
void GrGLProgram::genInputColor(GrGLShaderBuilder* builder, SkString* inColor) {
switch (fDesc.fColorInput) {
case GrGLProgram::Desc::kAttribute_ColorInput: {
builder->fVSAttrs.push_back().set(kVec4f_GrSLType,
GrGLShaderVar::kAttribute_TypeModifier,
COL_ATTR_NAME);
const char *vsName, *fsName;
builder->addVarying(kVec4f_GrSLType, "Color", &vsName, &fsName);
builder->fVSCode.appendf("\t%s = " COL_ATTR_NAME ";\n", vsName);
*inColor = fsName;
} break;
case GrGLProgram::Desc::kUniform_ColorInput: {
const char* name;
fUniformHandles.fColorUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
kVec4f_GrSLType, "Color", &name);
*inColor = name;
break;
}
case GrGLProgram::Desc::kTransBlack_ColorInput:
GrAssert(!"needComputedColor should be false.");
break;
case GrGLProgram::Desc::kSolidWhite_ColorInput:
break;
default:
GrCrash("Unknown color type.");
break;
}
}
void GrGLProgram::genUniformCoverage(GrGLShaderBuilder* builder, SkString* inOutCoverage) {
const char* covUniName;
fUniformHandles.fCoverageUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
kVec4f_GrSLType, "Coverage", &covUniName);
if (inOutCoverage->size()) {
builder->fFSCode.appendf("\tvec4 uniCoverage = %s * %s;\n",
covUniName, inOutCoverage->c_str());
*inOutCoverage = "uniCoverage";
} else {
*inOutCoverage = covUniName;
}
}
namespace {
void gen_attribute_coverage(GrGLShaderBuilder* segments,
SkString* inOutCoverage) {
segments->fVSAttrs.push_back().set(kVec4f_GrSLType,
GrGLShaderVar::kAttribute_TypeModifier,
COV_ATTR_NAME);
const char *vsName, *fsName;
segments->addVarying(kVec4f_GrSLType, "Coverage", &vsName, &fsName);
segments->fVSCode.appendf("\t%s = " COV_ATTR_NAME ";\n", vsName);
if (inOutCoverage->size()) {
segments->fFSCode.appendf("\tvec4 attrCoverage = %s * %s;\n",
fsName, inOutCoverage->c_str());
*inOutCoverage = "attrCoverage";
} else {
*inOutCoverage = fsName;
}
}
}
void GrGLProgram::genGeometryShader(GrGLShaderBuilder* segments) const {
#if GR_GL_EXPERIMENTAL_GS
if (fDesc.fExperimentalGS) {
GrAssert(fContextInfo.glslGeneration() >= k150_GrGLSLGeneration);
segments->fGSHeader.append("layout(triangles) in;\n"
"layout(triangle_strip, max_vertices = 6) out;\n");
segments->fGSCode.append("\tfor (int i = 0; i < 3; ++i) {\n"
"\t\tgl_Position = gl_in[i].gl_Position;\n");
if (fDesc.fEmitsPointSize) {
segments->fGSCode.append("\t\tgl_PointSize = 1.0;\n");
}
GrAssert(segments->fGSInputs.count() == segments->fGSOutputs.count());
int count = segments->fGSInputs.count();
for (int i = 0; i < count; ++i) {
segments->fGSCode.appendf("\t\t%s = %s[i];\n",
segments->fGSOutputs[i].getName().c_str(),
segments->fGSInputs[i].getName().c_str());
}
segments->fGSCode.append("\t\tEmitVertex();\n"
"\t}\n"
"\tEndPrimitive();\n");
}
#endif
}
const char* GrGLProgram::adjustInColor(const SkString& inColor) const {
if (inColor.size()) {
return inColor.c_str();
} else {
if (Desc::kSolidWhite_ColorInput == fDesc.fColorInput) {
return GrGLSLOnesVecf(4);
} else {
return GrGLSLZerosVecf(4);
}
}
}
namespace {
// prints a shader using params similar to glShaderSource
void print_shader(GrGLint stringCnt,
const GrGLchar** strings,
GrGLint* stringLengths) {
for (int i = 0; i < stringCnt; ++i) {
if (NULL == stringLengths || stringLengths[i] < 0) {
GrPrintf(strings[i]);
} else {
GrPrintf("%.*s", stringLengths[i], strings[i]);
}
}
}
// Compiles a GL shader, returns shader ID or 0 if failed params have same meaning as glShaderSource
GrGLuint compile_shader(const GrGLContextInfo& gl,
GrGLenum type,
int stringCnt,
const char** strings,
int* stringLengths) {
SK_TRACE_EVENT1("GrGLProgram::CompileShader",
"stringCount", SkStringPrintf("%i", stringCnt).c_str());
GrGLuint shader;
GR_GL_CALL_RET(gl.interface(), shader, CreateShader(type));
if (0 == shader) {
return 0;
}
const GrGLInterface* gli = gl.interface();
GrGLint compiled = GR_GL_INIT_ZERO;
GR_GL_CALL(gli, ShaderSource(shader, stringCnt, strings, stringLengths));
GR_GL_CALL(gli, CompileShader(shader));
GR_GL_CALL(gli, GetShaderiv(shader, GR_GL_COMPILE_STATUS, &compiled));
if (!compiled) {
GrGLint infoLen = GR_GL_INIT_ZERO;
GR_GL_CALL(gli, GetShaderiv(shader, GR_GL_INFO_LOG_LENGTH, &infoLen));
SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger
if (infoLen > 0) {
// retrieve length even though we don't need it to workaround bug in chrome cmd buffer
// param validation.
GrGLsizei length = GR_GL_INIT_ZERO;
GR_GL_CALL(gli, GetShaderInfoLog(shader, infoLen+1,
&length, (char*)log.get()));
print_shader(stringCnt, strings, stringLengths);
GrPrintf("\n%s", log.get());
}
GrAssert(!"Shader compilation failed!");
GR_GL_CALL(gli, DeleteShader(shader));
return 0;
}
return shader;
}
// helper version of above for when shader is already flattened into a single SkString
GrGLuint compile_shader(const GrGLContextInfo& gl, GrGLenum type, const SkString& shader) {
const GrGLchar* str = shader.c_str();
int length = shader.size();
return compile_shader(gl, type, 1, &str, &length);
}
}
// compiles all the shaders from builder and stores the shader IDs
bool GrGLProgram::compileShaders(const GrGLShaderBuilder& builder) {
SkString shader;
builder.getShader(GrGLShaderBuilder::kVertex_ShaderType, &shader);
if (c_PrintShaders) {
GrPrintf(shader.c_str());
GrPrintf("\n");
}
if (!(fVShaderID = compile_shader(fContextInfo, GR_GL_VERTEX_SHADER, shader))) {
return false;
}
if (builder.fUsesGS) {
builder.getShader(GrGLShaderBuilder::kGeometry_ShaderType, &shader);
if (c_PrintShaders) {
GrPrintf(shader.c_str());
GrPrintf("\n");
}
if (!(fGShaderID = compile_shader(fContextInfo, GR_GL_GEOMETRY_SHADER, shader))) {
return false;
}
} else {
fGShaderID = 0;
}
builder.getShader(GrGLShaderBuilder::kFragment_ShaderType, &shader);
if (c_PrintShaders) {
GrPrintf(shader.c_str());
GrPrintf("\n");
}
if (!(fFShaderID = compile_shader(fContextInfo, GR_GL_FRAGMENT_SHADER, shader))) {
return false;
}
return true;
}
bool GrGLProgram::genProgram(const GrEffectStage* stages[]) {
GrAssert(0 == fProgramID);
GrGLShaderBuilder builder(fContextInfo, fUniformManager);
const uint32_t& layout = fDesc.fVertexLayout;
#if GR_GL_EXPERIMENTAL_GS
builder.fUsesGS = fDesc.fExperimentalGS;
#endif
SkXfermode::Coeff colorCoeff, uniformCoeff;
// The rest of transfer mode color filters have not been implemented
if (fDesc.fColorFilterXfermode < SkXfermode::kCoeffModesCnt) {
GR_DEBUGCODE(bool success =)
SkXfermode::ModeAsCoeff(static_cast<SkXfermode::Mode>
(fDesc.fColorFilterXfermode),
&uniformCoeff, &colorCoeff);
GR_DEBUGASSERT(success);
} else {
colorCoeff = SkXfermode::kOne_Coeff;
uniformCoeff = SkXfermode::kZero_Coeff;
}
// no need to do the color filter if coverage is 0. The output color is scaled by the coverage.
// All the dual source outputs are scaled by the coverage as well.
if (Desc::kTransBlack_ColorInput == fDesc.fCoverageInput) {
colorCoeff = SkXfermode::kZero_Coeff;
uniformCoeff = SkXfermode::kZero_Coeff;
}
// If we know the final color is going to be all zeros then we can
// simplify the color filter coefficients. needComputedColor will then
// come out false below.
if (Desc::kTransBlack_ColorInput == fDesc.fColorInput) {
colorCoeff = SkXfermode::kZero_Coeff;
if (SkXfermode::kDC_Coeff == uniformCoeff ||
SkXfermode::kDA_Coeff == uniformCoeff) {
uniformCoeff = SkXfermode::kZero_Coeff;
} else if (SkXfermode::kIDC_Coeff == uniformCoeff ||
SkXfermode::kIDA_Coeff == uniformCoeff) {
uniformCoeff = SkXfermode::kOne_Coeff;
}
}
bool needColorFilterUniform;
bool needComputedColor;
need_blend_inputs(uniformCoeff, colorCoeff,
&needColorFilterUniform, &needComputedColor);
// the dual source output has no canonical var name, have to
// declare an output, which is incompatible with gl_FragColor/gl_FragData.
bool dualSourceOutputWritten = false;
builder.fHeader.append(GrGetGLSLVersionDecl(fContextInfo.binding(),
fContextInfo.glslGeneration()));
GrGLShaderVar colorOutput;
bool isColorDeclared = GrGLSLSetupFSColorOuput(fContextInfo.glslGeneration(),
declared_color_output_name(),
&colorOutput);
if (isColorDeclared) {
builder.fFSOutputs.push_back(colorOutput);
}
const char* viewMName;
fUniformHandles.fViewMatrixUni = builder.addUniform(GrGLShaderBuilder::kVertex_ShaderType,
kMat33f_GrSLType, "ViewM", &viewMName);
builder.fVSCode.appendf("\tvec3 pos3 = %s * vec3(%s, 1);\n"
"\tgl_Position = vec4(pos3.xy, 0, pos3.z);\n",
viewMName, builder.positionAttribute().getName().c_str());
// incoming color to current stage being processed.
SkString inColor;
if (needComputedColor) {
this->genInputColor(&builder, &inColor);
}
// we output point size in the GS if present
if (fDesc.fEmitsPointSize && !builder.fUsesGS){
builder.fVSCode.append("\tgl_PointSize = 1.0;\n");
}
// add texture coordinates that are used to the list of vertex attr decls
SkString texCoordAttrs[GrDrawState::kMaxTexCoords];
for (int t = 0; t < GrDrawState::kMaxTexCoords; ++t) {
if (GrDrawState::VertexUsesTexCoordIdx(t, layout)) {
tex_attr_name(t, texCoordAttrs + t);
builder.fVSAttrs.push_back().set(kVec2f_GrSLType,
GrGLShaderVar::kAttribute_TypeModifier,
texCoordAttrs[t].c_str());
}
}
///////////////////////////////////////////////////////////////////////////
// compute the final color
// if we have color stages string them together, feeding the output color
// of each to the next and generating code for each stage.
if (needComputedColor) {
SkString outColor;
for (int s = 0; s < fDesc.fFirstCoverageStage; ++s) {
if (GrGLEffect::kNoEffectKey != fDesc.fEffectKeys[s]) {
// create var to hold stage result
outColor = "color";
outColor.appendS32(s);
builder.fFSCode.appendf("\tvec4 %s;\n", outColor.c_str());
const char* inCoords;
// figure out what our input coords are
int tcIdx = GrDrawState::VertexTexCoordsForStage(s, layout);
if (tcIdx < 0) {
inCoords = builder.positionAttribute().c_str();
} else {
// must have input tex coordinates if stage is enabled.
GrAssert(texCoordAttrs[tcIdx].size());
inCoords = texCoordAttrs[tcIdx].c_str();
}
builder.setCurrentStage(s);
fEffects[s] = builder.createAndEmitGLEffect(*stages[s],
fDesc.fEffectKeys[s],
inColor.size() ? inColor.c_str() : NULL,
outColor.c_str(),
inCoords,
&fUniformHandles.fSamplerUnis[s]);
builder.setNonStage();
inColor = outColor;
}
}
}
// if have all ones or zeros for the "dst" input to the color filter then we
// may be able to make additional optimizations.
if (needColorFilterUniform && needComputedColor && !inColor.size()) {
GrAssert(Desc::kSolidWhite_ColorInput == fDesc.fColorInput);
bool uniformCoeffIsZero = SkXfermode::kIDC_Coeff == uniformCoeff ||
SkXfermode::kIDA_Coeff == uniformCoeff;
if (uniformCoeffIsZero) {
uniformCoeff = SkXfermode::kZero_Coeff;
bool bogus;
need_blend_inputs(SkXfermode::kZero_Coeff, colorCoeff,
&needColorFilterUniform, &bogus);
}
}
const char* colorFilterColorUniName = NULL;
if (needColorFilterUniform) {
fUniformHandles.fColorFilterUni = builder.addUniform(
GrGLShaderBuilder::kFragment_ShaderType,
kVec4f_GrSLType, "FilterColor",
&colorFilterColorUniName);
}
bool wroteFragColorZero = false;
if (SkXfermode::kZero_Coeff == uniformCoeff &&
SkXfermode::kZero_Coeff == colorCoeff) {
builder.fFSCode.appendf("\t%s = %s;\n",
colorOutput.getName().c_str(),
GrGLSLZerosVecf(4));
wroteFragColorZero = true;
} else if (SkXfermode::kDst_Mode != fDesc.fColorFilterXfermode) {
builder.fFSCode.append("\tvec4 filteredColor;\n");
const char* color = adjustInColor(inColor);
add_color_filter(&builder.fFSCode, "filteredColor", uniformCoeff,
colorCoeff, colorFilterColorUniName, color);
inColor = "filteredColor";
}
///////////////////////////////////////////////////////////////////////////
// compute the partial coverage (coverage stages and edge aa)
SkString inCoverage;
bool coverageIsZero = Desc::kTransBlack_ColorInput == fDesc.fCoverageInput;
// we don't need to compute coverage at all if we know the final shader
// output will be zero and we don't have a dual src blend output.
if (!wroteFragColorZero || Desc::kNone_DualSrcOutput != fDesc.fDualSrcOutput) {
if (!coverageIsZero) {
bool inCoverageIsScalar = this->genEdgeCoverage(&inCoverage, &builder);
switch (fDesc.fCoverageInput) {
case Desc::kSolidWhite_ColorInput:
// empty string implies solid white
break;
case Desc::kAttribute_ColorInput:
gen_attribute_coverage(&builder, &inCoverage);
inCoverageIsScalar = false;
break;
case Desc::kUniform_ColorInput:
this->genUniformCoverage(&builder, &inCoverage);
inCoverageIsScalar = false;
break;
default:
GrCrash("Unexpected input coverage.");
}
SkString outCoverage;
const int& startStage = fDesc.fFirstCoverageStage;
for (int s = startStage; s < GrDrawState::kNumStages; ++s) {
if (fDesc.fEffectKeys[s]) {
// create var to hold stage output
outCoverage = "coverage";
outCoverage.appendS32(s);
builder.fFSCode.appendf("\tvec4 %s;\n", outCoverage.c_str());
const char* inCoords;
// figure out what our input coords are
int tcIdx =
GrDrawState::VertexTexCoordsForStage(s, layout);
if (tcIdx < 0) {
inCoords = builder.positionAttribute().c_str();
} else {
// must have input tex coordinates if stage is
// enabled.
GrAssert(texCoordAttrs[tcIdx].size());
inCoords = texCoordAttrs[tcIdx].c_str();
}
// stages don't know how to deal with a scalar input. (Maybe they should. We
// could pass a GrGLShaderVar)
if (inCoverageIsScalar) {
builder.fFSCode.appendf("\tvec4 %s4 = vec4(%s);\n",
inCoverage.c_str(), inCoverage.c_str());
inCoverage.append("4");
}
builder.setCurrentStage(s);
fEffects[s] = builder.createAndEmitGLEffect(
*stages[s],
fDesc.fEffectKeys[s],
inCoverage.size() ? inCoverage.c_str() : NULL,
outCoverage.c_str(),
inCoords,
&fUniformHandles.fSamplerUnis[s]);
builder.setNonStage();
inCoverage = outCoverage;
}
}
}
if (Desc::kNone_DualSrcOutput != fDesc.fDualSrcOutput) {
builder.fFSOutputs.push_back().set(kVec4f_GrSLType,
GrGLShaderVar::kOut_TypeModifier,
dual_source_output_name());
bool outputIsZero = coverageIsZero;
SkString coeff;
if (!outputIsZero &&
Desc::kCoverage_DualSrcOutput != fDesc.fDualSrcOutput && !wroteFragColorZero) {
if (!inColor.size()) {
outputIsZero = true;
} else {
if (Desc::kCoverageISA_DualSrcOutput == fDesc.fDualSrcOutput) {
coeff.printf("(1 - %s.a)", inColor.c_str());
} else {
coeff.printf("(vec4(1,1,1,1) - %s)", inColor.c_str());
}
}
}
if (outputIsZero) {
builder.fFSCode.appendf("\t%s = %s;\n",
dual_source_output_name(),
GrGLSLZerosVecf(4));
} else {
builder.fFSCode.appendf("\t%s =", dual_source_output_name());
GrGLSLModulate4f(&builder.fFSCode, coeff.c_str(), inCoverage.c_str());
builder.fFSCode.append(";\n");
}
dualSourceOutputWritten = true;
}
}
///////////////////////////////////////////////////////////////////////////
// combine color and coverage as frag color
if (!wroteFragColorZero) {
if (coverageIsZero) {
builder.fFSCode.appendf("\t%s = %s;\n",
colorOutput.getName().c_str(),
GrGLSLZerosVecf(4));
} else {
builder.fFSCode.appendf("\t%s = ", colorOutput.getName().c_str());
GrGLSLModulate4f(&builder.fFSCode, inColor.c_str(), inCoverage.c_str());
builder.fFSCode.append(";\n");
}
}
///////////////////////////////////////////////////////////////////////////
// insert GS
#if GR_DEBUG
this->genGeometryShader(&builder);
#endif
///////////////////////////////////////////////////////////////////////////
// compile and setup attribs and unis
if (!this->compileShaders(builder)) {
return false;
}
if (!this->bindOutputsAttribsAndLinkProgram(builder,
texCoordAttrs,
isColorDeclared,
dualSourceOutputWritten)) {
return false;
}
builder.finished(fProgramID);
this->initSamplerUniforms();
fUniformHandles.fRTHeightUni = builder.getRTHeightUniform();
return true;
}
bool GrGLProgram::bindOutputsAttribsAndLinkProgram(const GrGLShaderBuilder& builder,
SkString texCoordAttrNames[],
bool bindColorOut,
bool bindDualSrcOut) {
GL_CALL_RET(fProgramID, CreateProgram());
if (!fProgramID) {
return false;
}
GL_CALL(AttachShader(fProgramID, fVShaderID));
if (fGShaderID) {
GL_CALL(AttachShader(fProgramID, fGShaderID));
}
GL_CALL(AttachShader(fProgramID, fFShaderID));
if (bindColorOut) {
GL_CALL(BindFragDataLocation(fProgramID, 0, declared_color_output_name()));
}
if (bindDualSrcOut) {
GL_CALL(BindFragDataLocationIndexed(fProgramID, 0, 1, dual_source_output_name()));
}
// Bind the attrib locations to same values for all shaders
GL_CALL(BindAttribLocation(fProgramID,
PositionAttributeIdx(),
builder.positionAttribute().c_str()));
for (int t = 0; t < GrDrawState::kMaxTexCoords; ++t) {
if (texCoordAttrNames[t].size()) {
GL_CALL(BindAttribLocation(fProgramID,
TexCoordAttributeIdx(t),
texCoordAttrNames[t].c_str()));
}
}
GL_CALL(BindAttribLocation(fProgramID, ColorAttributeIdx(), COL_ATTR_NAME));
GL_CALL(BindAttribLocation(fProgramID, CoverageAttributeIdx(), COV_ATTR_NAME));
GL_CALL(BindAttribLocation(fProgramID, EdgeAttributeIdx(), EDGE_ATTR_NAME));
GL_CALL(LinkProgram(fProgramID));
GrGLint linked = GR_GL_INIT_ZERO;
GL_CALL(GetProgramiv(fProgramID, GR_GL_LINK_STATUS, &linked));
if (!linked) {
GrGLint infoLen = GR_GL_INIT_ZERO;
GL_CALL(GetProgramiv(fProgramID, GR_GL_INFO_LOG_LENGTH, &infoLen));
SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger
if (infoLen > 0) {
// retrieve length even though we don't need it to workaround
// bug in chrome cmd buffer param validation.
GrGLsizei length = GR_GL_INIT_ZERO;
GL_CALL(GetProgramInfoLog(fProgramID,
infoLen+1,
&length,
(char*)log.get()));
GrPrintf((char*)log.get());
}
GrAssert(!"Error linking program");
GL_CALL(DeleteProgram(fProgramID));
fProgramID = 0;
return false;
}
return true;
}
void GrGLProgram::initSamplerUniforms() {
GL_CALL(UseProgram(fProgramID));
// We simply bind the uniforms to successive texture units beginning at 0. setData() assumes this
// behavior.
GrGLint texUnitIdx = 0;
for (int s = 0; s < GrDrawState::kNumStages; ++s) {
int numSamplers = fUniformHandles.fSamplerUnis[s].count();
for (int u = 0; u < numSamplers; ++u) {
UniformHandle handle = fUniformHandles.fSamplerUnis[s][u];
if (GrGLUniformManager::kInvalidUniformHandle != handle) {
fUniformManager.setSampler(handle, texUnitIdx);
++texUnitIdx;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
void GrGLProgram::setData(GrGpuGL* gpu) {
const GrDrawState& drawState = gpu->getDrawState();
int rtHeight = drawState.getRenderTarget()->height();
if (GrGLUniformManager::kInvalidUniformHandle != fUniformHandles.fRTHeightUni &&
fRTHeight != rtHeight) {
fUniformManager.set1f(fUniformHandles.fRTHeightUni, SkIntToScalar(rtHeight));
fRTHeight = rtHeight;
}
GrGLint texUnitIdx = 0;
for (int s = 0; s < GrDrawState::kNumStages; ++s) {
if (NULL != fEffects[s]) {
const GrEffectStage& stage = drawState.getStage(s);
GrAssert(NULL != stage.getEffect());
fEffects[s]->setData(fUniformManager, stage);
int numSamplers = fUniformHandles.fSamplerUnis[s].count();
for (int u = 0; u < numSamplers; ++u) {
UniformHandle handle = fUniformHandles.fSamplerUnis[s][u];
if (GrGLUniformManager::kInvalidUniformHandle != handle) {
const GrTextureAccess& access = (*stage.getEffect())->textureAccess(u);
GrGLTexture* texture = static_cast<GrGLTexture*>(access.getTexture());
gpu->bindTexture(texUnitIdx, access.getParams(), texture);
++texUnitIdx;
}
}
}
}
}
| 40.313175 | 146 | 0.550844 | [
"solid"
] |
2ab4384323d6f965ca2446dba426be1657490cae | 18,419 | hpp | C++ | include/base_pxfoundations/foundation/PsMathUtils.hpp | DeanoC/base_pxfoundations | 8150e24a606b184781bf1552e09f17c03e67e501 | [
"BSD-3-Clause"
] | null | null | null | include/base_pxfoundations/foundation/PsMathUtils.hpp | DeanoC/base_pxfoundations | 8150e24a606b184781bf1552e09f17c03e67e501 | [
"BSD-3-Clause"
] | null | null | null | include/base_pxfoundations/foundation/PsMathUtils.hpp | DeanoC/base_pxfoundations | 8150e24a606b184781bf1552e09f17c03e67e501 | [
"BSD-3-Clause"
] | null | null | null | //
// 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 NVIDIA CORPORATION 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 ``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.
//
// Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PSFOUNDATION_PSMATHUTILS_H
#define PSFOUNDATION_PSMATHUTILS_H
#include "foundation/PxPreprocessor.hpp"
#include "foundation/PxTransform.hpp"
#include "foundation/PxMat33.hpp"
#include "Ps.hpp"
#include "PsIntrinsics.hpp"
// General guideline is: if it's an abstract math function, it belongs here.
// If it's a math function where the inputs have specific semantics (e.g.
// separateSwingTwist) it doesn't.
namespace physx {
namespace shdfnd {
/**
\brief sign returns the sign of its argument. The sign of zero is undefined.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 sign(const PxF32 a) {
return intrinsics::sign(a);
}
/**
\brief sign returns the sign of its argument. The sign of zero is undefined.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 sign(const PxF64 a) {
return (a >= 0.0) ? 1.0 : -1.0;
}
/**
\brief sign returns the sign of its argument. The sign of zero is undefined.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxI32 sign(const PxI32 a) {
return (a >= 0) ? 1 : -1;
}
/**
\brief Returns true if the two numbers are within eps of each other.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE bool equals(const PxF32 a, const PxF32 b, const PxF32 eps) {
return (PxAbs(a - b) < eps);
}
/**
\brief Returns true if the two numbers are within eps of each other.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE bool equals(const PxF64 a, const PxF64 b, const PxF64 eps) {
return (PxAbs(a - b) < eps);
}
/**
\brief The floor function returns a floating-point value representing the largest integer that is less than or equal to
x.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 floor(const PxF32 a) {
return floatFloor(a);
}
/**
\brief The floor function returns a floating-point value representing the largest integer that is less than or equal to
x.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 floor(const PxF64 a) {
return ::floor(a);
}
/**
\brief The ceil function returns a single value representing the smallest integer that is greater than or equal to x.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 ceil(const PxF32 a) {
return ::ceilf(a);
}
/**
\brief The ceil function returns a double value representing the smallest integer that is greater than or equal to x.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 ceil(const PxF64 a) {
return ::ceil(a);
}
/**
\brief mod returns the floating-point remainder of x / y.
If the value of y is 0.0, mod returns a quiet NaN.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 mod(const PxF32 x, const PxF32 y) {
return PxF32(::fmodf(x, y));
}
/**
\brief mod returns the floating-point remainder of x / y.
If the value of y is 0.0, mod returns a quiet NaN.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 mod(const PxF64 x, const PxF64 y) {
return ::fmod(x, y);
}
/**
\brief Square.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 sqr(const PxF32 a) {
return a * a;
}
/**
\brief Square.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 sqr(const PxF64 a) {
return a * a;
}
/**
\brief Calculates x raised to the power of y.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 pow(const PxF32 x, const PxF32 y) {
return ::powf(x, y);
}
/**
\brief Calculates x raised to the power of y.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 pow(const PxF64 x, const PxF64 y) {
return ::pow(x, y);
}
/**
\brief Calculates e^n
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 exp(const PxF32 a) {
return ::expf(a);
}
/**
\brief Calculates e^n
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 exp(const PxF64 a) {
return ::exp(a);
}
/**
\brief Calculates 2^n
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 exp2(const PxF32 a) {
return ::expf(a * 0.693147180559945309417f);
}
/**
\brief Calculates 2^n
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 exp2(const PxF64 a) {
return ::exp(a * 0.693147180559945309417);
}
/**
\brief Calculates logarithms.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 logE(const PxF32 a) {
return ::logf(a);
}
/**
\brief Calculates logarithms.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 logE(const PxF64 a) {
return ::log(a);
}
/**
\brief Calculates logarithms.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 log2(const PxF32 a) {
return ::logf(a) / 0.693147180559945309417f;
}
/**
\brief Calculates logarithms.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 log2(const PxF64 a) {
return ::log(a) / 0.693147180559945309417;
}
/**
\brief Calculates logarithms.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 log10(const PxF32 a) {
return ::log10f(a);
}
/**
\brief Calculates logarithms.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 log10(const PxF64 a) {
return ::log10(a);
}
/**
\brief Converts degrees to radians.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 degToRad(const PxF32 a) {
return 0.01745329251994329547f * a;
}
/**
\brief Converts degrees to radians.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 degToRad(const PxF64 a) {
return 0.01745329251994329547 * a;
}
/**
\brief Converts radians to degrees.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 radToDeg(const PxF32 a) {
return 57.29577951308232286465f * a;
}
/**
\brief Converts radians to degrees.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF64 radToDeg(const PxF64 a) {
return 57.29577951308232286465 * a;
}
//! \brief compute sine and cosine at the same time. There is a 'fsincos' on PC that we probably want to use here
PX_CUDA_CALLABLE PX_FORCE_INLINE void sincos(const PxF32 radians, PxF32 &sin, PxF32 &cos) {
/* something like:
_asm fld Local
_asm fsincos
_asm fstp LocalCos
_asm fstp LocalSin
*/
sin = PxSin(radians);
cos = PxCos(radians);
}
/**
\brief uniform random number in [a,b]
*/
PX_FORCE_INLINE PxI32 rand(const PxI32 a, const PxI32 b) {
return a + PxI32(::rand() % (b - a + 1));
}
/**
\brief uniform random number in [a,b]
*/
PX_FORCE_INLINE PxF32 rand(const PxF32 a, const PxF32 b) {
return a + (b - a) * ::rand() / RAND_MAX;
}
//! \brief return angle between two vectors in radians
PX_CUDA_CALLABLE PX_FORCE_INLINE PxF32 angle(const PxVec3 &v0, const PxVec3 &v1) {
const PxF32 cos = v0.dot(v1); // |v0|*|v1|*Cos(Angle)
const PxF32 sin = (v0.cross(v1)).magnitude(); // |v0|*|v1|*Sin(Angle)
return PxAtan2(sin, cos);
}
//! If possible use instead fsel on the dot product /*fsel(d.dot(p),onething,anotherthing);*/
//! Compares orientations (more readable, user-friendly function)
PX_CUDA_CALLABLE PX_FORCE_INLINE bool sameDirection(const PxVec3 &d, const PxVec3 &p) {
return d.dot(p) >= 0.0f;
}
//! Checks 2 values have different signs
PX_CUDA_CALLABLE PX_FORCE_INLINE IntBool differentSign(PxReal f0, PxReal f1) {
#if !PX_EMSCRIPTEN
union {
PxU32 u;
PxReal f;
} u1, u2;
u1.f = f0;
u2.f = f1;
return IntBool((u1.u ^ u2.u) & PX_SIGN_BITMASK);
#else
// javascript floats are 64-bits...
return IntBool( (f0*f1) < 0.0f );
#endif
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33 star(const PxVec3 &v) {
return PxMat33(PxVec3(0, v.z, -v.y), PxVec3(-v.z, 0, v.x), PxVec3(v.y, -v.x, 0));
}
PX_CUDA_CALLABLE PX_INLINE PxVec3 log(const PxQuat &q) {
const PxReal s = q.getImaginaryPart().magnitude();
if (s < 1e-12f)
return PxVec3(0.0f);
// force the half-angle to have magnitude <= pi/2
PxReal halfAngle = q.w < 0 ? PxAtan2(-s, -q.w) : PxAtan2(s, q.w);
PX_ASSERT(halfAngle >= -PxPi / 2 && halfAngle <= PxPi / 2);
return q.getImaginaryPart().getNormalized() * 2.f * halfAngle;
}
PX_CUDA_CALLABLE PX_INLINE PxQuat exp(const PxVec3 &v) {
const PxReal m = v.magnitudeSquared();
return m < 1e-24f ? PxQuat(PxIdentity) : PxQuat(PxSqrt(m), v * PxRecipSqrt(m));
}
// quat to rotate v0 t0 v1
PX_CUDA_CALLABLE PX_INLINE PxQuat rotationArc(const PxVec3 &v0, const PxVec3 &v1) {
const PxVec3 cross = v0.cross(v1);
const PxReal d = v0.dot(v1);
if (d <= -0.99999f)
return (PxAbs(v0.x) < 0.1f ? PxQuat(0.0f, v0.z, -v0.y, 0.0f) : PxQuat(v0.y, -v0.x, 0.0, 0.0)).getNormalized();
const PxReal s = PxSqrt((1 + d) * 2), r = 1 / s;
return PxQuat(cross.x * r, cross.y * r, cross.z * r, s * 0.5f).getNormalized();
}
/**
\brief returns largest axis
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 largestAxis(const PxVec3 &v) {
PxU32 m = PxU32(v.y > v.x ? 1 : 0);
return v.z > v[m] ? 2 : m;
}
/**
\brief returns indices for the largest axis and 2 other axii
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 largestAxis(const PxVec3 &v, PxU32 &other1, PxU32 &other2) {
if (v.x >= PxMax(v.y, v.z)) {
other1 = 1;
other2 = 2;
return 0;
} else if (v.y >= v.z) {
other1 = 0;
other2 = 2;
return 1;
} else {
other1 = 0;
other2 = 1;
return 2;
}
}
/**
\brief returns axis with smallest absolute value
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 closestAxis(const PxVec3 &v) {
PxU32 m = PxU32(PxAbs(v.y) > PxAbs(v.x) ? 1 : 0);
return PxAbs(v.z) > PxAbs(v[m]) ? 2 : m;
}
PX_CUDA_CALLABLE PX_INLINE PxU32 closestAxis(const PxVec3 &v, PxU32 &j, PxU32 &k) {
// find largest 2D plane projection
const PxF32 absPx = PxAbs(v.x);
const PxF32 absNy = PxAbs(v.y);
const PxF32 absNz = PxAbs(v.z);
PxU32 m = 0; // x biggest axis
j = 1;
k = 2;
if (absNy > absPx && absNy > absNz) {
// y biggest
j = 2;
k = 0;
m = 1;
} else if (absNz > absPx) {
// z biggest
j = 0;
k = 1;
m = 2;
}
return m;
}
/*!
Extend an edge along its length by a factor
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE void makeFatEdge(PxVec3 &p0, PxVec3 &p1, PxReal fatCoeff) {
PxVec3 delta = p1 - p0;
const PxReal m = delta.magnitude();
if (m > 0.0f) {
delta *= fatCoeff / m;
p0 -= delta;
p1 += delta;
}
}
//! Compute point as combination of barycentric coordinates
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3
computeBarycentricPoint(const PxVec3 &p0, const PxVec3 &p1, const PxVec3 &p2, PxReal u, PxReal v) {
// This seems to confuse the compiler...
// return (1.0f - u - v)*p0 + u*p1 + v*p2;
const PxF32 w = 1.0f - u - v;
return PxVec3(w * p0.x + u * p1.x + v * p2.x, w * p0.y + u * p1.y + v * p2.y, w * p0.z + u * p1.z + v * p2.z);
}
// generates a pair of quaternions (swing, twist) such that in = swing * twist, with
// swing.x = 0
// twist.y = twist.z = 0, and twist is a unit quat
PX_FORCE_INLINE void separateSwingTwist(const PxQuat &q, PxQuat &swing, PxQuat &twist) {
twist = q.x != 0.0f ? PxQuat(q.x, 0, 0, q.w).getNormalized() : PxQuat(PxIdentity);
swing = q * twist.getConjugate();
}
PX_FORCE_INLINE float computeSwingAngle(float swingYZ, float swingW) {
return 4.0f * PxAtan2(swingYZ, 1.0f + swingW); // tan (t/2) = sin(t)/(1+cos t), so this is the quarter angle
}
// generate two tangent vectors to a given normal
PX_FORCE_INLINE void normalToTangents(const PxVec3 &normal, PxVec3 &tangent0, PxVec3 &tangent1) {
tangent0 = PxAbs(normal.x) < 0.70710678f ? PxVec3(0, -normal.z, normal.y) : PxVec3(-normal.y, normal.x, 0);
tangent0.normalize();
tangent1 = normal.cross(tangent0);
}
/**
\brief computes a oriented bounding box around the scaled basis.
\param basis Input = skewed basis, Output = (normalized) orthogonal basis.
\return Bounding box extent.
*/
PX_FOUNDATION_API PxVec3 optimizeBoundingBox(PxMat33 &basis);
PX_FOUNDATION_API PxQuat slerp(const PxReal t, const PxQuat &left, const PxQuat &right);
PX_CUDA_CALLABLE PX_INLINE PxVec3 ellipseClamp(const PxVec3 &point, const PxVec3 &radii) {
// This function need to be implemented in the header file because
// it is included in a spu shader program.
// finds the closest point on the ellipse to a given point
// (p.y, p.z) is the input point
// (e.y, e.z) are the radii of the ellipse
// lagrange multiplier method with Newton/Halley hybrid root-finder.
// see http://www.geometrictools.com/Documentation/DistancePointToEllipse2.pdf
// for proof of Newton step robustness and initial estimate.
// Halley converges much faster but sometimes overshoots - when that happens we take
// a newton step instead
// converges in 1-2 iterations where D&C works well, and it's good with 4 iterations
// with any ellipse that isn't completely crazy
const PxU32 MAX_ITERATIONS = 20;
const PxReal convergenceThreshold = 1e-4f;
// iteration requires first quadrant but we recover generality later
PxVec3 q(0, PxAbs(point.y), PxAbs(point.z));
const PxReal tinyEps = 1e-6f; // very close to minor axis is numerically problematic but trivial
if (radii.y >= radii.z) {
if (q.z < tinyEps)
return PxVec3(0, point.y > 0 ? radii.y : -radii.y, 0);
} else {
if (q.y < tinyEps)
return PxVec3(0, 0, point.z > 0 ? radii.z : -radii.z);
}
PxVec3 denom, e2 = radii.multiply(radii), eq = radii.multiply(q);
// we can use any initial guess which is > maximum(-e.y^2,-e.z^2) and for which f(t) is > 0.
// this guess works well near the axes, but is weak along the diagonals.
PxReal t = PxMax(eq.y - e2.y, eq.z - e2.z);
for (PxU32 i = 0; i < MAX_ITERATIONS; i++) {
denom = PxVec3(0, 1 / (t + e2.y), 1 / (t + e2.z));
PxVec3 denom2 = eq.multiply(denom);
PxVec3 fv = denom2.multiply(denom2);
PxReal f = fv.y + fv.z - 1;
// although in exact arithmetic we are guaranteed f>0, we can get here
// on the first iteration via catastrophic cancellation if the point is
// very close to the origin. In that case we just behave as if f=0
if (f < convergenceThreshold)
return e2.multiply(point).multiply(denom);
PxReal df = fv.dot(denom) * -2.0f;
t = t - f / df;
}
// we didn't converge, so clamp what we have
PxVec3 r = e2.multiply(point).multiply(denom);
return r * PxRecipSqrt(sqr(r.y / radii.y) + sqr(r.z / radii.z));
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal tanHalf(PxReal sin, PxReal cos) {
// PT: avoids divide by zero for singularity. We return sqrt(FLT_MAX) instead of FLT_MAX
// to make sure the calling code doesn't generate INF values when manipulating the returned value
// (some joints multiply it by 4, etc).
if (cos == -1.0f)
return sin < 0.0f ? -sqrtf(FLT_MAX) : sqrtf(FLT_MAX);
// PT: half-angle formula: tan(a/2) = sin(a)/(1+cos(a))
return sin / (1.0f + cos);
}
PX_INLINE PxQuat quatFromTanQVector(const PxVec3 &v) {
PxReal v2 = v.dot(v);
if (v2 < 1e-12f)
return PxQuat(PxIdentity);
PxReal d = 1 / (1 + v2);
return PxQuat(v.x * 2, v.y * 2, v.z * 2, 1 - v2) * d;
}
PX_FORCE_INLINE PxVec3 cross100(const PxVec3 &b) {
return PxVec3(0.0f, -b.z, b.y);
}
PX_FORCE_INLINE PxVec3 cross010(const PxVec3 &b) {
return PxVec3(b.z, 0.0f, -b.x);
}
PX_FORCE_INLINE PxVec3 cross001(const PxVec3 &b) {
return PxVec3(-b.y, b.x, 0.0f);
}
PX_INLINE void decomposeVector(PxVec3 &normalCompo, PxVec3 &tangentCompo, const PxVec3 &outwardDir,
const PxVec3 &outwardNormal) {
normalCompo = outwardNormal * (outwardDir.dot(outwardNormal));
tangentCompo = outwardDir - normalCompo;
}
//! \brief Return (i+1)%3
// Avoid variable shift for XBox:
// PX_INLINE PxU32 Ps::getNextIndex3(PxU32 i) { return (1<<i) & 3; }
PX_INLINE PxU32 getNextIndex3(PxU32 i) {
return (i + 1 + (i >> 1)) & 3;
}
PX_INLINE PxMat33 rotFrom2Vectors(const PxVec3 &from, const PxVec3 &to) {
// See bottom of http://www.euclideanspace.com/maths/algebra/matrix/orthogonal/rotation/index.htm
// Early exit if to = from
if ((from - to).magnitudeSquared() < 1e-4f)
return PxMat33(PxIdentity);
// Early exit if to = -from
if ((from + to).magnitudeSquared() < 1e-4f)
return PxMat33::createDiagonal(PxVec3(1.0f, -1.0f, -1.0f));
PxVec3 n = from.cross(to);
PxReal C = from.dot(to), S = PxSqrt(1 - C * C), CC = 1 - C;
PxReal xx = n.x * n.x, yy = n.y * n.y, zz = n.z * n.z, xy = n.x * n.y, yz = n.y * n.z, xz = n.x * n.z;
PxMat33 R;
R(0, 0) = 1 + CC * (xx - 1);
R(0, 1) = -n.z * S + CC * xy;
R(0, 2) = n.y * S + CC * xz;
R(1, 0) = n.z * S + CC * xy;
R(1, 1) = 1 + CC * (yy - 1);
R(1, 2) = -n.x * S + CC * yz;
R(2, 0) = -n.y * S + CC * xz;
R(2, 1) = n.x * S + CC * yz;
R(2, 2) = 1 + CC * (zz - 1);
return R;
}
PX_FOUNDATION_API void integrateTransform(const PxTransform &curTrans, const PxVec3 &linvel, const PxVec3 &angvel,
PxReal timeStep, PxTransform &result);
PX_INLINE void computeBasis(const PxVec3 &dir, PxVec3 &right, PxVec3 &up) {
// Derive two remaining vectors
if (PxAbs(dir.y) <= 0.9999f) {
right = PxVec3(dir.z, 0.0f, -dir.x);
right.normalize();
// PT: normalize not needed for 'up' because dir & right are unit vectors,
// and by construction the angle between them is 90 degrees (i.e. sin(angle)=1)
up = PxVec3(dir.y * right.z, dir.z * right.x - dir.x * right.z, -dir.y * right.x);
} else {
right = PxVec3(1.0f, 0.0f, 0.0f);
up = PxVec3(0.0f, dir.z, -dir.y);
up.normalize();
}
}
PX_INLINE void computeBasis(const PxVec3 &p0, const PxVec3 &p1, PxVec3 &dir, PxVec3 &right, PxVec3 &up) {
// Compute the new direction vector
dir = p1 - p0;
dir.normalize();
// Derive two remaining vectors
computeBasis(dir, right, up);
}
PX_FORCE_INLINE bool isAlmostZero(const PxVec3 &v) {
if (PxAbs(v.x) > 1e-6f || PxAbs(v.y) > 1e-6f || PxAbs(v.z) > 1e-6f)
return false;
return true;
}
} // namespace shdfnd
} // namespace physx
#endif
| 29.329618 | 119 | 0.692166 | [
"vector"
] |
2ab629f1d7aa1847a3eb1ec385cd20b9efff1d41 | 7,953 | cc | C++ | test/av1_fwd_txfm2d_test.cc | mzso/av1 | a77c871ee03f9a3445f3bdb7cfd7dad4e3fd2db1 | [
"BSD-2-Clause"
] | null | null | null | test/av1_fwd_txfm2d_test.cc | mzso/av1 | a77c871ee03f9a3445f3bdb7cfd7dad4e3fd2db1 | [
"BSD-2-Clause"
] | null | null | null | test/av1_fwd_txfm2d_test.cc | mzso/av1 | a77c871ee03f9a3445f3bdb7cfd7dad4e3fd2db1 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2016, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "test/acm_random.h"
#include "test/util.h"
#include "test/av1_txfm_test.h"
#include "av1/common/av1_txfm.h"
#include "./av1_rtcd.h"
using libaom_test::ACMRandom;
using libaom_test::input_base;
using libaom_test::bd;
using libaom_test::compute_avg_abs_error;
using libaom_test::Fwd_Txfm2d_Func;
using libaom_test::TYPE_TXFM;
using std::vector;
namespace {
// tx_type_, tx_size_, max_error_, max_avg_error_
typedef std::tr1::tuple<TX_TYPE, TX_SIZE, double, double> AV1FwdTxfm2dParam;
class AV1FwdTxfm2d : public ::testing::TestWithParam<AV1FwdTxfm2dParam> {
public:
virtual void SetUp() {
tx_type_ = GET_PARAM(0);
tx_size_ = GET_PARAM(1);
max_error_ = GET_PARAM(2);
max_avg_error_ = GET_PARAM(3);
count_ = 500;
TXFM_2D_FLIP_CFG fwd_txfm_flip_cfg;
av1_get_fwd_txfm_cfg(tx_type_, tx_size_, &fwd_txfm_flip_cfg);
amplify_factor_ = libaom_test::get_amplification_factor(tx_type_, tx_size_);
tx_width_ = fwd_txfm_flip_cfg.row_cfg->txfm_size;
tx_height_ = fwd_txfm_flip_cfg.col_cfg->txfm_size;
ud_flip_ = fwd_txfm_flip_cfg.ud_flip;
lr_flip_ = fwd_txfm_flip_cfg.lr_flip;
fwd_txfm_ = libaom_test::fwd_txfm_func_ls[tx_size_];
txfm2d_size_ = tx_width_ * tx_height_;
input_ = reinterpret_cast<int16_t *>(
aom_memalign(16, sizeof(input_[0]) * txfm2d_size_));
output_ = reinterpret_cast<int32_t *>(
aom_memalign(16, sizeof(output_[0]) * txfm2d_size_));
ref_input_ = reinterpret_cast<double *>(
aom_memalign(16, sizeof(ref_input_[0]) * txfm2d_size_));
ref_output_ = reinterpret_cast<double *>(
aom_memalign(16, sizeof(ref_output_[0]) * txfm2d_size_));
}
void RunFwdAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
double avg_abs_error = 0;
for (int ci = 0; ci < count_; ci++) {
for (int ni = 0; ni < txfm2d_size_; ++ni) {
input_[ni] = rnd.Rand16() % input_base;
ref_input_[ni] = static_cast<double>(input_[ni]);
output_[ni] = 0;
ref_output_[ni] = 0;
}
fwd_txfm_(input_, output_, tx_width_, tx_type_, bd);
if (lr_flip_ && ud_flip_) {
libaom_test::fliplrud(ref_input_, tx_width_, tx_height_, tx_width_);
} else if (lr_flip_) {
libaom_test::fliplr(ref_input_, tx_width_, tx_height_, tx_width_);
} else if (ud_flip_) {
libaom_test::flipud(ref_input_, tx_width_, tx_height_, tx_width_);
}
libaom_test::reference_hybrid_2d(ref_input_, ref_output_, tx_type_,
tx_size_);
double actual_max_error = 0;
for (int ni = 0; ni < txfm2d_size_; ++ni) {
ref_output_[ni] = round(ref_output_[ni]);
const double this_error =
fabs(output_[ni] - ref_output_[ni]) / amplify_factor_;
actual_max_error = AOMMAX(actual_max_error, this_error);
}
EXPECT_GE(max_error_, actual_max_error)
<< "tx_size = " << tx_size_ << ", tx_type = " << tx_type_;
if (actual_max_error > max_error_) { // exit early.
break;
}
avg_abs_error += compute_avg_abs_error<int32_t, double>(
output_, ref_output_, txfm2d_size_);
}
avg_abs_error /= amplify_factor_;
avg_abs_error /= count_;
EXPECT_GE(max_avg_error_, avg_abs_error)
<< "tx_size = " << tx_size_ << ", tx_type = " << tx_type_;
}
virtual void TearDown() {
aom_free(input_);
aom_free(output_);
aom_free(ref_input_);
aom_free(ref_output_);
}
private:
double max_error_;
double max_avg_error_;
int count_;
double amplify_factor_;
TX_TYPE tx_type_;
TX_SIZE tx_size_;
int tx_width_;
int tx_height_;
int txfm2d_size_;
Fwd_Txfm2d_Func fwd_txfm_;
int16_t *input_;
int32_t *output_;
double *ref_input_;
double *ref_output_;
int ud_flip_; // flip upside down
int lr_flip_; // flip left to right
};
vector<AV1FwdTxfm2dParam> GetTxfm2dParamList() {
vector<AV1FwdTxfm2dParam> param_list;
for (int t = 0; t < TX_TYPES; ++t) {
const TX_TYPE tx_type = static_cast<TX_TYPE>(t);
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_4X4, 2, 0.5));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_8X8, 5, 0.6));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_16X16, 11, 1.5));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_32X32, 70, 7));
#if CONFIG_TX64X64
if (tx_type == DCT_DCT) { // Other types not supported by these tx sizes.
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_64X64, 70, 7));
}
#endif // CONFIG_TX64X64
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_4X8, 3.2, 0.58));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_8X4, 3.6, 0.63));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_8X16, 15, 1.5));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_16X8, 15, 1.5));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_16X32, 57, 7));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_32X16, 37, 7));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_4X16, 5, 0.7));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_16X4, 5.5, 0.9));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_8X32, 20, 2.2));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_32X8, 15, 1.8));
#if CONFIG_TX64X64
if (tx_type == DCT_DCT) { // Other types not supported by these tx sizes.
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_32X64, 136, 7));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_64X32, 136, 7));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_16X64, 30, 3.6));
param_list.push_back(AV1FwdTxfm2dParam(tx_type, TX_64X16, 50, 6.0));
}
#endif // CONFIG_TX64X64
}
return param_list;
}
INSTANTIATE_TEST_CASE_P(C, AV1FwdTxfm2d,
::testing::ValuesIn(GetTxfm2dParamList()));
TEST_P(AV1FwdTxfm2d, RunFwdAccuracyCheck) { RunFwdAccuracyCheck(); }
TEST(AV1FwdTxfm2d, CfgTest) {
for (int bd_idx = 0; bd_idx < BD_NUM; ++bd_idx) {
int bd = libaom_test::bd_arr[bd_idx];
int8_t low_range = libaom_test::low_range_arr[bd_idx];
int8_t high_range = libaom_test::high_range_arr[bd_idx];
for (int tx_size = 0; tx_size < TX_SIZES_ALL; ++tx_size) {
for (int tx_type = 0; tx_type < TX_TYPES; ++tx_type) {
#if CONFIG_TX64X64
if ((tx_size_wide[tx_size] == 64 || tx_size_high[tx_size] == 64) &&
tx_type != DCT_DCT) {
continue;
}
#endif // CONFIG_TX64X64
TXFM_2D_FLIP_CFG cfg;
av1_get_fwd_txfm_cfg(static_cast<TX_TYPE>(tx_type),
static_cast<TX_SIZE>(tx_size), &cfg);
int8_t stage_range_col[MAX_TXFM_STAGE_NUM];
int8_t stage_range_row[MAX_TXFM_STAGE_NUM];
av1_gen_fwd_stage_range(stage_range_col, stage_range_row, &cfg, bd);
const TXFM_1D_CFG *col_cfg = cfg.col_cfg;
const TXFM_1D_CFG *row_cfg = cfg.row_cfg;
libaom_test::txfm_stage_range_check(stage_range_col, col_cfg->stage_num,
col_cfg->cos_bit, low_range,
high_range);
libaom_test::txfm_stage_range_check(stage_range_row, row_cfg->stage_num,
row_cfg->cos_bit, low_range,
high_range);
}
}
}
}
} // namespace
| 37.338028 | 80 | 0.676223 | [
"vector"
] |
2ab6ed2856f26decb73a7c29c98fa9263601249c | 21,481 | cpp | C++ | src/main.cpp | Sennevds/MQTTLeds | 6af9d726ce472974ddcb1e1b3a6f6a9970dcf920 | [
"MIT"
] | null | null | null | src/main.cpp | Sennevds/MQTTLeds | 6af9d726ce472974ddcb1e1b3a6f6a9970dcf920 | [
"MIT"
] | null | null | null | src/main.cpp | Sennevds/MQTTLeds | 6af9d726ce472974ddcb1e1b3a6f6a9970dcf920 | [
"MIT"
] | null | null | null |
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "FastLED.h"
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
/************ WIFI and MQTT INFORMATION (CHANGE THESE FOR YOUR SETUP) ******************/
#define wifi_ssid "YourSSID" //enter your WIFI SSID
#define wifi_password "YourWIFIPassword" //enter your WIFI Password
#define mqtt_server "YOURMQTTSERVER.COM" // Enter your MQTT server adderss or IP. I use my DuckDNS adddress (yourname.duckdns.org) in this field
#define mqtt_user "YourUSERNAME" //enter your MQTT username
#define mqtt_password "YourPASSWORD!" //enter your password
/************ FastLED Defintions ******************/
#define DATA_PIN 5 //on the NodeMCU 1.0, FastLED will default to the D5 pin after throwing an error during compiling. Leave as is.
#define LED_TYPE WS2812 //change to match your LED type
#define COLOR_ORDER RGB //change to match your LED configuration
#define NUM_LEDS 73 //change to match your setup
//No Changes Required After This Point
/****************************** MQTT TOPICS (change these topics as you wish) ***************************************/
#define colorstatuspub "hass/mqttstrip/colorstatus"
#define setcolorsub "hass/mqttstrip/setcolor"
#define setpowersub "hass/mqttstrip/setpower"
#define seteffectsub "hass/mqttstrip/seteffect"
#define setbrightness "hass/mqttstrip/setbrightness"
#define setcolorpub "hass/mqttstrip/setcolorpub"
#define setpowerpub "hass/mqttstrip/setpowerpub"
#define seteffectpub "hass/mqttstrip/seteffectpub"
#define setbrightnesspub "hass/mqttstrip/setbrightnesspub"
#define setanimationspeed "hass/mqttstrip/setanimationspeed"
void setupStripedPalette( CRGB A, CRGB AB, CRGB B, CRGB BA);
void setup_wifi();
void callback(char* topic, byte* payload, unsigned int length);
void reconnect();
void addGlitter( fract8 chanceOfGlitter);
void addGlitterColor( fract8 chanceOfGlitter, int Rcolor, int Gcolor, int Bcolor);
void fadeall();
void Fire2012WithPalette();
/*************************** EFFECT CONTROL VARIABLES AND INITIALIZATIONS ************************************/
#if defined(FASTLED_VERSION) && (FASTLED_VERSION < 3001000)
#warning "Requires FastLED 3.1 or later; check github for latest code."
#endif
String setColor ="0,0,150";
String setPower;
String setEffect = "Solid";
String setBrightness = "150";
int brightness = 150;
String setAnimationSpeed;
int animationspeed = 240;
String setColorTemp;
int Rcolor = 0;
int Gcolor = 0;
int Bcolor = 0;
CRGB leds[NUM_LEDS];
/****************FOR CANDY CANE***************/
CRGBPalette16 currentPalettestriped; //for Candy Cane
CRGBPalette16 gPal; //for fire
/****************FOR NOISE***************/
static uint16_t dist; // A random number for our noise generator.
uint16_t scale = 30; // Wouldn't recommend changing this on the fly, or the animation will be really blocky.
uint8_t maxChanges = 48; // Value for blending between palettes.
CRGBPalette16 targetPalette(OceanColors_p);
CRGBPalette16 currentPalette(CRGB::Black);
/*****************For TWINKER********/
#define DENSITY 80
int twinklecounter = 0;
/*********FOR RIPPLE***********/
uint8_t colour; // Ripple colour is randomized.
int center = 0; // Center of the current ripple.
int step = -1; // -1 is the initializing step.
uint8_t myfade = 255; // Starting brightness.
#define maxsteps 16 // Case statement wouldn't allow a variable.
uint8_t bgcol = 0; // Background colour rotates.
int thisdelay = 20; // Standard delay value.
/**************FOR RAINBOW***********/
uint8_t thishue = 0; // Starting hue value.
uint8_t deltahue = 10;
/**************FOR DOTS**************/
uint8_t count = 0; // Count up to 255 and then reverts to 0
uint8_t fadeval = 224; // Trail behind the LED's. Lower => faster fade.
uint8_t bpm = 30;
/**************FOR LIGHTNING**************/
uint8_t frequency = 50; // controls the interval between strikes
uint8_t flashes = 8; //the upper limit of flashes per strike
unsigned int dimmer = 1;
uint8_t ledstart; // Starting location of a flash
uint8_t ledlen;
int lightningcounter = 0;
/********FOR FUNKBOX EFFECTS**********/
int idex = 0; //-LED INDEX (0 to NUM_LEDS-1
int TOP_INDEX = int(NUM_LEDS / 2);
int thissat = 255; //-FX LOOPS DELAY VAR
uint8_t thishuepolice = 0;
int antipodal_index(int i) {
int iN = i + TOP_INDEX;
if (i >= TOP_INDEX) {
iN = ( i + TOP_INDEX ) % NUM_LEDS;
}
return iN;
}
/********FIRE**********/
#define COOLING 55
#define SPARKING 120
bool gReverseDirection = false;
/********BPM**********/
uint8_t gHue = 0;
char message_buff[100];
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
FastLED.setMaxPowerInVoltsAndMilliamps(12, 10000); //experimental for power management. Feel free to try in your own setup.
FastLED.setBrightness(brightness);
setupStripedPalette( CRGB::Red, CRGB::Red, CRGB::White, CRGB::White); //for CANDY CANE
gPal = HeatColors_p; //for FIRE
fill_solid(leds, NUM_LEDS, CRGB(255, 0, 0)); //Startup LED Lights
FastLED.show();
setup_wifi();
client.setServer(mqtt_server, 1883); //CHANGE PORT HERE IF NEEDED
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifi_ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
ArduinoOTA.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
int i = 0;
if (String(topic) == setpowersub) {
for (i = 0; i < length; i++) {
message_buff[i] = payload[i];
}
message_buff[i] = '\0';
setPower = String(message_buff);
Serial.println("Set Power: " + setPower);
if (setPower == "OFF") {
client.publish(setpowerpub, "OFF");
}
if (setPower == "ON") {
client.publish(setpowerpub, "ON");
}
}
if (String(topic) == seteffectsub) {
for (i = 0; i < length; i++) {
message_buff[i] = payload[i];
}
message_buff[i] = '\0';
setEffect = String(message_buff);
Serial.println("Set Effect: " + setEffect);
setPower = "ON";
client.publish(setpowerpub, "ON");
if (setEffect == "Twinkle") {
twinklecounter = 0;
}
if (setEffect == "Lightning") {
twinklecounter = 0;
}
}
if (String(topic) == setbrightness) {
for (i = 0; i < length; i++) {
message_buff[i] = payload[i];
}
message_buff[i] = '\0';
setBrightness = String(message_buff);
Serial.println("Set Brightness: " + setBrightness);
brightness = setBrightness.toInt();
setPower = "ON";
client.publish(setpowerpub, "ON");
}
// if (String(topic) == setcolortemp) { //colortemp setup for future update
// for (i = 0; i < length; i++) {
// message_buff[i] = payload[i];
// }
// message_buff[i] = '\0';
// setColorTemp = String(message_buff);
// Serial.println("Set Color Temperature: " + setColorTemp);
// setPower = "ON";
// client.publish(setpowerpub, "ON");
// }
if (String(topic) == setcolorsub) {
for (i = 0; i < length; i++) {
message_buff[i] = payload[i];
}
message_buff[i] = '\0';
client.publish(setcolorpub, message_buff);
setColor = String(message_buff);
Serial.println("Set Color: " + setColor);
setPower = "ON";
client.publish(setpowerpub, "ON");
}
if (String(topic) == setanimationspeed) {
for (i = 0; i < length; i++) {
message_buff[i] = payload[i];
}
message_buff[i] = '\0';
setAnimationSpeed = String(message_buff);
animationspeed = setAnimationSpeed.toInt();
}
}
void loop() {
ArduinoOTA.handle();
if (!client.connected()) {
reconnect();
}
client.loop();
int Rcolor = setColor.substring(0, setColor.indexOf(',')).toInt();
int Gcolor = setColor.substring(setColor.indexOf(',') + 1, setColor.lastIndexOf(',')).toInt();
int Bcolor = setColor.substring(setColor.lastIndexOf(',') + 1).toInt();
if (setPower == "OFF") {
setEffect = "Solid";
for ( int i = 0; i < NUM_LEDS; i++) {
leds[i].fadeToBlackBy( 8 ); //FADE OFF LEDS
}
}
if (setEffect == "Sinelon") {
fadeToBlackBy( leds, NUM_LEDS, 20);
int pos = beatsin16(13, 0, NUM_LEDS);
leds[pos] += CRGB(Rcolor, Gcolor, Bcolor);
}
if (setEffect == "Juggle" ) { // eight colored dots, weaving in and out of sync with each other
fadeToBlackBy( leds, NUM_LEDS, 20);
byte dothue = 0;
for ( int i = 0; i < 8; i++) {
leds[beatsin16(i + 7, 0, NUM_LEDS)] |= CRGB(Rcolor, Gcolor, Bcolor);
dothue += 32;
}
}
if (setEffect == "Confetti" ) { // random colored speckles that blink in and fade smoothly
fadeToBlackBy( leds, NUM_LEDS, 10);
int pos = random16(NUM_LEDS);
leds[pos] += CRGB(Rcolor + random8(64), Gcolor, Bcolor);
}
if (setEffect == "Rainbow") {
// FastLED's built-in rainbow generator
static uint8_t starthue = 0; thishue++;
fill_rainbow(leds, NUM_LEDS, thishue, deltahue);
}
if (setEffect == "Rainbow with Glitter") { // FastLED's built-in rainbow generator with Glitter
static uint8_t starthue = 0;
thishue++;
fill_rainbow(leds, NUM_LEDS, thishue, deltahue);
addGlitter(80);
}
if (setEffect == "Glitter") {
fadeToBlackBy( leds, NUM_LEDS, 20);
addGlitterColor(80, Rcolor, Gcolor, Bcolor);
}
if (setEffect == "BPM") { // colored stripes pulsing at a defined Beats-Per-Minute (BPM)
uint8_t BeatsPerMinute = 62;
CRGBPalette16 palette = PartyColors_p;
uint8_t beat = beatsin8( BeatsPerMinute, 64, 255);
for( int i = 0; i < NUM_LEDS; i++) { //9948
leds[i] = ColorFromPalette(palette, gHue+(i*2), beat-gHue+(i*10));
}
}
if (setEffect == "Solid" & setPower == "ON" ) { //Fill entire strand with solid color
fill_solid(leds, NUM_LEDS, CRGB(Rcolor, Gcolor, Bcolor));
}
if (setEffect == "Twinkle") {
twinklecounter = twinklecounter + 1;
if (twinklecounter < 2) { //Resets strip if previous animation was running
FastLED.clear();
FastLED.show();
}
const CRGB lightcolor(8, 7, 1);
for ( int i = 0; i < NUM_LEDS; i++) {
if ( !leds[i]) continue; // skip black pixels
if ( leds[i].r & 1) { // is red odd?
leds[i] -= lightcolor; // darken if red is odd
} else {
leds[i] += lightcolor; // brighten if red is even
}
}
if ( random8() < DENSITY) {
int j = random16(NUM_LEDS);
if ( !leds[j] ) leds[j] = lightcolor;
}
}
if (setEffect == "Dots") {
uint8_t inner = beatsin8(bpm, NUM_LEDS / 4, NUM_LEDS / 4 * 3);
uint8_t outer = beatsin8(bpm, 0, NUM_LEDS - 1);
uint8_t middle = beatsin8(bpm, NUM_LEDS / 3, NUM_LEDS / 3 * 2);
leds[middle] = CRGB::Purple;
leds[inner] = CRGB::Blue;
leds[outer] = CRGB::Aqua;
nscale8(leds, NUM_LEDS, fadeval);
}
if (setEffect == "Lightning") {
twinklecounter = twinklecounter + 1; //Resets strip if previous animation was running
Serial.println(twinklecounter);
if (twinklecounter < 2) {
FastLED.clear();
FastLED.show();
}
ledstart = random8(NUM_LEDS); // Determine starting location of flash
ledlen = random8(NUM_LEDS - ledstart); // Determine length of flash (not to go beyond NUM_LEDS-1)
for (int flashCounter = 0; flashCounter < random8(3, flashes); flashCounter++) {
if (flashCounter == 0) dimmer = 5; // the brightness of the leader is scaled down by a factor of 5
else dimmer = random8(1, 3); // return strokes are brighter than the leader
fill_solid(leds + ledstart, ledlen, CHSV(255, 0, 255 / dimmer));
FastLED.show(); // Show a section of LED's
delay(random8(4, 10)); // each flash only lasts 4-10 milliseconds
fill_solid(leds + ledstart, ledlen, CHSV(255, 0, 0)); // Clear the section of LED's
FastLED.show();
if (flashCounter == 0) delay (150); // longer delay until next flash after the leader
delay(50 + random8(100)); // shorter delay between strokes
}
delay(random8(frequency) * 100); // delay between strikes
}
if (setEffect == "Police One") { //POLICE LIGHTS (TWO COLOR SINGLE LED)
idex++;
if (idex >= NUM_LEDS) {
idex = 0;
}
int idexR = idex;
int idexB = antipodal_index(idexR);
int thathue = (thishuepolice + 160) % 255;
for (int i = 0; i < NUM_LEDS; i++ ) {
if (i == idexR) {
leds[i] = CHSV(thishuepolice, thissat, 255);
}
else if (i == idexB) {
leds[i] = CHSV(thathue, thissat, 255);
}
else {
leds[i] = CHSV(0, 0, 0);
}
}
}
if (setEffect == "Police All") { //POLICE LIGHTS (TWO COLOR SOLID)
idex++;
if (idex >= NUM_LEDS) {
idex = 0;
}
int idexR = idex;
int idexB = antipodal_index(idexR);
int thathue = (thishuepolice + 160) % 255;
leds[idexR] = CHSV(thishuepolice, thissat, 255);
leds[idexB] = CHSV(thathue, thissat, 255);
}
if (setEffect == "Candy Cane") {
static uint8_t startIndex = 0;
startIndex = startIndex + 1; /* higher = faster motion */
fill_palette( leds, NUM_LEDS,
startIndex, 16, /* higher = narrower stripes */
currentPalettestriped, 255, LINEARBLEND);
}
if (setEffect == "Cyclon Rainbow") { //Single Dot Down
static uint8_t hue = 0;
Serial.print("x");
// First slide the led in one direction
for(int i = 0; i < NUM_LEDS; i++) {
// Set the i'th led to red
leds[i] = CHSV(hue++, 255, 255);
// Show the leds
FastLED.show();
// now that we've shown the leds, reset the i'th led to black
// leds[i] = CRGB::Black;
fadeall();
// Wait a little bit before we loop around and do it again
delay(10);
}
for(int i = (NUM_LEDS)-1; i >= 0; i--) {
// Set the i'th led to red
leds[i] = CHSV(hue++, 255, 255);
// Show the leds
FastLED.show();
// now that we've shown the leds, reset the i'th led to black
// leds[i] = CRGB::Black;
fadeall();
// Wait a little bit before we loop around and do it again
delay(10);
}
}
if (setEffect == "Fire") {
Fire2012WithPalette();
}
random16_add_entropy( random8());
EVERY_N_MILLISECONDS(10) {
nblendPaletteTowardPalette(currentPalette, targetPalette, maxChanges); // FOR NOISE ANIMATION
{ gHue++; }
if (setEffect == "Noise") {
setPower = "ON";
for (int i = 0; i < NUM_LEDS; i++) { // Just ONE loop to fill up the LED array as all of the pixels change.
uint8_t index = inoise8(i * scale, dist + i * scale) % 255; // Get a value from the noise function. I'm using both x and y axis.
leds[i] = ColorFromPalette(currentPalette, index, 255, LINEARBLEND); // With that value, look up the 8 bit colour palette value and assign it to the current LED.
}
dist += beatsin8(10, 1, 4); // Moving along the distance (that random number we started out with). Vary it a bit with a sine wave.
// In some sketches, I've used millis() instead of an incremented counter. Works a treat.
}
if (setEffect == "Ripple") {
for (int i = 0; i < NUM_LEDS; i++) leds[i] = CHSV(bgcol++, 255, 15); // Rotate background colour.
switch (step) {
case -1: // Initialize ripple variables.
center = random(NUM_LEDS);
colour = random8();
step = 0;
break;
case 0:
leds[center] = CHSV(colour, 255, 255); // Display the first pixel of the ripple.
step ++;
break;
case maxsteps: // At the end of the ripples.
step = -1;
break;
default: // Middle of the ripples.
leds[(center + step + NUM_LEDS) % NUM_LEDS] += CHSV(colour, 255, myfade / step * 2); // Simple wrap from Marc Miller
leds[(center - step + NUM_LEDS) % NUM_LEDS] += CHSV(colour, 255, myfade / step * 2);
step ++; // Next step.
break;
}
}
}
EVERY_N_SECONDS(5) {
targetPalette = CRGBPalette16(CHSV(random8(), 255, random8(128, 255)), CHSV(random8(), 255, random8(128, 255)), CHSV(random8(), 192, random8(128, 255)), CHSV(random8(), 255, random8(128, 255)));
}
FastLED.setBrightness(brightness); //EXECUTE EFFECT COLOR
FastLED.show();
if (animationspeed > 0 && animationspeed < 150) { //Sets animation speed based on receieved value
FastLED.delay(1000 / animationspeed);
}
}
void setupStripedPalette( CRGB A, CRGB AB, CRGB B, CRGB BA)
{
currentPalettestriped = CRGBPalette16(
A, A, A, A, A, A, A, A, B, B, B, B, B, B, B, B
// A, A, A, A, A, A, A, A, B, B, B, B, B, B, B, B
);
}
void fadeall() { for(int i = 0; i < NUM_LEDS; i++) { leds[i].nscale8(250); } } //for CYCLON
void Fire2012WithPalette()
{
// Array of temperature readings at each simulation cell
static byte heat[NUM_LEDS];
// Step 1. Cool down every cell a little
for( int i = 0; i < NUM_LEDS; i++) {
heat[i] = qsub8( heat[i], random8(0, ((COOLING * 10) / NUM_LEDS) + 2));
}
// Step 2. Heat from each cell drifts 'up' and diffuses a little
for( int k= NUM_LEDS - 1; k >= 2; k--) {
heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
}
// Step 3. Randomly ignite new 'sparks' of heat near the bottom
if( random8() < SPARKING ) {
int y = random8(7);
heat[y] = qadd8( heat[y], random8(160,255) );
}
// Step 4. Map from heat cells to LED colors
for( int j = 0; j < NUM_LEDS; j++) {
// Scale the heat value from 0-255 down to 0-240
// for best results with color palettes.
byte colorindex = scale8( heat[j], 240);
CRGB color = ColorFromPalette( gPal, colorindex);
int pixelnumber;
if( gReverseDirection ) {
pixelnumber = (NUM_LEDS-1) - j;
} else {
pixelnumber = j;
}
leds[pixelnumber] = color;
}
}
void addGlitter( fract8 chanceOfGlitter)
{
if( random8() < chanceOfGlitter) {
leds[ random16(NUM_LEDS) ] += CRGB::White;
}
}
void addGlitterColor( fract8 chanceOfGlitter, int Rcolor, int Gcolor, int Bcolor)
{
if( random8() < chanceOfGlitter) {
leds[ random16(NUM_LEDS) ] += CRGB(Rcolor, Gcolor, Bcolor);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("PorchLEDs", mqtt_user, mqtt_password)) {
Serial.println("connected");
FastLED.clear (); //Turns off startup LEDs after connection is made
FastLED.show();
client.subscribe(setcolorsub);
client.subscribe(setbrightness);
//client.subscribe(setcolortemp);
client.subscribe(setpowersub);
client.subscribe(seteffectsub);
client.subscribe(setanimationspeed);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
| 32.895865 | 198 | 0.58568 | [
"solid"
] |
2aba1cb0a1673518ee3d3535881f84d059df30c2 | 853 | hpp | C++ | includes/nomad/State/IntroState.hpp | manning390/Nomad | d2a7aabb9bd4cfe56cc37bd786533634f019c02a | [
"MIT"
] | null | null | null | includes/nomad/State/IntroState.hpp | manning390/Nomad | d2a7aabb9bd4cfe56cc37bd786533634f019c02a | [
"MIT"
] | null | null | null | includes/nomad/State/IntroState.hpp | manning390/Nomad | d2a7aabb9bd4cfe56cc37bd786533634f019c02a | [
"MIT"
] | null | null | null | #ifndef STATE_INTROSTATE
#define STATE_INTROSTATE
#include <vector>
#include "State/State.hpp"
#include <SFML/Graphics/Text.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
class StateMachine;
namespace sf {
class RenderWindow;
}
class IntroState : public State {
public:
IntroState(StateMachine& game, sf::RenderWindow& window, bool replace = true);
void pause();
void resume();
void update();
void draw();
private:
sf::Texture bgTex;
sf::Sprite bg;
sf::RectangleShape fader;
sf::Color alpha;
sf::Font font;
std::vector<sf::Text> texts;
unsigned int cursorPos = 0;
};
#endif // STATE_INTROSTATE | 21.871795 | 86 | 0.656506 | [
"vector"
] |
2aba4df00705590c99463d87b8b055b169df2e2a | 33,503 | hpp | C++ | sdl/Hypergraph/fs/Compose.hpp | sdl-research/hyp | d39f388f9cd283bcfa2f035f399b466407c30173 | [
"Apache-2.0"
] | 29 | 2015-01-26T21:49:51.000Z | 2021-06-18T18:09:42.000Z | sdl/Hypergraph/fs/Compose.hpp | hypergraphs/hyp | d39f388f9cd283bcfa2f035f399b466407c30173 | [
"Apache-2.0"
] | 1 | 2015-12-08T15:03:15.000Z | 2016-01-26T14:31:06.000Z | sdl/Hypergraph/fs/Compose.hpp | hypergraphs/hyp | d39f388f9cd283bcfa2f035f399b466407c30173 | [
"Apache-2.0"
] | 4 | 2015-11-21T14:25:38.000Z | 2017-10-30T22:22:00.000Z | // Copyright 2014-2015 SDL plc
// 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
ComposeFst<InputFst, MatchFst, Filter, WeightProductFn>
lazy composition of finite state machines (automata or transducer) M1 * M2
M1 is an "Input" fst - it must return a lazy (best-first if you can) generator of
out arcs for a given state. it may have as output labels <eps> or terminal
labels only.
M2 is a "Match" fst - it provides generators of out arcs from a state matching a
given input symbol (including special symbols <eps> <phi> <sigma> <rho>)
notation:
states q1 from M1 and q2 from M2
arc input labels i1 and i2; output labels o1 and o2 for the arcs i1:o1 from M1 and i2:o2 from M2
the composition is modified by a Filter type which affects the order in which <eps> i2 and o1 are taken,
so as not to introduce multiple derivations that are essentially the same
the derivations in the composition take input yields I1 and output yields O2
from paths in M1 and 2 resp. that have matching inner yields O1==I2 (after
removing <eps>). the weight of the composed derivation is the product of the
derivations from M1 and M2.
this is achieved by having states (q1, filter, q2) in the composition, final
iff q1 and q2 are both final, and starting in
(start1, Filter::normal, start2). the outgoing arcs in the composition are
built from the outgoing arcs of q1 and q2 (described below).
note that the weight type for the Match fst may be different from that of
the Lazy M1 and the Lazy composition; a function object serves to define
the product (e.g. a viterbi hypergraph weight can be multiplied into a
FeatureWeight by giving it a feature id and weight)
Lazy composition should be faster and may have a smaller result than the CFG
FST intersection markus implemented in ../Compose.hpp
the generation of outgoing arcs in the composition from state (q1, filter, q2) works as follows:
(see
http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en/us/pubs/archive/37568.pdf)
for M1 arc i1:o1 -> state r1 (from state q1):
for M2 arc i2:o2 -> state r2 (from state q2):
the filter state filter' depends on the type of transition taken and the type of filter (described later)
the weight of the arc is the product of the M1 and M2 arc (with
Weight::one() serving in case only one arc is mentioned)
DEFINITION: standard match:
if o1==i2 are non-special terminal symbols, we get (in composition) i1:o2 -> (r1, Filter::normal, r2)
now, for all the special (not standard) matches:
if o1==<eps> and Filter::allowInputEpsilon, we get i1:<eps> -> (r1, filter', q2) (the M2 state is
unchanged)
if i2==<eps> and Filter::allowMatchEpsilon, we get <eps>:o2 -> (q1, filter', r2)
if i2==o1==<eps> and Filter::allowInputMatchEpsilon, we get i1:o2 -> (r1, filter', r2)
if i2==<sigma> and o1 is a terminal symbol, we get i1:(o1 if o2==<sigma> else o2) -> (r1, Filter::normal,
r2)
if i2==<rho> and o1 is a terminal symbol AND no standard match occurred for
the arc i1:o1, we get i1:(o1 if o2==<rho> else o2) -> r1, Filter::normal, r2)
(similar to, and inaddition to, any <sigma> case above)
finally, if i2==<phi> and Filter::allowMatchEpsilon and no
standard matches occured for the entire compose state (for *every* input arc), <eps>:o2 -> (q1, filter',
r2)
note: in understanding the code below, recall that M1 is an InputFst and M2
is a MatchFst-that is, types or variable names beginning with "input" do
not refer to the input label (which is given by labelPair.first) but rather
to a state, arc, or label of M1.
TODO: allow lazy fst composition for one-lexical-symbol-per-arc (ignoring
but preserving any non-lexical labels before the lexical tail)
*/
#ifndef COMPOSE_JG20121225_HPP
#define COMPOSE_JG20121225_HPP
#pragma once
#include <sdl/Hypergraph/Exception.hpp>
#include <sdl/Hypergraph/IMutableHypergraph.hpp>
#include <sdl/Hypergraph/MixFeature.hpp>
#include <sdl/Hypergraph/SortArcs.hpp>
#include <sdl/Hypergraph/WeightUtil.hpp>
#include <sdl/Hypergraph/WeightsFwdDecls.hpp>
#include <sdl/Hypergraph/fs/Fst.hpp>
#include <sdl/Hypergraph/fs/LazyBest.hpp>
#include <sdl/Hypergraph/fs/SaveFst.hpp>
#include <sdl/Util/FlattenGenerators.hpp>
#include <sdl/Util/LogHelper.hpp>
#include <sdl/Util/RefCount.hpp>
#include <sdl/Util/SharedGenerator.hpp>
#include <sdl/Util/Valgrind.hpp>
#include <boost/functional/hash.hpp>
#include <boost/mpl/and.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <algorithm>
#include <type_traits>
namespace sdl {
namespace Hypergraph {
namespace fs {
struct FstComposeOptions : SaveFstOptions {
FstComposeOptions()
: fstCompose(true)
, allowDuplicatePaths(false)
, sortBestFirst(true)
, epsilonMatchingFilter(true)
, allowDuplicatePathsIf1Best(false) {}
template <class Arc>
bool willLazyFsCompose(Hypergraph::IHypergraph<Arc> const& hg) const {
return fstCompose && hg.isFsmLike() && usingLazyBest();
}
template <class Config>
void configure(Config& config) {
SaveFstOptions::configure(config);
config("fst-compose", &fstCompose)
.defaulted()("true: optimized fst1*fst2 compose (false: cfg*fst, which is slower)");
config("sort-best-first", &sortBestFirst)
.defaulted()(
"for fst-compose, if not saving whole output HG attempt to sort out-arcs best-first (ignored for "
"non-mutable hypergraphs)");
config("epsilon-matching-paths", &epsilonMatchingFilter)
.defaulted()(
"use a three-valued filter state that prefers matching input x:<eps> match <eps>:y directly into "
"x:y. this result may be larger or smaller. (TODO: seems buggy - ate some paths in testing)");
config("allow-duplicate-paths", &allowDuplicatePaths)
.defaulted()(
"for viterbi-like (idempotent plus - i.e. plus(x, x) = x) semirings, allow repeated equivalent "
"paths involving epsilons. this will result in n-best duplicates, but otherwise may be faster");
config("allow-duplicate-paths-if-1best", &allowDuplicatePathsIf1Best)
.defaulted()(
"allow-duplicate-paths only if prune-to-nbest=1 (because the downside of allow-duplicate-paths "
"is "
"extra paths)");
config("mix-fst", &mix)(
"a MixFeature for scaling the fst1 arc weight into the fst2 arc weight (and assigning feature id if "
"fst1 is FeatureWeight). if fst1 and fst2 are both FHG, then you have fst1*(fst^scale) - the "
"features of both");
}
MixFeature<> mix;
bool fstCompose;
bool allowDuplicatePaths, allowDuplicatePathsIf1Best;
bool sortBestFirst;
bool epsilonMatchingFilter;
bool allowDuplicatesEffective() const {
return allowDuplicatePaths || allowDuplicatePathsIf1Best && pruneToNbest == 1;
}
};
using Vocabulary::WhichFstComposeSpecials;
/**
\return symbol doesn't consume input.
*/
inline bool isNonconsuming(Sym matchLabel) {
return matchLabel == EPSILON::ID || matchLabel == PHI::ID;
}
/**
symbol always matches.
*/
inline bool isWildcard(Sym matchLabel) {
return matchLabel == EPSILON::ID || matchLabel == SIGMA::ID;
}
/**
\return symbol matches only when no explicitly labeled (non-epsilon) arc matches
*/
inline bool isFallback(Sym matchLabel) {
return matchLabel == PHI::ID || matchLabel == RHO::ID;
}
struct FilterBase {
void matchEpsilon() {}
void inputEpsilon() {}
void normal() {}
void inputMatchEpsilon() {}
};
/**
a filter is a modification to the simple cross product of states (q1, q2) for
M1*M2-instead we have (q1, f, q2), where the filter state can prevent
ambiguous paths involving epsilon, or even combine an M1 arc i1:<eps> with an
M2 arc <eps>:o2 to produce a result i1:o1 directly. NoEpsilonFilter is a dummy
filter (so you'll get ambiguous paths)
this filter should give smaller outputs but at the cost of redundant paths
sequencing consecutive input and match transducer epsilon arcs freely.
(see
http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en/us/pubs/archive/37568.pdf)
we treat nonconsuming 'else' (<phi>) as epsilon.
*/
struct NoEpsilonFilter : FilterBase {
bool allowInputEpsilon() const { return true; }
bool allowMatchEpsilon() const { return true; }
bool allowInputMatchEpsilon() const { return false; }
void hashCombine(std::size_t& h) const {}
bool operator==(NoEpsilonFilter const& o) const { return true; }
void setStart() const {}
friend inline std::ostream& operator<<(std::ostream& out, NoEpsilonFilter const& self) {
return out << '.';
}
};
/**
an epsilon sequencing filter that forces taking all the possible epsilons in A first before taking any from
B
(see
http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en/us/pubs/archive/37568.pdf)
0 if (o[e1], i[e2]) = (x, x) with x terminal,
0 if (o[e1], i[e2]) = (<eps>, ) and q3 = 0,
1 if (o[e1], i[e2]) = (, <eps>),
*/
struct Epsilon1First : FilterBase {
char s;
void normal() { s = 0; }
bool allowInputEpsilon() const { return true; }
void inputEpsilon() { s = 1; }
bool allowMatchEpsilon() const { return s == 0; }
void matchEpsilon() {} // s = 0
bool allowInputMatchEpsilon() const { return false; }
void hashCombine(std::size_t& h) const { h ^= ((std::size_t)-1) * s; }
bool operator==(Epsilon1First const& o) const { return s == o.s; }
void setStart() { s = false; }
friend inline std::ostream& operator<<(std::ostream& out, Epsilon1First const& self) {
out << (self.s ? '^' : '_');
return out;
}
};
/**
epsilon-matching filter
(see
http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en/us/pubs/archive/37568.pdf)
filter like Epsilon1First but preferring to take x:<eps> <eps>:y as a single
arc x:y. this may be slower or faster than Epsilon1First depending on
structure - generally, it's possible to save on arcs by introducing states;
this method benefits from that sharing less. on the other hand, if
unbalanced/unbounded input/output epsilons aren't common, this could produce
a smaller output.
q3' is:
0 if (o[e1], i[e2]) = (x, x) with x terminal,
0 if (o[e1], i[e2]) = (<eps>, <eps>) and q3 = 0, 'InputMatchEpsilon'
1 if (o[e1], i[e2]) = (, <eps>) and q3 != 2, 'MatchEpsilon'
2 if (o[e1], i[e2]) = (<eps>, ) and q3 != 1, 'InputEpsilon'
(0,1,2 are all final)
*/
struct EpsilonCombine : Epsilon1First {
bool allowInputEpsilon() const { return s != 1; }
void inputEpsilon() { s = 2; }
bool allowMatchEpsilon() const { return s != 2; }
void matchEpsilon() { s = 1; }
bool allowInputMatchEpsilon() const { return s == 0; }
void inputMatchEpsilon() {
assert(s == 0); // because we only go from 0 to 0 for input+match epsilon.
}
void hashCombine(std::size_t& h) const { h ^= (h >> (s + 1)) + s; }
friend inline std::ostream& operator<<(std::ostream& out, EpsilonCombine const& self) {
out << (self.s == 2 ? '#' : self.s ? '^' : '_');
return out;
}
};
/**
state in composition of input * match. (Filter: empty base optimization for NoEpsilonFilter)
*/
template <class InputStateId, class Filter = NoEpsilonFilter, class MatchStateId = StateId>
struct Compose2State : public Filter {
typedef InputStateId InputState;
typedef MatchStateId MatchState;
InputState input;
MatchState match;
void set_null_impl() {
::adl::adl_set_null(input);
setFilterStart();
::adl::adl_set_null(match);
}
friend inline void set_null(Compose2State& x) { x.set_null_impl(); }
friend inline std::ostream& operator<<(std::ostream& out, Compose2State const& self) {
out << self.input << (Filter const&)self << self.match;
return out;
}
Filter& filter() const { return *(Filter const*)this; }
Filter& filter() { return *(Filter*)this; }
void setFilterStart() { Filter::setStart(); }
typedef Compose2State self_type;
friend inline std::size_t hash_value(self_type const& x) {
std::size_t h = boost::hash<MatchState>()(x.match);
boost::hash_combine(h, x.input);
x.hashCombine(h);
return h;
}
bool operator==(Compose2State const& other) const {
return input == other.input && Filter::operator==(other) && match == other.match;
}
};
/**
TimesByFn is for computing result weights.
*/
template <class ArcT>
struct HypergraphMatchFst : HypergraphFst<ArcT> {
typedef IMutableHypergraph<ArcT> Hg;
typedef HypergraphFst<ArcT> Base;
typedef IHypergraph<ArcT> ConstHg;
typedef typename ArcT::Weight Weight;
typedef typename Weight::FloatT Distance;
typedef StateId State;
/**
if we know levels of input and match (both are acyclic), then we can do
perfect beamed search. of course, we might want to use per-input-level
beams only (which is fine
*/
Level combinedLevel(Level inputLevel, State st) const {
return this->nLevels == 1 ? inputLevel : (inputLevel * this->nLevels) + this->level(st);
}
Hg const& hg() const { return static_cast<Hg const&>(*this->pHg); }
/**
must have kSortedOutArcs already.
*/
HypergraphMatchFst(shared_ptr<Hg const> const& hg,
WhichFstComposeSpecials which = WhichFstComposeSpecials::undefined()) {
init(hg, which);
}
/**
sorts for you if needed.
*/
HypergraphMatchFst(shared_ptr<Hg> const& hg,
WhichFstComposeSpecials which = WhichFstComposeSpecials::undefined()) {
init(hg, which);
}
HypergraphMatchFst(Hg const& hg, WhichFstComposeSpecials which = WhichFstComposeSpecials::undefined()) {
init(hg, which);
}
/**
arcs matching input. must call explicitly for epsilon, rho, etc.
*/
typedef typename Base::Arcs Matches;
Matches arcsMatchingInput(StateId s, Sym in) const {
return Matches(hg().outArcsMatchingInput(s, in), this->arcFn);
}
WhichFstComposeSpecials whichSpecials;
protected:
template <class Hg>
void initSpecials(Hg const& hg, WhichFstComposeSpecials which) {
whichSpecials = which.defined() ? which : hg.whichInputFstComposeSpecials();
}
void init(shared_ptr<Hg> const& pHg, WhichFstComposeSpecials which) {
pHg->forceProperties(kSortedOutArcs);
initSpecials(*pHg, which);
Base::init(static_pointer_cast<Hg const>(pHg));
}
void init(shared_ptr<ConstHg const> const& pHg, WhichFstComposeSpecials which) {
if (!(pHg->properties() & kSortedOutArcs))
SDL_THROW_LOG(fs.Compose, ConfigException, "match hypergraph must have sorted out arcs");
initSpecials(*pHg, which);
this->needMutable(*pHg);
Base::init(pHg);
}
void init(ConstHg const& hg, WhichFstComposeSpecials which) { init(ptrNoDelete(hg), which); }
void init(Hg& hg, WhichFstComposeSpecials which) { init(ptrNoDelete(hg), which); }
};
/**
for composing with a MatchFst that has a single score that we wish to mix into an input feature weight,
using MixFeature. to join FeatureWeight MatchFst, see MixWeights instead.
*/
template <class ResultWeight, class InWeight, class Enable = void>
struct TimesByMix {
typedef ResultWeight result_type;
MixFeature<FeatureId, typename ResultWeight::FloatT> mix;
void timesBy(InWeight const& weight, ResultWeight& result) const { mix(weight.getValue(), result); }
template <class Weight>
result_type operator()(ResultWeight const& inputWt, Weight const& matchWt) const {
result_type r((inputWt));
timesBy(matchWt, r);
return r;
}
};
/**
this version for featureweight*featureweight.
*/
template <class FeatureWeight>
struct TimesByMix<FeatureWeight, FeatureWeight, typename FeatureWeight::IsFeatureWeight> {
typedef FeatureWeight result_type;
MixFeature<FeatureId, typename FeatureWeight::FloatT> mix;
void timesBy(FeatureWeight const& weight, FeatureWeight& result) const {
result.timesByScaled(weight, mix.scale);
}
result_type operator()(FeatureWeight const& inputWt, FeatureWeight const& matchWt) const {
result_type r((inputWt));
timesBy(matchWt, r);
return r;
}
};
/**
InputFst = e.g. HypergraphFst<Arc> or ComposeFst<...>, MatchFst = HypergraphMatchFst<Arc>.
or InputFst = ComposeFst<...>
*/
template <class InputFst, class MatchFst, class Filter = Epsilon1First,
class TimesFn = TimesByMix<typename InputFst::Weight, typename MatchFst::Weight>>
struct ComposeFst : TimesFn {
typedef ComposeFst<InputFst, MatchFst, Filter, TimesFn> Compose;
typedef TimesFn Times;
typedef InputFst Input;
typedef MatchFst Match;
template <class Init>
void initInput(Init& seed) {
if (!input) input.reset(new Input(seed));
}
template <class Init>
void initMatch(Init& seed) {
if (!match) match.reset(new Match(seed));
}
template <class InitInput, class InitMatch>
void init(InitInput const& initForInput, InitMatch const& initForMatch) {
initInput(initForInput);
initMatch(initForMatch);
}
IVocabularyPtr getVocabulary() const { return input->getVocabulary(); }
typedef shared_ptr<Input> InputPtr;
typedef shared_ptr<Match> MatchPtr;
typedef typename Input::State InputState;
typedef typename Match::State MatchState;
typedef Compose2State<InputState, Filter, MatchState> State;
typedef typename Input::Arc InputArc;
typedef typename Match::Arc MatchArc;
typedef typename Input::Arcs InputArcs;
typedef typename Input::Distance Distance;
typedef typename Match::Matches MatchArcs;
typedef typename Input::Weight InputWeight;
typedef typename Match::Weight MatchWeight;
typedef typename Times::result_type Weight;
typedef FstArc<Weight, State> Arc;
/**
overall scheme: generator of generators, best-first
emit a generator for (ArcsGen) each input arc, before and after input arcs
note: some of the generators may be empty; this is handled correctly by FlattenGenerators
*/
struct ArcsGen : Util::GeneratorBase<ArcsGen, Arc, Util::NonPeekableT>, Filter, Times {
typedef Arc result_type;
Filter& filter() { // empty base (NoEpsilonFilter) optimization
return *(Filter*)this;
}
// enum { kPreSigma, kMidSigma, kDoneSigma };
/**
exact determination in advance of whether there are more arcs to come. (we could use a null arc to
simplify)
*/
operator bool() const { return hasMore; }
void setDone() { hasMore = false; }
Arc operator()() {
Arc r; // could make peekable by r as member, init by pop() once when creating. could save us from
// detecting empty range in advance
LabelPair const& inLabels = inArc.labelPair;
r.dst.input = inArc.dst;
IF_SDL_HYPERGRAPH_FS_ANNOTATIONS(r.annotations = inArc.annotations;)
r.dst.filter() = *(Filter const*)this;
LabelPair& rLabels = r.labelPair;
rLabels.first = inLabels.first;
assert(hasMore);
if (inLabels.second == EPSILON::ID) { // two primary cases: input arc has epsilon output, or not.
if (matchedArcs) { // inputMatchEpsilon
MatchArc const& matchArc = matchedArcs();
assert(matchArc.labelPair.first == EPSILON::ID);
rLabels.second = matchArc.labelPair.second;
r.dst.match = matchArc.dst;
r.weight = Times::operator()(inArc.weight, matchArc.weight);
assert(Filter::allowInputEpsilon()); // because allowMatchEpsilon implies allowInputEpsilon
// after done w/ matchedArcs, take regular input epsilon by 'else' below:
} else {
// then take just input epsilon
assert(Filter::allowInputEpsilon());
rLabels.second = EPSILON::ID;
r.dst.filter().inputEpsilon();
r.weight = inArc.weight;
r.dst.match = matchSrc;
hasMore = false;
}
} else if (midSigma) {
assert(matchedArcs);
MatchArc const& matchArc = matchedArcs();
LabelPair const& matchLabels = matchArc.labelPair;
assert(matchLabels.first == SIGMA::ID); // must be sigma (wildcard)
Sym m2 = matchLabels.second;
r.dst.match = matchArc.dst;
r.weight = Times::operator()(inArc.weight, matchArc.weight);
rLabels.second = (m2 == SIGMA::ID ? inLabels.second : m2);
hasMore = matchedArcs;
} else {
assert(matchedArcs);
// first matched, then sigma (if matched only, we have no input arc)
MatchArc const& matchArc = matchedArcs();
LabelPair const& matchLabels = matchArc.labelPair;
Sym m1 = matchLabels.first, m2 = matchLabels.second;
r.dst.match = matchArc.dst;
if (m1 == EPSILON::ID || m1 == PHI::ID) { // phi or eps; no input arc.
assert(!inLabels.second); // we'll have set this explicitly to avoid above EPSILON::ID branch
r.weight = Times::operator()(Weight::one(), matchArc.weight);
// explicit times vs one since input and match weights are different
// types. i have the result weight as an input weight.
rLabels.second = m2 == PHI::ID ? EPSILON::ID : m2;
if (!matchedArcs) hasMore = false;
} else {
r.weight = Times::operator()(inArc.weight, matchArc.weight);
rLabels.second = (m1 == m2 ? inLabels.second : m2);
// remember that for rho and sigma we output the input symbol iff
// the output of the arc is also rho or sigma respectively
if (!matchedArcs) {
assert(inLabels.second); // else must have been phi or eps (nonconsuming) above
hasMore = initSigma();
}
}
}
return r;
}
bool initSigma() {
if (match->whichSpecials.test(SIGMA::id) && (matchedArcs = match->arcsMatchingInput(matchSrc, SIGMA::ID))) {
midSigma = true;
return true;
} else
return false;
}
bool initRho() {
return match->whichSpecials.test(RHO::id) && (matchedArcs = match->arcsMatchingInput(matchSrc, RHO::ID));
}
ArcsGen() {}
ArcsGen(Times const& times, Match* match, MatchState matchSrc)
: Times(times), match(match), matchSrc(matchSrc), hasMore(true), midSigma(false) {}
Match* match;
MatchArcs matchedArcs;
/// contains input epsilon and input src state if match arc is nonconsuming. otherwise it's an actually
/// arc:
InputArc inArc;
MatchState matchSrc; // used if inArc output label is epsilon, or for initSigma
bool hasMore, midSigma;
//, hasMoreSigma, initSigma; // done or more
// int sigmabytes[sizeof(MatchArcs)/sizeof(int)];
friend inline std::ostream& operator<<(std::ostream& out, ArcsGen const& self) {
out << "ArcsGen {" << self.inArc << " more?=" << self.hasMore;
out << "}";
return out;
}
};
/**
generator of ArcsGen generators, for FlattenGenerators.
1: for all match <eps>:...
2: for each inarc, either
2a: a:<eps> (including possibly using match <eps>:b at same time), or
2b: a:b b:c => a:c, else sigma:c
3: (if no matches at all in 2b), <phi>:...
*/
struct ArcsGenGen : Util::intrusive_refcount<ArcsGenGen, unsigned>,
Util::GeneratorBase<ArcsGenGen, ArcsGen, Util::NonPeekableT>,
Times
// non-atomic count because these are only held by one thread
{
typedef ArcsGen result_type;
enum ConcatState { matchEpsilon, matchRegular, matchDone };
operator bool() const { return concatState != matchDone; }
ArcsGen operator()() {
// returns the next nonempty generator, or else one with status==done (empty)
assert(concatState != matchDone);
ArcsGen r(*this, match.get(), src.match); // could make peekable by r as member.
Filter& filter = r.filter();
filter = src.filter();
if (concatState == matchEpsilon) {
concatState = matchRegular;
if (epsilon) { // match arc only. set phony self-loop input arc
r.matchedArcs = epsilon;
assert(filter.allowMatchEpsilon());
filter.matchEpsilon();
r.inArc.dst = src.input;
r.inArc.labelPair.first = EPSILON::ID;
r.inArc.labelPair.second
= NoSymbol; // intentionally not EPSILON::ID; helps distinguish from real epsilon input arcs
#if SDL_VALGRIND
// weight set to one in ArcsGen so shouldn't need
r.inArc.weight = Weight::one();
#endif
return r;
}
// else continue; no eligible
}
while (inArcs) {
Sym matchSym = (r.inArc = inArcs()).labelPair.second;
if (matchSym) {
if (matchSym == EPSILON::ID) {
// input epsilons don't cause us to exclude a phi in the match transducer.
if (filter.allowInputMatchEpsilon()
&& (r.matchedArcs = match->arcsMatchingInput(src.match, matchSym))) {
filter.inputMatchEpsilon();
assert(filter.allowInputEpsilon());
// will also generate input epsilon (permitted by all 3 filters)
return r;
} else if (filter.allowInputEpsilon()) {
filter.inputEpsilon();
return r;
} else
continue; // skip this arc; filter doesn't allow input epsilon
} else {
if ((r.matchedArcs = match->arcsMatchingInput(src.match, matchSym)))
anyStandardMatch = true; // will initSigma inside r after standard are exhausted
else if (r.initRho() || r.initSigma()) {
} else
continue;
filter.normal();
return r;
}
}
}
concatState = matchDone;
if (!anyStandardMatch && filter.allowMatchEpsilon() && match->whichSpecials.test(PHI::id)
&& (r.matchedArcs = match->arcsMatchingInput(src.match, PHI::ID))) {
filter.matchEpsilon();
r.inArc.dst = src.input;
r.inArc.labelPair.first = EPSILON::ID;
r.inArc.labelPair.second = NoSymbol;
#if SDL_VALGRIND
// r.inArc.weight = Weight::one();
#endif
// weight is set to one in ArcsGen
// maybe todo: keep track of eps matches also and report dead-state-ness. or caller can just detect
// empty outarcs range manually
} else {
r.setDone(); // returns empty range instead
}
// returning a sentinel empty generator is simpler than having a tricky
// operator bool() accounting for this case
return r;
}
ArcsGenGen(State const& src, InputPtr const& input, MatchPtr const& match, Times const& times)
: Times(times)
, src(src)
, inArcs(input->outArcs(src.input))
, match(match)
, concatState(matchEpsilon)
, anyStandardMatch()
, epsilon(match->whichSpecials.test(EPSILON::id) && src.allowMatchEpsilon()
? match->arcsMatchingInput(src.match, EPSILON::ID)
: MatchArcs()) // nonconsuming wildcard
{}
State src;
InputArcs inArcs;
MatchPtr match;
ConcatState concatState; // because we want to emit 3 different types of arcs
bool anyStandardMatch;
MatchArcs epsilon; // we don't save phi because it's not subject to reuse; it's the last thing we do
friend inline std::ostream& operator<<(std::ostream& out, ArcsGenGen const& self) {
out << "ArcsGenGen[";
out << self.src << " stage=" << self.concatState << " any=" << self.anyStandardMatch;
out << "]";
return out;
}
};
typedef DistanceForFstArc<Weight> DistanceFn;
typedef ArcsGenGen GenGenImpl;
typedef boost::intrusive_ptr<GenGenImpl> GenGenPtr;
typedef Util::SharedGenerator<GenGenPtr> GenGen;
typedef Util::FlattenGenerators<GenGen, DistanceFn> ArcsImpl;
typedef boost::intrusive_ptr<ArcsImpl> ArcsPtr;
typedef Util::SharedGenerator<ArcsPtr> Arcs;
Arcs outArcs(State const& src) const {
GenGenPtr pGenGen(new GenGenImpl(src, input, match, *this));
ArcsPtr pArcs(new ArcsImpl(GenGen(pGenGen), DistanceFn()));
return Arcs(pArcs);
}
State startState() const {
State r;
r.input = input->startState();
r.match = match->startState();
r.setFilterStart();
return r;
}
bool final(State const& st) const { return input->final(st.input) && match->final(st.match); }
Level level(State const& st) const {
return input->level(st.input);
// TODO: return match->combinedLevel(input->level(st.input), st.match);
}
Distance heuristic(State const& st) const {
return input->heuristic(st.input) + match->heuristic(st.match);
}
InputPtr input;
MatchPtr match;
};
// viterbi-like (idempotent plus) semirings do not need redundant paths removed unless you want nbest
template <class Weight, class Enable = void>
struct AllowDuplicateFilter {
typedef Epsilon1First type;
};
template <class Weight>
struct AllowDuplicateFilter<Weight, typename std::enable_if<WeightIdempotentPlus<Weight>::value>::type> {
typedef NoEpsilonFilter type;
};
template <template <class> class FstForArc, class Filter, class InHg, class MatchHg, class ArcOut>
void composeWithEpsilonFilterImpl(InHg const& inHg, MatchHg& matchHg, IMutableHypergraph<ArcOut>* outHg,
FstComposeOptions const& opt,
WhichFstComposeSpecials which = WhichFstComposeSpecials::undefined()) {
typedef typename InHg::Arc Arc1;
typedef typename MatchHg::Arc Arc2;
IVocabularyPtr const& vocab = matchHg.getVocabulary();
outHg->setVocabulary(vocab);
if (vocab != inHg.getVocabulary())
SDL_THROW_LOG(Hypergraph.fs.Compose, ConfigException, "input*match FST compose vocabularies must match");
typedef FstForArc<Arc1> Input;
typedef HypergraphMatchFst<Arc2> Match;
typedef ComposeFst<Input, Match, Filter, TimesByMix<typename Arc1::Weight, typename Arc2::Weight>> ComposedLazy;
ComposedLazy composedLazy;
composedLazy.input.reset(new Input(inHg, opt.annotations));
composedLazy.match.reset(new Match(matchHg, which));
composedLazy.mix = opt.mix;
saveFst(composedLazy, *outHg, opt);
}
/**
Filter is an epsilon filter type
to allow duplicates is to use a simpler filter state that doesn't rigorously sequence alternative a:*e* in
inHg and *e*:b in matchHg-this would be harmful in case of Log/Expectation weight because the number of
paths is higher than it should be, but might be faster for Viterbi/Feature weight (with no harm done).
*/
template <class Filter, class Arc1, class MatchHg, class ArcOut>
void composeWithEpsilonFilter(IMutableHypergraph<Arc1>& inHg, MatchHg& matchHg,
IMutableHypergraph<ArcOut>* outHg, FstComposeOptions const& opt,
WhichFstComposeSpecials which = WhichFstComposeSpecials::undefined()) {
bool makeBestFirst = opt.sortBestFirst && opt.usingLazyBest();
if (makeBestFirst) inHg.forceBestFirstArcs();
composeWithEpsilonFilterImpl<HypergraphFst, Filter>(inHg, matchHg, outHg, opt, which);
}
template <class Filter, class Arc1, class MatchHg, class ArcOut>
void composeWithEpsilonFilter(IMutableHypergraph<Arc1> const& inHg, MatchHg& matchHg,
IMutableHypergraph<ArcOut>* outHg, FstComposeOptions const& opt,
WhichFstComposeSpecials which = WhichFstComposeSpecials::undefined()) {
composeWithEpsilonFilterImpl<HypergraphFst, Filter>(inHg, matchHg, outHg, opt, which);
}
template <class Filter, class Arc1, class MatchHg, class ArcOut>
void composeWithEpsilonFilter(IHypergraph<Arc1> const& inHg, MatchHg& matchHg,
IMutableHypergraph<ArcOut>* outHg, FstComposeOptions const& opt,
WhichFstComposeSpecials which = WhichFstComposeSpecials::undefined()) {
composeWithEpsilonFilterImpl<ConstHypergraphFst, Filter>(inHg, matchHg, outHg, opt, which);
}
/**
weight type of arc3 should be same as InHg::Arc.
if InHg is IHypergraph, then we use ConstHypergraphFst, which is slightly
slower than if InHg is IMutableHypergraph (HypergraphFst)
*/
template <class InHg, class MatchHg, class ArcOut>
void compose(InHg& inHg, MatchHg& matchHg, IMutableHypergraph<ArcOut>* outHg, FstComposeOptions const& opt) {
WhichFstComposeSpecials which = matchHg.whichInputFstComposeSpecials();
SDL_DEBUG(Hypergraph.compose, which);
if (opt.allowDuplicatesEffective())
composeWithEpsilonFilter<typename AllowDuplicateFilter<typename InHg::Arc::Weight>::type>(inHg, matchHg,
outHg, opt, which);
else if (opt.epsilonMatchingFilter)
composeWithEpsilonFilter<EpsilonCombine>(inHg, matchHg, outHg, opt, which);
else
composeWithEpsilonFilter<Epsilon1First>(inHg, matchHg, outHg, opt, which);
}
}}}
#endif
| 38.509195 | 120 | 0.676865 | [
"object"
] |
2ac0b1ec69fa9aaac95f97820c9533e5805c953c | 21,143 | cpp | C++ | src/unit_test/hostintf/sai_hostif_unit_test.cpp | Dell-Networking/sonic-sai-common | 0ad86ab7f29732d318013e55fe11e7197c7c1246 | [
"Apache-2.0"
] | 1 | 2020-07-30T02:53:02.000Z | 2020-07-30T02:53:02.000Z | src/unit_test/hostintf/sai_hostif_unit_test.cpp | Dell-Networking/sonic-sai-common | 0ad86ab7f29732d318013e55fe11e7197c7c1246 | [
"Apache-2.0"
] | null | null | null | src/unit_test/hostintf/sai_hostif_unit_test.cpp | Dell-Networking/sonic-sai-common | 0ad86ab7f29732d318013e55fe11e7197c7c1246 | [
"Apache-2.0"
] | 4 | 2016-08-12T19:06:03.000Z | 2020-07-30T02:53:04.000Z | /************************************************************************
* LEGALESE: "Copyright (c) 2015, Dell Inc. All rights reserved."
*
* This source code is confidential, proprietary, and contains trade
* secrets that are the sole property of Dell Inc.
* Copy and/or distribution of this source code or disassembly or reverse
* engineering of the resultant object code are strictly forbidden without
* the written consent of Dell Inc.
*
************************************************************************/
/**
* @file ai_hostif_unit_test.cpp
*
* @brief This file contains the google unit test cases for testing the
* SAI host interface functionality.
*
*************************************************************************/
extern "C" {
#include "sai.h"
#include "saihostintf.h"
#include "saitypes.h"
}
#include "gtest/gtest.h"
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <inttypes.h>
#define SAI_MAX_PORTS 256
static unsigned int port_count = 0;
static sai_object_id_t port_list[SAI_MAX_PORTS] = {0};
static inline void sai_port_evt_callback (uint32_t count,
sai_port_event_notification_t *data)
{
uint32_t port_idx = 0;
sai_object_id_t port_id = 0;
sai_port_event_t port_event;
for(port_idx = 0; port_idx < count; port_idx++) {
port_id = data[port_idx].port_id;
port_event = data[port_idx].port_event;
if(port_event == SAI_PORT_EVENT_ADD) {
if(port_count < SAI_MAX_PORTS) {
port_list[port_count] = port_id;
port_count++;
}
printf("PORT ADD EVENT FOR port 0x%"PRIx64" and total ports count is %d \r\n",
port_id, port_count);
} else if(port_event == SAI_PORT_EVENT_DELETE) {
printf("PORT DELETE EVENT for port 0x%"PRIx64" and total ports count is %d \r\n",
port_id, port_count);
} else {
printf("Invalid PORT EVENT for port 0x%"PRIx64" \r\n", port_id);
}
}
}
static inline void sai_packet_event_callback (const void *buffer,
sai_size_t buffer_size,
uint32_t attr_count,
const sai_attribute_t *attr_list)
{
unsigned int index = 0;
printf("Pkt Size = %lu attr_count = %u\n",buffer_size, attr_count);
for (index = 0; index < attr_count; index++) {
printf("Attribute id=%u\n",attr_list[index].id);
if (SAI_HOSTIF_PACKET_INGRESS_PORT == attr_list[index].id) {
printf("Ingress Port object 0x%"PRIx64".\n",attr_list[index].value.oid);
} else if (SAI_HOSTIF_PACKET_TRAP_ID == attr_list[index].id) {
printf("Trap id = %u\n", attr_list[index].value.s32);
}
}
}
/*
* Stubs for Callback functions to be passed from adaptor host/application
* upon switch initialization API call.
*/
static inline void sai_port_state_evt_callback (uint32_t count,
sai_port_oper_status_notification_t *data)
{
}
static inline void sai_fdb_evt_callback(uint32_t count, sai_fdb_event_notification_data_t *data)
{
}
static inline void sai_switch_operstate_callback (sai_switch_oper_status_t
switchstate)
{
}
static inline void sai_switch_shutdown_callback (void)
{
}
/*
* API query is done while running the first test case and
* the method table is stored in sai_hostif_api_table so
* that its available for the rest of the test cases which
* use the method table
*/
class hostIntfInit : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
sai_switch_notification_t notification;
memset(¬ification, 0, sizeof(sai_switch_notification_t));
/*
* Query and populate the SAI Switch API Table.
*/
EXPECT_EQ (SAI_STATUS_SUCCESS, sai_api_query
(SAI_API_SWITCH, (static_cast<void**>
(static_cast<void*>(&p_sai_switch_api_tbl)))));
ASSERT_TRUE (p_sai_switch_api_tbl != NULL);
/*
* Switch Initialization.
* Fill in notification callback routines with stubs.
*/
notification.on_switch_state_change = sai_switch_operstate_callback;
notification.on_fdb_event = sai_fdb_evt_callback;
notification.on_port_state_change = sai_port_state_evt_callback;
notification.on_switch_shutdown_request = sai_switch_shutdown_callback;
notification.on_port_event = sai_port_evt_callback;
notification.on_packet_event = sai_packet_event_callback;
ASSERT_TRUE(p_sai_switch_api_tbl->initialize_switch != NULL);
EXPECT_EQ (SAI_STATUS_SUCCESS,
(p_sai_switch_api_tbl->initialize_switch (0, NULL, NULL,
¬ification)));
ASSERT_EQ(NULL,sai_api_query(SAI_API_HOST_INTERFACE,
(static_cast<void**>(static_cast<void*>(&sai_hostif_api_table)))));
ASSERT_TRUE(sai_hostif_api_table != NULL);
EXPECT_TRUE(sai_hostif_api_table->create_hostif != NULL);
EXPECT_TRUE(sai_hostif_api_table->remove_hostif != NULL);
EXPECT_TRUE(sai_hostif_api_table->set_hostif_attribute != NULL);
EXPECT_TRUE(sai_hostif_api_table->get_hostif_attribute !=NULL);
EXPECT_TRUE(sai_hostif_api_table->create_hostif_trap_group !=NULL);
EXPECT_TRUE(sai_hostif_api_table->remove_hostif_trap_group !=NULL);
EXPECT_TRUE(sai_hostif_api_table->set_trap_group_attribute !=NULL);
EXPECT_TRUE(sai_hostif_api_table->get_trap_group_attribute !=NULL);
EXPECT_TRUE(sai_hostif_api_table->set_trap_attribute !=NULL);
EXPECT_TRUE(sai_hostif_api_table->get_trap_attribute !=NULL);
EXPECT_TRUE(sai_hostif_api_table->set_user_defined_trap_attribute !=NULL);
EXPECT_TRUE(sai_hostif_api_table->get_user_defined_trap_attribute !=NULL);
EXPECT_TRUE(sai_hostif_api_table->recv_packet !=NULL);
EXPECT_TRUE(sai_hostif_api_table->send_packet !=NULL);
}
static sai_switch_api_t *p_sai_switch_api_tbl;
static sai_hostif_api_t *sai_hostif_api_table;
static sai_status_t sai_test_create_trapgroup(sai_object_id_t *group,
bool admin_state,
unsigned int cpu_queue);
};
sai_hostif_api_t* hostIntfInit::sai_hostif_api_table = NULL;
sai_switch_api_t *hostIntfInit::p_sai_switch_api_tbl = NULL;
#define SAI_MAX_TRAP_GROUP_ATTRS 4
#define SAI_GTEST_CPU_QUEUE_1 1
#define SAI_GTEST_CPU_QUEUE_2 2
sai_status_t hostIntfInit :: sai_test_create_trapgroup(sai_object_id_t *group,
bool admin_state,
unsigned int cpu_queue)
{
sai_attribute_t attr_list[SAI_MAX_TRAP_GROUP_ATTRS] = {0};
unsigned int attr_count = 0;
sai_status_t rc = SAI_STATUS_FAILURE;
attr_list[attr_count].id = SAI_HOSTIF_TRAP_GROUP_ATTR_ADMIN_STATE;
attr_list[attr_count].value.booldata = admin_state;
attr_count++;
attr_list[attr_count].id = SAI_HOSTIF_TRAP_GROUP_ATTR_QUEUE;
attr_list[attr_count].value.u32 = cpu_queue;
attr_count++;
attr_list[attr_count].id = SAI_HOSTIF_TRAP_GROUP_ATTR_PRIO;
attr_list[attr_count].value.u32 = 0;
attr_count++;
rc = sai_hostif_api_table->create_hostif_trap_group(group, attr_count,
attr_list);
return rc;
}
TEST_F(hostIntfInit, default_trap_group_operations)
{
sai_status_t rc = SAI_STATUS_FAILURE;
sai_attribute_t attr = {0};
sai_object_id_t trap_group_oid = 0;
memset(&attr, 0, sizeof(sai_attribute_t));
attr.id = SAI_SWITCH_ATTR_DEFAULT_TRAP_GROUP;
rc = p_sai_switch_api_tbl->get_switch_attribute(1, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
/*Default trap group object should not be NULL*/
ASSERT_NE (attr.value.oid, SAI_NULL_OBJECT_ID);
trap_group_oid = attr.value.oid;
/*Default trap group object is read only and cannot be set*/
/*Trying a negative test case*/
attr.id = SAI_SWITCH_ATTR_DEFAULT_TRAP_GROUP;
rc = p_sai_switch_api_tbl->set_switch_attribute(&attr);
ASSERT_NE (rc, SAI_STATUS_SUCCESS);
/* Default trap group points to CPU queue 0 and the key for trap group is
* the cpu queue. So creating another trap group with cpu queue 0 would
* not be allowed. Testing this case.
*/
rc = sai_test_create_trapgroup(&trap_group_oid, true, 0);
ASSERT_NE (rc, SAI_STATUS_SUCCESS);
/*Default trap group object cannot be removed*/
/*Trying a negative test case*/
rc = sai_hostif_api_table->remove_hostif_trap_group(trap_group_oid);
ASSERT_NE (rc, SAI_STATUS_SUCCESS);
}
TEST_F(hostIntfInit, create_remove_trapgroup)
{
sai_status_t rc = SAI_STATUS_FAILURE;
sai_object_id_t trap_group_oid = 0;
rc = sai_test_create_trapgroup(&trap_group_oid, true, SAI_GTEST_CPU_QUEUE_1);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
rc = sai_hostif_api_table->remove_hostif_trap_group(trap_group_oid);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
}
TEST_F(hostIntfInit, set_get_trapgroup)
{
sai_status_t rc = SAI_STATUS_FAILURE;
sai_object_id_t trap_group_oid = 0;
sai_attribute_t attr[2] = {0};
rc = sai_test_create_trapgroup(&trap_group_oid, true, SAI_GTEST_CPU_QUEUE_2);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
memset(&attr, 0, sizeof(attr));
attr[0].id = SAI_HOSTIF_TRAP_GROUP_ATTR_QUEUE;
attr[1].id = SAI_HOSTIF_TRAP_GROUP_ATTR_ADMIN_STATE;
rc = sai_hostif_api_table->get_trap_group_attribute(trap_group_oid, 2, attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
EXPECT_EQ(attr[0].value.u32, SAI_GTEST_CPU_QUEUE_2);
EXPECT_EQ(attr[1].value.booldata, true);
attr[0].id = SAI_HOSTIF_TRAP_GROUP_ATTR_QUEUE;
attr[0].value.u32 = SAI_GTEST_CPU_QUEUE_1;
rc = sai_hostif_api_table->set_trap_group_attribute(trap_group_oid, attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
memset(&attr, 0, sizeof(attr));
attr[0].id = SAI_HOSTIF_TRAP_GROUP_ATTR_QUEUE;
attr[1].id = SAI_HOSTIF_TRAP_GROUP_ATTR_ADMIN_STATE;
rc = sai_hostif_api_table->get_trap_group_attribute(trap_group_oid, 2, attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
EXPECT_EQ(attr[0].value.u32, SAI_GTEST_CPU_QUEUE_1);
EXPECT_EQ(attr[1].value.booldata, true);
rc = sai_hostif_api_table->remove_hostif_trap_group(trap_group_oid);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
}
TEST_F(hostIntfInit, set_ttl_trap)
{
sai_status_t rc = SAI_STATUS_FAILURE;
sai_object_id_t trap_group_oid = 0;
sai_attribute_t attr = {0}, attr_list[2] = {0};
rc = sai_test_create_trapgroup(&trap_group_oid, true, SAI_GTEST_CPU_QUEUE_2);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_PACKET_ACTION;
attr.value.s32 = SAI_PACKET_ACTION_TRAP;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_TTL_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = trap_group_oid;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_TTL_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr_list[0].id = SAI_HOSTIF_TRAP_ATTR_PACKET_ACTION;
attr_list[1].id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
rc = sai_hostif_api_table->get_trap_attribute(SAI_HOSTIF_TRAP_ID_TTL_ERROR, 2, attr_list);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
EXPECT_EQ(attr_list[0].value.s32, SAI_PACKET_ACTION_TRAP);
EXPECT_EQ(attr_list[1].value.oid, trap_group_oid);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = SAI_NULL_OBJECT_ID;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_TTL_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
rc = sai_hostif_api_table->remove_hostif_trap_group(trap_group_oid);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
}
TEST_F(hostIntfInit, set_l3_mtu_failure_trap)
{
sai_status_t rc = SAI_STATUS_FAILURE;
sai_object_id_t trap_group_oid = 0;
sai_attribute_t attr = {0}, attr_list[2] = {0};
rc = sai_test_create_trapgroup(&trap_group_oid, true, SAI_GTEST_CPU_QUEUE_1);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_PACKET_ACTION;
attr.value.s32 = SAI_PACKET_ACTION_TRAP;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_L3_MTU_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = trap_group_oid;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_L3_MTU_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr_list[0].id = SAI_HOSTIF_TRAP_ATTR_PACKET_ACTION;
attr_list[1].id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
rc = sai_hostif_api_table->get_trap_attribute(SAI_HOSTIF_TRAP_ID_L3_MTU_ERROR, 2, attr_list);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
EXPECT_EQ(attr_list[0].value.s32, SAI_PACKET_ACTION_TRAP);
EXPECT_EQ(attr_list[1].value.oid, trap_group_oid);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = SAI_NULL_OBJECT_ID;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_L3_MTU_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
rc = sai_hostif_api_table->remove_hostif_trap_group(trap_group_oid);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
}
TEST_F(hostIntfInit, set_samplepacket_trap)
{
sai_status_t rc = SAI_STATUS_FAILURE;
sai_object_id_t trap_group_oid = 0;
sai_attribute_t attr = {0};
rc = sai_test_create_trapgroup(&trap_group_oid, true, SAI_GTEST_CPU_QUEUE_1);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = trap_group_oid;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_SAMPLEPACKET, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
memset(&attr, 0, sizeof(sai_attribute_t));
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
rc = sai_hostif_api_table->get_trap_attribute(SAI_HOSTIF_TRAP_ID_SAMPLEPACKET, 1, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
EXPECT_EQ(attr.value.oid, trap_group_oid);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = SAI_NULL_OBJECT_ID;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_SAMPLEPACKET, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
rc = sai_hostif_api_table->remove_hostif_trap_group(trap_group_oid);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
}
TEST_F(hostIntfInit, set_dhcp_trap)
{
sai_status_t rc = SAI_STATUS_FAILURE;
sai_object_id_t trap_group_oid = 0;
sai_object_list_t portlist = {0};
sai_attribute_t attr = {0}, attr_list[4] = {0};
rc = sai_test_create_trapgroup(&trap_group_oid, true, SAI_GTEST_CPU_QUEUE_2);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = trap_group_oid;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_DHCP, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_PRIORITY;
attr.value.u32 = 5;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_DHCP, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
portlist.count = 2;
portlist.list = (sai_object_id_t *) calloc(portlist.count, sizeof(sai_object_id_t));
portlist.list[0] = port_list[port_count - 2];
portlist.list[1] = port_list[port_count - 1];
attr.id = SAI_HOSTIF_TRAP_ATTR_PORT_LIST;
attr.value.objlist = portlist;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_DHCP, &attr);
free(portlist.list );
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_PACKET_ACTION;
attr.value.s32 = SAI_PACKET_ACTION_TRAP;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_DHCP, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr_list[0].id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr_list[1].id = SAI_HOSTIF_TRAP_ATTR_TRAP_PRIORITY;
attr_list[2].id = SAI_HOSTIF_TRAP_ATTR_PORT_LIST;
attr_list[2].value.objlist.count = 2;
attr_list[2].value.objlist.list = (sai_object_id_t *)
calloc(attr_list[2].value.objlist.count,
sizeof(sai_object_id_t));
attr_list[3].id = SAI_HOSTIF_TRAP_ATTR_PACKET_ACTION;
rc = sai_hostif_api_table->get_trap_attribute(SAI_HOSTIF_TRAP_ID_DHCP,
4, attr_list);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
EXPECT_EQ (attr_list[0].value.oid, trap_group_oid);
EXPECT_EQ (attr_list[1].value.u32, 5);
EXPECT_EQ (attr_list[2].value.objlist.count, 2);
EXPECT_EQ (attr_list[3].value.s32, SAI_PACKET_ACTION_TRAP);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = SAI_NULL_OBJECT_ID;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_DHCP, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
rc = sai_hostif_api_table->remove_hostif_trap_group(trap_group_oid);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
}
TEST_F(hostIntfInit, share_set_trap_group)
{
sai_status_t rc = SAI_STATUS_FAILURE;
sai_object_id_t trap_group_oid = 0;
sai_attribute_t attr = {0};
rc = sai_test_create_trapgroup(&trap_group_oid, true, SAI_GTEST_CPU_QUEUE_1);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_PACKET_ACTION;
attr.value.s32 = SAI_PACKET_ACTION_TRAP;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_L3_MTU_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = trap_group_oid;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_L3_MTU_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_PACKET_ACTION;
attr.value.s32 = SAI_PACKET_ACTION_TRAP;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_TTL_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = trap_group_oid;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_TTL_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_GROUP_ATTR_QUEUE;
attr.value.u32 = SAI_GTEST_CPU_QUEUE_2;
rc = sai_hostif_api_table->set_trap_group_attribute(trap_group_oid, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
attr.id = SAI_HOSTIF_TRAP_ATTR_TRAP_GROUP;
attr.value.oid = SAI_NULL_OBJECT_ID;
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_L3_MTU_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
rc = sai_hostif_api_table->set_trap_attribute(SAI_HOSTIF_TRAP_ID_TTL_ERROR, &attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
rc = sai_hostif_api_table->remove_hostif_trap_group(trap_group_oid);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
}
TEST_F(hostIntfInit, send_pkt_pipeline_bypass)
{
sai_attribute_t sai_attr[2];
sai_status_t rc = SAI_STATUS_FAILURE;
unsigned char buffer[] =
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x82, 0x2f,
0x2e, 0x42, 0x46, 0x74, 0x08, 0x06, 0x00, 0x01,
0x08, 0x00, 0x06, 0x04, 0x00, 0x01, 0x82, 0x2f,
0x2e, 0x42, 0x46, 0x74, 0x0a, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00};
sai_attr[0].id = SAI_HOSTIF_PACKET_EGRESS_PORT_OR_LAG;
sai_attr[0].value.oid = port_list[port_count - 1];
sai_attr[1].id = SAI_HOSTIF_PACKET_TX_TYPE;
sai_attr[1].value.s32 = SAI_HOSTIF_TX_TYPE_PIPELINE_BYPASS;
rc = sai_hostif_api_table->send_packet(SAI_NULL_OBJECT_ID, buffer,
sizeof(buffer), 2, &sai_attr[0]);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
}
TEST_F(hostIntfInit, send_pkt_pipeline_lookup)
{
sai_attribute_t sai_attr = {0};
sai_status_t rc = SAI_STATUS_FAILURE;
unsigned char buffer[] =
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x82, 0x2f,
0x2e, 0x42, 0x46, 0x74, 0x08, 0x06, 0x00, 0x01,
0x08, 0x00, 0x06, 0x04, 0x00, 0x01, 0x82, 0x2f,
0x2e, 0x42, 0x46, 0x74, 0x0a, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00};
sai_attr.id = SAI_HOSTIF_PACKET_TX_TYPE;
sai_attr.value.s32 = SAI_HOSTIF_TX_TYPE_PIPELINE_LOOKUP;
rc = sai_hostif_api_table->send_packet(SAI_NULL_OBJECT_ID, buffer,
sizeof(buffer), 1, &sai_attr);
ASSERT_EQ (rc, SAI_STATUS_SUCCESS);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 36.898778 | 108 | 0.692002 | [
"object"
] |
2ac6d8f7eb497a2ef6111b42b4ce00eeb9122e47 | 5,657 | cpp | C++ | AtCoder/ABC/200/D.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | 2 | 2018-12-11T14:37:24.000Z | 2022-01-23T18:11:54.000Z | AtCoder/ABC/200/D.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | AtCoder/ABC/200/D.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
// g++ -std=c++17 -Wl,-stack_size -Wl,0x10000000 main.cpp
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1000000001
#define MOD 1000000007
#define EPS 1e-6
#define ll long long int
#define ld long double
#define fi first
#define se second
#define all(v) v.begin(),v.end()
#define pr(v) { for(int i=0;i<v.size();i++) { v[i]==INF? cout<<"INF " : cout<<v[i]<<" "; } cout<<endl;}
#define t1(x) cerr<<#x<<" : "<<x<<endl
#define t2(x, y) cerr<<#x<<" : "<<x<<" "<<#y<<" : "<<y<<endl
#define t3(x, y, z) cerr<<#x<<" : " <<x<<" "<<#y<<" : "<<y<<" "<<#z<<" : "<<z<<endl
#define t4(a,b,c,d) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<endl
#define t5(a,b,c,d,e) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<endl
#define t6(a,b,c,d,e,f) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<" "<<#f<<" : "<<f<<endl
#define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME
#define t(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__)
#define _ cerr<<"here"<<endl;
#define __ {ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);}
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class A, class B> ostream& operator<<(ostream& out, const pair<A, B> &a){ return out<<"("<<a.first<<", "<<a.second<<")";}
template <int> ostream& operator<<(ostream& os, const vector<int>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { if(v[i]!=INF) os << v[i]; else os << "INF";if (i != v.size() - 1) os << ", "; } os << "]"; return os; }
template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { os << v[i]; ;if (i != v.size() - 1) os << ", "; } os << "]\n"; return os; }
vector<int> getIndices(vector<int> &v, int n, int &index) {
const int N = 200;
vector<vector<int> > dp(n, vector<int>(N));
vector<vector<int> > back(n, vector<int>(N, -1));
dp[0][v[0] % N] = 1;
// dp[0][0] = 1;
for(int i = 1; i < n; i++) {
dp[i][v[i] % N] = 1;
for(int j = 0; j < N; j++) {
if(index == -1) {
if(dp[i-1][((j - v[i]%N) + N) % N] > 0) {
back[i][j] = ((j - v[i]%N) + N) % N;
}
if(dp[i-1][j] > 0) {
back[i][j] = j;
}
} else {
if(dp[i-1][j] > 0) {
back[i][j] = j;
}
if(dp[i-1][((j - v[i]%N) + N) % N] > 0) {
back[i][j] = ((j - v[i]%N) + N) % N;
}
}
dp[i][j] += dp[i-1][j] + dp[i-1][((j - v[i]%N) + N) % N];
// dp[i][((j + v[i]) % N)] += dp[i-1][((j + v[i]) % N)] + dp[i-1][j];
}
}
int backIndex = index;
if(index == -1) {
for(int j = 0; j < 200; j++) {
if(dp[n-1][j] > 1) {
backIndex = j;
break;
}
}
}
index = backIndex;
// t(dp);
if(backIndex == -1) {
vector<int> ansIndex;
return ansIndex;
} else {
int currI = n-1;
vector<int> ansIndex;
while(backIndex != -1) {
// t(backIndex, ansIndex, currI);
int tempIndex = back[currI][backIndex];
// t(tempIndex);
if((tempIndex != backIndex && v[currI] != 0)) {
ansIndex.pu(currI + 1);
if(tempIndex == -1) break;
}
backIndex = tempIndex;
currI--;
}
return ansIndex;
// t(ansIndex);
// cout << "Yes" << endl;
// cout << 1 << " " << ansIndex.front() << endl;
// cout << ansIndex.size() - 1 << " ";
// for(int i = 1; i < ansIndex.size(); i++) cout << ansIndex[i] << " "; cout << endl;
}
}
int main() {
__;
const int N = 200;
int n;
cin >> n;
vector<int> v(n);
for(int i = 0; i < n; i++) cin >> v[i];
{
vector<vector<int> > easyAns(200);
for(int i = 0; i < n; i++) {
easyAns[v[i] % N].pu(i+1);
}
for(int j = 0; j < 200; j++) {
if(easyAns[j].size() > 1) {
cout << "Yes" << endl;
cout << 1 << " " << easyAns[j].front() << endl;
cout << 1 << " " << easyAns[j].back() << endl;
return 0;
}
}
}
// vector<vector<int> > back(n, vector<int>(N, -1));
int index = -1;
vector<int> indices1 = getIndices(v, n, index);
// t(index);
if(index == -1) {
cout << "No" << endl;
return 0;
}
// set<int> s(indices1.begin(), indices1.end());
// vector<int> w;
// for(int i = 0; i < n; i++) {
// if(s.count(i+1)) {
// w.pu(0);
// } else {
// w.pu(v[i]);
// }
// }
vector<int> indices2 = getIndices(v, n, index);
sort(indices1.begin(), indices1.end());
sort(indices2.begin(), indices2.end());
set<int> s1(indices1.begin(), indices1.end());
set<int> s2(indices2.begin(), indices2.end());
set<int> s3;
for(auto it : s1) {
if(s2.count(it)) s3.insert(it);
}
for(auto it : s3) {
s1.erase(it);
s2.erase(it);
}
cout << "Yes" << endl;
cout << s1.size() << " ";
for(auto it : s1) cout << it << " "; cout << endl;
cout << s2.size() << " ";
for(auto it : s2) cout << it << " "; cout << endl;
return 0;
}
| 32.889535 | 224 | 0.416652 | [
"vector"
] |
2ad0ed5dab893c1bbe72924620c67c724c2b43fe | 1,335 | cpp | C++ | src/chesslbl.cpp | elvisxiaozhi/For-English-Learner | 88dd74ff2d6b9c77cf40e7dc376d278368bc861b | [
"MIT"
] | null | null | null | src/chesslbl.cpp | elvisxiaozhi/For-English-Learner | 88dd74ff2d6b9c77cf40e7dc376d278368bc861b | [
"MIT"
] | 1 | 2018-09-23T14:00:06.000Z | 2018-09-23T14:00:06.000Z | src/chesslbl.cpp | elvisxiaozhi/For-English-Learner | 88dd74ff2d6b9c77cf40e7dc376d278368bc861b | [
"MIT"
] | null | null | null | #include "chesslbl.h"
#include <QMouseEvent>
const int ChessLbl::circle = 0;
const int ChessLbl::cross = 1;
const int ChessLbl::unfilled = 2;
ChessLbl::ChessLbl(QWidget *parent, int row, int col) : QLabel(parent), isCross(unfilled)
{
this->row = row;
this->col = col;
setMinimumSize(87, 87);
setPixmap(QPixmap());
setAlignment(Qt::AlignCenter);
setBorder(row * 3 + col);
}
void ChessLbl::setBorder(int index)
{
switch(index) {
case 1:
setStyleSheet("QLabel { border-style: solid; border-color: #29a3a3; border-width: 0px 7px; }");
break;
case 3:
setStyleSheet("QLabel { border-style: solid; border-color: #29a3a3; border-width: 7px 0px; }");
break;
case 4:
setStyleSheet("QLabel { border-style: solid; border-color: #29a3a3; border-width: 7px 7px; }");
break;
case 5:
setStyleSheet("QLabel { border-style: solid; border-color: #29a3a3; border-width: 7px 0px; }");
break;
case 7:
setStyleSheet("QLabel { border-style: solid; border-color: #29a3a3; border-width: 0px 7px; }");
break;
default:
break;
}
}
void ChessLbl::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton) {
emit clicked(row, col);
}
}
| 27.8125 | 104 | 0.598502 | [
"solid"
] |
2ad4f1fdb931defcb5f52f480c8b339b87ea2b0e | 22,376 | cpp | C++ | src/test/performanceTester.cpp | Tobi2001/asr_psm | 18f0959c4a69a6e254d7b53a4d6cc6e6b28f0ccc | [
"BSD-3-Clause"
] | 1 | 2019-10-29T13:37:30.000Z | 2019-10-29T13:37:30.000Z | src/test/performanceTester.cpp | Tobi2001/asr_psm | 18f0959c4a69a6e254d7b53a4d6cc6e6b28f0ccc | [
"BSD-3-Clause"
] | null | null | null | src/test/performanceTester.cpp | Tobi2001/asr_psm | 18f0959c4a69a6e254d7b53a4d6cc6e6b28f0ccc | [
"BSD-3-Clause"
] | 1 | 2019-11-03T14:00:30.000Z | 2019-11-03T14:00:30.000Z |
#include <ros/package.h>
#include <boost/filesystem/path.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <ISM/utility/TableHelper.hpp>
#include "learner/SceneLearningEngine.h"
#include "inference/model/SceneModelDescription.h"
#include <sys/time.h>
#include <string>
#include <chrono>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
using boost::posix_time::ptime;
using boost::posix_time::time_duration;
using boost::filesystem::path;
using namespace ISM;
using namespace ProbabilisticSceneRecognition;
using namespace boost::posix_time;
std::vector<unsigned> objectCounts = {
3, 4, 5
};
std::vector<unsigned> timestepCounts = {
100, 200, 300, 400
};
std::string testSetFolder = "ValidationSets";
std::string testSetFolderNoRefs = "TestSetsNoRefs";
std::string validTestSetPref = "validValidationSets_";
std::string invalidTestSetPref = "invalidValidationSets_";
std::string outputPath;
std::vector<std::string> testSets;
std::vector<std::string> testSetsNoRefs;
std::vector<std::string> demoRecordings;
std::vector<std::string> demoRecordingsNames;
double recognitionThreshold = 1.0e-04;
// overwritten in training, used for performance tests:
std::string inferenceAlgorithm = "maximum";
std::string treeAlgorithm = "fullymeshed";
std::string optimizationAlgorithm = "RecordHunt";
bool train = false;
bool test = !train; // recognition runtime
double scale, sigma;
std::string frameId;
void setDefaultParameters()
{
ros::NodeHandle nh("~");
nh.setParam("scene_model_type", "ocm");
nh.setParam("workspace_volume", 8.0);
nh.setParam("static_break_ratio", 1.01);
nh.setParam("together_ratio", 0.90);
nh.setParam("intermediate_results", false);
nh.setParam("timestamps", false);
nh.setParam("kernels_min", 1);
nh.setParam("kernels_max", 5);
nh.setParam("runs_per_kernel", 3);
nh.setParam("synthetic_samples", 10);
nh.setParam("interval_position", 0.25);
nh.setParam("interval_orientation", 10);
nh.setParam("orientation_plot_path", "UNDEFINED");
nh.setParam("max_angle_deviation", 45);
frameId = "/PTU";
nh.setParam("base_frame_id", frameId);
scale = 1.0;
nh.setParam("scale_factor", scale);
sigma = 3.0;
nh.setParam("sigma_multiplicator", sigma);
nh.setParam("attempts_per_run", 10);
//SHARED PARAMETERS:
nh.setParam("targeting_help", false);
nh.setParam("inference_algorithm", inferenceAlgorithm);
// COMBINATORIAL OPTIMIZATION PARAMETERS:
nh.setParam("starting_topologies_type", "BestStarOrFullyMeshed");
nh.setParam("number_of_starting_topologies", 1);
nh.setParam("neighbourhood_function", "TopologyManager");
nh.setParam("remove_relations", true);
nh.setParam("swap_relations", true);
nh.setParam("maximum_neighbour_count", 100);
nh.setParam("cost_function", "WeightedSum");
nh.setParam("false_positives_weight", 5);
nh.setParam("avg_recognition_time_weight", 1);
nh.setParam("false_negatives_weight", 5);
nh.setParam("test_set_generator_type", "relative");
nh.setParam("test_set_count", 1000);
nh.setParam("object_missing_in_test_set_probability", 0);
nh.setParam("recognition_threshold", recognitionThreshold);
nh.setParam("loaded_test_set_count", 1000);
nh.setParam("write_valid_test_sets_filename", "");
nh.setParam("write_invalid_test_sets_filename", "");
nh.setParam("conditional_probability_algorithm", "minimum");
nh.setParam("revisit_topologies", true);
nh.setParam("flexible_recognition_threshold", false);
nh.setParam("quit_after_test_set_evaluation", false);
nh.setParam("get_worst_star_topology", false);
nh.setParam("hill_climbing_random_walk_probability", 0);
nh.setParam("hill_climbing_random_restart_probability", 0.2);
nh.setParam("record_hunt_initial_acceptable_cost_delta", 0.02);
nh.setParam("record_hunt_cost_delta_decrease_factor", 0.01);
nh.setParam("simulated_annealing_start_temperature", 1);
nh.setParam("simulated_annealing_end_temperature", 0.005);
nh.setParam("simulated_annealing_repetitions_before_update", 8);
nh.setParam("simulated_annealing_temperature_factor", 0.9);
nh.setParam("xml_output", "file");
nh.setParam("optimization_history_output", "txt");
nh.setParam("create_runtime_log", false);
nh.setParam("log_file_name", "");
nh.setParam("visualize_inference", false);
//INFERENCE PARAMETERS:
nh.setParam("plot", false);
nh.setParam("object_topic", "/stereo/objects");
nh.setParam("scene_graph_topic", "/scene_graphs");
nh.setParam("evidence_timeout", 100);
}
void writeFile(const std::string & directoryPath, const std::string & filenName, std::ostringstream & content)
{
std::string filePath = directoryPath + "/" + filenName;
std::ofstream file;
std::ios_base::iostate exceptionMask = file.exceptions() | std::ios::failbit | std::ios::badbit;
file.exceptions(exceptionMask);
try
{
file.open(filePath);
file << content.str();
file.flush();
file.close();
}
catch (std::ios_base::failure& e)
{
std::cerr << "std::ios_base::failure" << std::endl;
std::cerr << e.what() << "\n";
}
}
double calculateStandardDeviation(const std::vector<double>& values, const double& average)
{
double sumSquares = 0;
for (double value : values)
{
sumSquares += (value - average) * (value - average);
}
double variance = sumSquares / values.size();
return std::sqrt(variance);
}
void createHistogram(const std::vector<double>& values, const unsigned int intervals, const std::string & fileName)
{
double minValue = std::numeric_limits<double>::max();
double maxValue = std::numeric_limits<double>::min();
for (double value : values)
{
minValue = std::min(minValue, value);
maxValue = std::max(maxValue, value);
}
double diff = maxValue - minValue;
double factor = intervals / diff;
std::vector<unsigned int> histogram(intervals, 0);
for (double value : values)
{
histogram[std::min((unsigned int) std::floor((value - minValue) * factor), intervals)]++;
}
std::ostringstream oss;
oss << "Intervall in seconds, Number Testsets" << std::endl;
for (unsigned int i = 0; i < intervals; ++i)
{
double lower = minValue + (i * 1 / factor);
double upper = lower + 1 / factor;
oss << lower << "-" << upper << ", " << histogram[i] << std::endl;
}
writeFile(outputPath, fileName, oss);
}
void runOptimization(std::ostringstream & os)
{
std::stringstream error;
error << "";
time_duration td;
try
{
ptime t1(boost::posix_time::microsec_clock::local_time());
boost::shared_ptr<SceneLearningEngine> sceneLearningEngine(new SceneLearningEngine());
sceneLearningEngine->readLearnerInput();
sceneLearningEngine->generateSceneModel();
sceneLearningEngine->saveSceneModel();
ptime t2(boost::posix_time::microsec_clock::local_time());
td = t2 - t1;
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
error << ", Error: " << e.what();
td = minutes(0);
}
long secs = td.total_seconds() % 60;
long mins = std::floor(td.total_seconds() / 60.);
os << ", " << mins << "." << secs << error.str() << std::endl;
}
void initRandomScenes()
{
for (unsigned int i = 0; i < objectCounts.size(); ++i)
{
for (unsigned int j = 0; j < timestepCounts.size(); ++j)
{
std::string demoName = "demoRecording_" + std::to_string(objectCounts[i]) + "_" + std::to_string(timestepCounts[j]) + ".sqlite";
std::string demoRecordingPath = outputPath + "/" + demoName;
demoRecordings.push_back(demoRecordingPath);
demoRecordingsNames.push_back(demoName);
}
}
}
void initTestSets()
{
std::string testSetFolderPath = outputPath + "/" + testSetFolder;
if(!boost::filesystem::exists(testSetFolderPath))
boost::filesystem::create_directories(testSetFolderPath);
for (unsigned int i = 0; i < demoRecordings.size(); ++i) {
path validTestSetsPath(testSetFolderPath + "/" + validTestSetPref + demoRecordingsNames[i]);
path invalidTestSetsPath(testSetFolderPath + "/" + invalidTestSetPref + demoRecordingsNames[i]);
testSets.push_back(validTestSetsPath.string());
testSets.push_back(invalidTestSetsPath.string());
}
}
void trainScenes(unsigned int run)
{
std::ostringstream os;
os << "Scene, Training duration" << std::endl;
for (unsigned int i = 0; i < demoRecordings.size(); ++i) {
ros::NodeHandle nh("~");
nh.setParam("relation_tree_trainer_type", treeAlgorithm);
nh.setParam("optimization_algorithm", optimizationAlgorithm);
std::cout << "Learner input: " << demoRecordings[i] << std::endl;
nh.setParam("input_db_file", demoRecordings[i]);
std::string additionalInfo = "";
if (treeAlgorithm == "combinatorial_optimization") additionalInfo = "_" + optimizationAlgorithm;
std::string demoName = demoRecordingsNames[i].substr(0, demoRecordingsNames[i].find("."));
std::string sceneModelName = demoName + "_" + treeAlgorithm + additionalInfo;
std::cout << "Learning model " << outputPath << "/" << run << "/" << sceneModelName << ".xml" << std::endl;
nh.setParam("scene_model_name", sceneModelName);
nh.setParam("scene_model_directory", outputPath + "/" + std::to_string(run));
nh.setParam("valid_test_set_db_filename", testSets[i * 2]);
nh.setParam("invalid_test_set_db_filename", testSets[i * 2 + 1]);
std::string subfolder = outputPath + "/" + std::to_string(run) + "/" + demoName + "/";
nh.setParam("xml_file_path", subfolder);
nh.setParam("optimization_history_file_path", subfolder);
std::cout << "Writing partial models and optimization histories into folder " << subfolder << "/" << demoName << std::endl;
os << demoRecordings[i] << ", ";
runOptimization(os);
}
writeFile(outputPath + "/" + std::to_string(run), treeAlgorithm + "_" + optimizationAlgorithm + "_d" + std::to_string(run) + "_" + "trainingTime.csv", os);
}
std::vector<ObjectSetPtr> loadTestSetsFromDB(std::string fileName, std::string patternName)
{
try
{
TableHelperPtr localTableHelper(new TableHelper(fileName));
std::vector<ObjectSetPtr> testSet;
if (!localTableHelper)
throw std::runtime_error("No local table helper!");
if (!localTableHelper->getRecordedPattern(patternName))
throw std::runtime_error("No recorded pattern for pattern name " + patternName);
testSet = localTableHelper->getRecordedPattern(patternName)->objectSets;
std::cout << "Read test sets for pattern " << patternName << std::endl;
return testSet;
}
catch (soci::soci_error& se)
{
std::cerr << "Soci error " << se.what() << std::endl;
throw se;
}
}
struct PerformanceEvaluationResult
{
unsigned int falsePositives;
unsigned int falseNegatives;
double averageRecognitionRuntime;
std::vector<std::pair<std::string, double>> recognitionRuntimes;
std::string getDescription()
{
std::stringstream out;
out << falsePositives << " false positives, " << falseNegatives << ", falseNegatives, " << averageRecognitionRuntime << "s average recognition runtime";
return out.str();
}
};
PerformanceEvaluationResult evaluate(const std::vector<ObjectSetPtr>& ts, bool valid, const std::string& patternName, const std::string& trainedScenePath)
{
PerformanceEvaluationResult er;
er.falseNegatives = 0;
er.falsePositives = 0;
er.recognitionRuntimes = std::vector<std::pair<std::string, double>>();
double fullRecognitionRuntime = 0;
std::string in = "";
if (!valid) in = "in";
std::cout << "Evaluating " << ts.size() << " " << in << "valid test sets for pattern " << patternName << std::endl;
boost::shared_ptr<SceneModelDescription> model(new SceneModelDescription());
boost::shared_ptr<Visualization::ProbabilisticSceneModelVisualization> mVisualizer(new Visualization::ProbabilisticSceneModelVisualization());
model->loadModelFromFile(trainedScenePath, inferenceAlgorithm);
model->initializeVisualizer(mVisualizer);
mVisualizer->setDrawingParameters(scale, sigma, frameId);
for (unsigned int testSetNumber = 0; testSetNumber < ts.size(); testSetNumber++)
{
ObjectSetPtr testSet = ts[testSetNumber];
if (!testSet)
throw std::runtime_error("Test set pointer invalid");
std::vector<SceneIdentifier> sceneList;
double actualRecognitionThreshold = 0.5;
time_duration td;
ros::Time start = ros::Time::now();
for (unsigned int i = 0; i < testSet->objects.size(); i++)
{
boost::shared_ptr<Object> object(new Object(*(testSet->objects[i])));
model->integrateEvidence(object);
}
model->updateModel();
model->getSceneListWithProbabilities(sceneList);
ros::Time end = ros::Time::now();
double recognitionRuntime = end.toSec() - start.toSec();
std::string validity = "v";
if (!valid) validity = "i";
std::string testSetName = patternName + "_" + validity + "_" + std::to_string(testSetNumber);
std::pair<std::string, double> result(testSetName, -1);
er.recognitionRuntimes.push_back(result);
fullRecognitionRuntime += recognitionRuntime;
double probability = -1;
for (SceneIdentifier sceneIdentifier: sceneList)
{
if (sceneIdentifier.mType == "ocm")
{
probability = sceneIdentifier.mLikelihood;
break;
}
}
if (probability == -1)
throw std::runtime_error("Could not find probability for scene ocm in list of scene probabilities.");
if (valid && probability <= actualRecognitionThreshold)
er.falseNegatives++;
if (!valid && probability > actualRecognitionThreshold)
er.falsePositives++;
}
er.averageRecognitionRuntime = fullRecognitionRuntime / ((double) er.recognitionRuntimes.size());
return er;
}
// recognition performance
void testPerformance()
{
std::ostringstream os;
os << "Scene, Average Recognition Runtime, Standard Deviation of Recognition Runtime" << std::endl;
unsigned index = 0;
for (unsigned int i = 0; i < objectCounts.size(); ++i)
{
for (unsigned int j = 0; j < timestepCounts.size(); ++j)
{
std::cout << "index = " << index << std::endl;
path demoRecording(demoRecordings[index]);
std::cout << "demo recording: " << demoRecording.string() << std::endl;
std::string sceneModelNameSuffix = "_" + treeAlgorithm;
if (treeAlgorithm == "combinatorial_optimization") sceneModelNameSuffix += "_" + optimizationAlgorithm;
std::string trainedScenePath = outputPath + "/ProbabilisticSceneModels/" + demoRecording.stem().string() + sceneModelNameSuffix + ".xml" ;
std::cout << "Using model " << trainedScenePath << std::endl;
std::string sceneName = "demo_recording_" + std::to_string(objectCounts[i]) + "_" + std::to_string(timestepCounts[j]);
std::cout << sceneName << std::endl;
std::string validTestSets = testSets[index * 2];
std::string invalidTestSets = testSets[index * 2 + 1];
std::cout << "Loading test sets from " << validTestSets << ", " << invalidTestSets << std::endl;
std::vector<ObjectSetPtr> validSets = loadTestSetsFromDB(validTestSets, sceneName);
std::vector<ObjectSetPtr> invalidSets = loadTestSetsFromDB(invalidTestSets, sceneName);
std::cout << "Test set loading complete." << std::endl;
std::cout << "Model initialized." << std::endl;
PerformanceEvaluationResult validER = evaluate(validSets, true, sceneName, trainedScenePath);
PerformanceEvaluationResult invalidER = evaluate(invalidSets, false, sceneName, trainedScenePath);
PerformanceEvaluationResult er;
er.falseNegatives = validER.falseNegatives + invalidER.falseNegatives;
er.falsePositives = validER.falsePositives + invalidER.falsePositives;
double fullRecognitionRuntime = 0;
for (std::pair<std::string, double> validRt: validER.recognitionRuntimes)
{
er.recognitionRuntimes.push_back(validRt);
fullRecognitionRuntime += validRt.second;
}
for (std::pair<std::string, double> invalidRt: invalidER.recognitionRuntimes)
{
er.recognitionRuntimes.push_back(invalidRt);
fullRecognitionRuntime += invalidRt.second;
}
er.averageRecognitionRuntime = fullRecognitionRuntime / ((double) (validER.recognitionRuntimes.size() + invalidER.recognitionRuntimes.size()));
// To manuever around a weird issue where, if the actual recognition runtime gets assigned to the pair, there is an munmap_chunk() invalid pointer error:
er.averageRecognitionRuntime = (validER.averageRecognitionRuntime * validER.recognitionRuntimes.size()
+ invalidER.averageRecognitionRuntime * invalidER.recognitionRuntimes.size())
/ (validER.recognitionRuntimes.size() + invalidER.recognitionRuntimes.size());
std::cout << "Evaluation complete." << std::endl;
std::vector<std::pair<std::string, double>> recognitionRuntimes = er.recognitionRuntimes;
std::vector<double> runtimes;
std::ostringstream runtimesPerSetStream;
runtimesPerSetStream << "Testset name, Average recognition runtime" << std::endl;
for (std::pair<std::string, double> valuePair : recognitionRuntimes)
{
runtimes.push_back(valuePair.second);
runtimesPerSetStream << valuePair.first << ", " << valuePair.second << std::endl;
}
writeFile(outputPath, sceneName + "_runtimes_per_testset.csv", runtimesPerSetStream);
std::cout << er.getDescription() << std::endl;
std::ostringstream falserec;
falserec << "scene; false positives; false negatives; sum; average recognition runtime" << std::endl;
falserec << sceneName << "; " << er.falsePositives << "; " << er.falseNegatives << "; " << er.falsePositives + er.falseNegatives << "; " << er.averageRecognitionRuntime << std::endl;
writeFile(outputPath, sceneName + "_false_recognitions.csv", falserec);
os << objectCounts[i] << "-" << timestepCounts[j] << ", " << er.averageRecognitionRuntime <<
", " << calculateStandardDeviation(runtimes, er.averageRecognitionRuntime) << std::endl;
createHistogram(runtimes, 10, sceneName + "_histogram.csv");
std::cout << "Histogram created." << std::endl;
index++;
std::cout << "timestepCounts.size() = " << timestepCounts.size() << ", j = " << j << std::endl;
}
}
writeFile(outputPath, "runtimes.csv", os);
}
/** This program serves to test training and recognition performance of asr_psm.
* Note that it does not generate test sets (for learning) and validation sets (for recognition)
* on its own. Generate them using the standard combinatorial optimization launch file with quit_after_test_set_generation set to true
* and the same parameters as below. Write the databases to asr_psm/data/test/performanceTestRessources/[ValidationSets/]demoRecording_X_Y00.sqlite
* with X from objectCounts, Y from timestepCounts below.
* Also note that training will, unless stopped earlier, perform 1000 runs while cycling through the different algorithms, so the comparably long
* tests can be run mostly automated. Errors are tolerated and marked in the results, again to allow it to run without needing constant supervision.
* The recognition tests have to be run one each, but they are also usually much quicker. */
int main(int argc, char *argv[])
{
std::string packagePath = ros::package::getPath("asr_psm");
outputPath = packagePath + "/data/test/performanceTestRessources";
if(!boost::filesystem::exists(outputPath))
boost::filesystem::create_directories(outputPath);
ros::init(argc, argv, "performance_test" + treeAlgorithm + "_" + optimizationAlgorithm);
ros::NodeHandle nh; // necessary to show ros streams
setDefaultParameters();
initRandomScenes();
initTestSets();
std::vector<std::string> methods = {
"tree",
"fullymeshed",
"combinatorial_optimization",
"combinatorial_optimization",
"combinatorial_optimization"
};
std::vector<std::string> algos = {
"HillClimbing",
"HillClimbing",
"HillClimbing",
"RecordHunt",
"SimulatedAnnealing"
};
unsigned int i = 0;
while (train && i < 1000)
{
treeAlgorithm = methods[i % methods.size()];
optimizationAlgorithm = algos[i % algos.size()];
std::string subfolder = outputPath + "/" + std::to_string(i);
if (!boost::filesystem::exists(subfolder))
boost::filesystem::create_directories(subfolder);
for (path demoRecording: demoRecordingsNames)
{
std::string demofolder = subfolder + "/" + demoRecording.stem().string();
if (!boost::filesystem::exists(demofolder))
boost::filesystem::create_directories(demofolder);
}
try
{
trainScenes(i);
}
catch (std::exception& e)
{
std::ofstream errorfile;
errorfile.open(subfolder + "/error.txt");
if (errorfile.is_open())
{
errorfile << e.what();
errorfile.close();
}
std::cerr << e.what();
}
i++;
}
//Set up LogHelper
std::string logFileName = "Log_x.txt";
path logFilePath = outputPath + "/Logfile/" + logFileName;
LogHelper::init(logFilePath, LOG_INFO);
if (test) testPerformance();
}
| 37.925424 | 194 | 0.656775 | [
"object",
"vector",
"model"
] |
2ad5a8eff54a82113976fff4bacac18f9fca09ce | 3,658 | hpp | C++ | cvxpy/cvxcore/src/LinOp.hpp | TShimko126/cvxpy | 8b89b3f8ef7daba1db39f5029e4902f06c75b29f | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2021-09-24T12:59:45.000Z | 2021-09-24T13:00:08.000Z | cvxpy/cvxcore/src/LinOp.hpp | TShimko126/cvxpy | 8b89b3f8ef7daba1db39f5029e4902f06c75b29f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cvxpy/cvxcore/src/LinOp.hpp | TShimko126/cvxpy | 8b89b3f8ef7daba1db39f5029e4902f06c75b29f | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-09-24T13:00:18.000Z | 2021-09-24T13:00:18.000Z | // Copyright 2017 Steven Diamond
//
// 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.
#ifndef LINOP_H
#define LINOP_H
#include <vector>
#include <cassert>
#include <iostream>
#include "Utils.hpp"
/* ID for all coefficient matrices associated with linOps of CONSTANT_TYPE */
static const int CONSTANT_ID = -1;
/* TYPE of each LinOP */
enum operatortype {
VARIABLE,
PROMOTE,
MUL,
RMUL,
MUL_ELEM,
DIV,
SUM,
NEG,
INDEX,
TRANSPOSE,
SUM_ENTRIES,
TRACE,
RESHAPE,
DIAG_VEC,
DIAG_MAT,
UPPER_TRI,
CONV,
HSTACK,
VSTACK,
SCALAR_CONST,
DENSE_CONST,
SPARSE_CONST,
NO_OP,
KRON
};
/* linOp TYPE */
typedef operatortype OperatorType;
/* LinOp Class mirrors the CVXPY linOp class. Data fields are determined
by the TYPE of LinOp. No error checking is performed on the data fields,
and the semantics of SIZE, ARGS, and DATA depends on the linop TYPE. */
class LinOp {
public:
OperatorType type;
std::vector<int> size;
/* Children LinOps in the tree */
std::vector<LinOp*> args;
/* Dimensions of data */
int data_ndim;
/* Sparse Data Fields */
bool sparse; // True only if linOp has sparse_data
Matrix sparse_data;
/* Dense Data Field */
Eigen::MatrixXd dense_data;
/* Slice Data: stores slice data as (row_slice, col_slice)
* where slice = (start, end, step_size) */
std::vector<std::vector<int> > slice;
/* Constructor */
LinOp(){
sparse = false; // sparse by default
}
/* Checks if LinOp is constant type */
bool has_constant_type() {
return type == SCALAR_CONST || type == DENSE_CONST
|| type == SPARSE_CONST;
}
/* Initializes DENSE_DATA. MATRIX is a pointer to the data of a 2D
* numpy array, ROWS and COLS are the size of the ARRAY.
*
* MATRIX must be a contiguous array of doubles aligned in fortran
* order.
*
* NOTE: The function prototype must match the type-map in CVXCanon.i
* exactly to compile and run properly.
*/
void set_dense_data(double* matrix, int rows, int cols) {
dense_data = Eigen::Map<Eigen::MatrixXd> (matrix, rows, cols);
}
/* Initializes SPARSE_DATA from a sparse matrix in COO format.
* DATA, ROW_IDXS, COL_IDXS are assumed to be contiguous 1D numpy arrays
* where (DATA[i], ROW_IDXS[i], COLS_IDXS[i]) is a (V, I, J) triplet in
* the matrix. ROWS and COLS should refer to the size of the matrix.
*
* NOTE: The function prototype must match the type-map in CVXCanon.i
* exactly to compile and run properly.
*/
void set_sparse_data(double *data, int data_len, double *row_idxs,
int rows_len, double *col_idxs, int cols_len,
int rows, int cols) {
assert(rows_len == data_len && cols_len == data_len);
sparse = true;
Matrix sparse_coeffs(rows, cols);
std::vector<Triplet> tripletList;
tripletList.reserve(data_len);
for (int idx = 0; idx < data_len; idx++) {
tripletList.push_back(Triplet(int(row_idxs[idx]), int(col_idxs[idx]),
data[idx]));
}
sparse_coeffs.setFromTriplets(tripletList.begin(), tripletList.end());
sparse_coeffs.makeCompressed();
sparse_data = sparse_coeffs;
data_ndim = 2;
}
};
#endif
| 27.712121 | 77 | 0.691635 | [
"vector"
] |
2ae381c41c695af71cb39ba2816b1e9112f35630 | 50,413 | cpp | C++ | arangod/VocBase/replication-dump.cpp | asaaki/ArangoDB | a1d4f6f33c09ffd6f67744dbe748e83dc0fe6b82 | [
"Apache-2.0"
] | 15 | 2019-08-08T02:06:36.000Z | 2019-10-15T17:52:58.000Z | arangod/VocBase/replication-dump.cpp | asaaki/ArangoDB | a1d4f6f33c09ffd6f67744dbe748e83dc0fe6b82 | [
"Apache-2.0"
] | null | null | null | arangod/VocBase/replication-dump.cpp | asaaki/ArangoDB | a1d4f6f33c09ffd6f67744dbe748e83dc0fe6b82 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// @brief replication dump functions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "replication-dump.h"
#include "BasicsC/conversions.h"
#include "BasicsC/files.h"
#include "BasicsC/json.h"
#include "BasicsC/logging.h"
#include "BasicsC/tri-strings.h"
#include "Utils/CollectionNameResolver.h"
#include "VocBase/collection.h"
#include "VocBase/datafile.h"
#include "VocBase/document-collection.h"
#include "VocBase/server.h"
#include "VocBase/transaction.h"
#include "VocBase/vocbase.h"
#include "VocBase/voc-shaper.h"
#include "Wal/Logfile.h"
#include "Wal/LogfileManager.h"
#include "Wal/Marker.h"
#include "Cluster/ServerState.h"
using namespace triagens;
// -----------------------------------------------------------------------------
// --SECTION-- REPLICATION
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- private defines
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief shortcut function
////////////////////////////////////////////////////////////////////////////////
#define FAIL_IFNOT(func, buffer, val) \
if (func(buffer, val) != TRI_ERROR_NO_ERROR) { \
return TRI_ERROR_OUT_OF_MEMORY; \
}
////////////////////////////////////////////////////////////////////////////////
/// @brief create a string-buffer function name
////////////////////////////////////////////////////////////////////////////////
#define APPEND_FUNC(name) TRI_ ## name ## StringBuffer
////////////////////////////////////////////////////////////////////////////////
/// @brief append a character to a string-buffer or fail
////////////////////////////////////////////////////////////////////////////////
#define APPEND_CHAR(buffer, c) FAIL_IFNOT(APPEND_FUNC(AppendChar), buffer, c)
////////////////////////////////////////////////////////////////////////////////
/// @brief append a string to a string-buffer or fail
////////////////////////////////////////////////////////////////////////////////
#define APPEND_STRING(buffer, str) FAIL_IFNOT(APPEND_FUNC(AppendString), buffer, str)
////////////////////////////////////////////////////////////////////////////////
/// @brief append uint64 to a string-buffer or fail
////////////////////////////////////////////////////////////////////////////////
#define APPEND_UINT64(buffer, val) FAIL_IFNOT(APPEND_FUNC(AppendUInt64), buffer, val)
// -----------------------------------------------------------------------------
// --SECTION-- private types
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief a datafile descriptor
////////////////////////////////////////////////////////////////////////////////
typedef struct df_entry_s {
TRI_datafile_t* _data;
TRI_voc_tick_t _dataMin;
TRI_voc_tick_t _dataMax;
TRI_voc_tick_t _tickMax;
bool _isJournal;
}
df_entry_t;
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief translate a (local) collection id into a collection name
////////////////////////////////////////////////////////////////////////////////
char const* NameFromCid (TRI_replication_dump_t* dump,
TRI_voc_cid_t cid) {
auto it = dump->_collectionNames.find(cid);
if (it != dump->_collectionNames.end()) {
// collection name is in cache already
return (*it).second.c_str();
}
// collection name not in cache yet
char* name = TRI_GetCollectionNameByIdVocBase(dump->_vocbase, cid);
if (name != nullptr) {
// insert into cache
dump->_collectionNames.insert(it, std::make_pair(cid, std::string(name)));
TRI_FreeString(TRI_UNKNOWN_MEM_ZONE, name);
// and look it up again
return NameFromCid(dump, cid);
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief append a collection name or id to a string buffer
////////////////////////////////////////////////////////////////////////////////
static int AppendCollection (TRI_replication_dump_t* dump,
TRI_voc_cid_t cid,
bool translateCollectionIds,
triagens::arango::CollectionNameResolver* resolver) {
if (translateCollectionIds) {
if (cid > 0) {
std::string name;
if (triagens::arango::ServerState::instance()->isDBserver()) {
name = resolver->getCollectionNameCluster(cid);
}
else {
name = resolver->getCollectionName(cid);
}
APPEND_STRING(dump->_buffer, name.c_str());
return TRI_ERROR_NO_ERROR;
}
APPEND_STRING(dump->_buffer, "_unknown");
}
else {
APPEND_UINT64(dump->_buffer, (uint64_t) cid);
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief iterate over a vector of datafiles and pick those with a specific
/// data range
////////////////////////////////////////////////////////////////////////////////
static int IterateDatafiles (TRI_vector_pointer_t const* datafiles,
TRI_vector_t* result,
TRI_voc_tick_t dataMin,
TRI_voc_tick_t dataMax,
bool isJournal) {
int res = TRI_ERROR_NO_ERROR;
size_t const n = datafiles->_length;
for (size_t i = 0; i < n; ++i) {
TRI_datafile_t* df = static_cast<TRI_datafile_t*>(TRI_AtVectorPointer(datafiles, i));
df_entry_t entry = {
df,
df->_dataMin,
df->_dataMax,
df->_tickMax,
isJournal
};
LOG_TRACE("checking datafile %llu with data range %llu - %llu, tick max: %llu",
(unsigned long long) df->_fid,
(unsigned long long) df->_dataMin,
(unsigned long long) df->_dataMax,
(unsigned long long) df->_tickMax);
if (df->_dataMin == 0 || df->_dataMax == 0) {
// datafile doesn't have any data
continue;
}
TRI_ASSERT(df->_tickMin <= df->_tickMax);
TRI_ASSERT(df->_dataMin <= df->_dataMax);
if (dataMax < df->_dataMin) {
// datafile is newer than requested range
continue;
}
if (dataMin > df->_dataMax) {
// datafile is older than requested range
continue;
}
res = TRI_PushBackVector(result, &entry);
if (res != TRI_ERROR_NO_ERROR) {
break;
}
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the datafiles of a collection for a specific tick range
////////////////////////////////////////////////////////////////////////////////
static TRI_vector_t GetRangeDatafiles (TRI_document_collection_t* document,
TRI_voc_tick_t dataMin,
TRI_voc_tick_t dataMax) {
TRI_vector_t datafiles;
LOG_TRACE("getting datafiles in data range %llu - %llu",
(unsigned long long) dataMin,
(unsigned long long) dataMax);
// determine the datafiles of the collection
TRI_InitVector(&datafiles, TRI_CORE_MEM_ZONE, sizeof(df_entry_t));
TRI_READ_LOCK_DATAFILES_DOC_COLLECTION(document);
IterateDatafiles(&document->_datafiles, &datafiles, dataMin, dataMax, false);
IterateDatafiles(&document->_journals, &datafiles, dataMin, dataMax, true);
TRI_READ_UNLOCK_DATAFILES_DOC_COLLECTION(document);
return datafiles;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief append database id plus collection id
////////////////////////////////////////////////////////////////////////////////
static int AppendContext (TRI_replication_dump_t* dump,
TRI_voc_tick_t databaseId,
TRI_voc_cid_t collectionId) {
APPEND_STRING(dump->_buffer, "\"database\":\"");
APPEND_UINT64(dump->_buffer, databaseId);
APPEND_STRING(dump->_buffer, "\",\"cid\":\"");
APPEND_UINT64(dump->_buffer, collectionId);
APPEND_STRING(dump->_buffer, "\",");
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a raw marker from a datafile for a collection dump
////////////////////////////////////////////////////////////////////////////////
static int StringifyMarkerDump (TRI_replication_dump_t* dump,
TRI_document_collection_t* document,
TRI_df_marker_t const* marker,
bool withTicks,
bool translateCollectionIds,
triagens::arango::CollectionNameResolver* resolver) {
// This covers two cases:
// 1. document is not nullptr and marker points into a data file
// 2. document is a nullptr and marker points into a WAL file
// no other combinations are allowed.
TRI_string_buffer_t* buffer;
TRI_replication_operation_e type;
TRI_voc_key_t key;
TRI_voc_rid_t rid;
bool haveData = true;
bool isWal = false;
buffer = dump->_buffer;
if (buffer == nullptr) {
return TRI_ERROR_INTERNAL;
}
switch (marker->_type) {
case TRI_DOC_MARKER_KEY_DELETION: {
TRI_ASSERT(nullptr != document);
auto m = reinterpret_cast<TRI_doc_deletion_key_marker_t const*>(marker);
key = ((char*) m) + m->_offsetKey;
type = REPLICATION_MARKER_REMOVE;
rid = m->_rid;
haveData = false;
break;
}
case TRI_DOC_MARKER_KEY_DOCUMENT: {
TRI_ASSERT(nullptr != document);
auto m = reinterpret_cast<TRI_doc_document_key_marker_t const*>(marker);
key = ((char*) m) + m->_offsetKey;
type = REPLICATION_MARKER_DOCUMENT;
rid = m->_rid;
break;
}
case TRI_DOC_MARKER_KEY_EDGE: {
TRI_ASSERT(nullptr != document);
auto m = reinterpret_cast<TRI_doc_document_key_marker_t const*>(marker);
key = ((char*) m) + m->_offsetKey;
type = REPLICATION_MARKER_EDGE;
rid = m->_rid;
break;
}
case TRI_WAL_MARKER_REMOVE: {
TRI_ASSERT(nullptr == document);
auto m = static_cast<wal::remove_marker_t const*>(marker);
key = ((char*) m) + sizeof(wal::remove_marker_t);
type = REPLICATION_MARKER_REMOVE;
rid = m->_revisionId;
haveData = false;
isWal = true;
break;
}
case TRI_WAL_MARKER_DOCUMENT: {
TRI_ASSERT(nullptr == document);
auto m = static_cast<wal::document_marker_t const*>(marker);
key = ((char*) m) + m->_offsetKey;
type = REPLICATION_MARKER_DOCUMENT;
rid = m->_revisionId;
isWal = true;
break;
}
case TRI_WAL_MARKER_EDGE: {
TRI_ASSERT(nullptr == document);
auto m = static_cast<wal::edge_marker_t const*>(marker);
key = ((char*) m) + m->_offsetKey;
type = REPLICATION_MARKER_EDGE;
rid = m->_revisionId;
isWal = true;
break;
}
default: {
return TRI_ERROR_INTERNAL;
}
}
if (withTicks) {
APPEND_STRING(buffer, "{\"tick\":\"");
APPEND_UINT64(buffer, (uint64_t) marker->_tick);
APPEND_STRING(buffer, "\",\"type\":");
}
else {
APPEND_STRING(buffer, "{\"type\":");
}
APPEND_UINT64(buffer, (uint64_t) type);
APPEND_STRING(buffer, ",\"key\":\"");
// key is user-defined, but does not need escaping
APPEND_STRING(buffer, key);
APPEND_STRING(buffer, "\",\"rev\":\"");
APPEND_UINT64(buffer, (uint64_t) rid);
// document
if (haveData) {
APPEND_STRING(buffer, "\",\"data\":{");
// common document meta-data
APPEND_STRING(buffer, "\"" TRI_VOC_ATTRIBUTE_KEY "\":\"");
APPEND_STRING(buffer, key);
APPEND_STRING(buffer, "\",\"" TRI_VOC_ATTRIBUTE_REV "\":\"");
APPEND_UINT64(buffer, (uint64_t) rid);
APPEND_CHAR(buffer, '"');
// Is it an edge marker?
if (marker->_type == TRI_DOC_MARKER_KEY_EDGE ||
marker->_type == TRI_WAL_MARKER_EDGE) {
TRI_voc_key_t fromKey;
TRI_voc_key_t toKey;
TRI_voc_cid_t fromCid;
TRI_voc_cid_t toCid;
if (marker->_type == TRI_DOC_MARKER_KEY_EDGE) {
auto e = reinterpret_cast<TRI_doc_edge_key_marker_t const*>(marker);
fromKey = ((char*) e) + e->_offsetFromKey;
toKey = ((char*) e) + e->_offsetToKey;
fromCid = e->_fromCid;
toCid = e->_toCid;
}
else { // TRI_WAL_MARKER_EDGE
auto e = reinterpret_cast<wal::edge_marker_t const*>(marker);
fromKey = ((char*) e) + e->_offsetFromKey;
toKey = ((char*) e) + e->_offsetToKey;
fromCid = e->_fromCid;
toCid = e->_toCid;
}
int res;
APPEND_STRING(buffer, ",\"" TRI_VOC_ATTRIBUTE_FROM "\":\"");
res = AppendCollection(dump, fromCid, translateCollectionIds, resolver);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
APPEND_STRING(buffer, "\\/");
APPEND_STRING(buffer, fromKey);
APPEND_STRING(buffer, "\",\"" TRI_VOC_ATTRIBUTE_TO "\":\"");
res = AppendCollection(dump, toCid, translateCollectionIds, resolver);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
APPEND_STRING(buffer, "\\/");
APPEND_STRING(buffer, toKey);
APPEND_CHAR(buffer, '"');
}
// the actual document data
TRI_shaped_json_t shaped;
if (! isWal) {
auto m = reinterpret_cast<TRI_doc_document_key_marker_t const*>(marker);
TRI_EXTRACT_SHAPED_JSON_MARKER(shaped, m);
TRI_StringifyArrayShapedJson(document->getShaper(), buffer, &shaped, true); // ONLY IN DUMP, PROTECTED by fake trx above
}
else { // isWal == true
auto m = static_cast<wal::document_marker_t const*>(marker);
TRI_EXTRACT_SHAPED_JSON_MARKER(shaped, m);
char const* legend = reinterpret_cast<char const*>(m) + m->_offsetLegend;
if (m->_offsetJson - m->_offsetLegend == 8) {
auto p = reinterpret_cast<int64_t const*>(legend);
legend += *p;
}
basics::LegendReader legendReader(legend);
TRI_StringifyArrayShapedJson(&legendReader, buffer, &shaped, true);
}
APPEND_STRING(buffer, "}}\n");
}
else { // deletion marker, so no data
APPEND_STRING(buffer, "\"}\n");
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief append the document attributes of a marker
////////////////////////////////////////////////////////////////////////////////
static int AppendDocument (triagens::wal::document_marker_t const* marker,
TRI_replication_dump_t* dump) {
TRI_shaped_json_t shaped;
shaped._sid = marker->_shape;
shaped._data.length = marker->_size - marker->_offsetJson;
shaped._data.data = (char*) marker + marker->_offsetJson;
// check if the marker contains a legend
char const* legend = reinterpret_cast<char const*>(marker) + marker->_offsetLegend;
if (*((uint64_t*) legend) == 0ULL) {
// marker has no legend
// create a fake transaction so no assertion fails
triagens::arango::TransactionBase trx(true);
// try to open the collection and use the shaper
TRI_vocbase_t* vocbase = TRI_UseDatabaseByIdServer(dump->_vocbase->_server, marker->_databaseId);
if (vocbase == nullptr) {
// we'll not return an error in this case but an empty document
// this is intentional so the replication can still continue with documents of collections
// that survived
return TRI_ERROR_NO_ERROR;
}
TRI_vocbase_col_status_e status;
TRI_vocbase_col_t* collection = TRI_UseCollectionByIdVocBase(vocbase, marker->_collectionId, status);
int res = TRI_ERROR_NO_ERROR;
if (collection == nullptr) {
// we'll not return an error in this case but an empty document
// this is intentional so the replication can still continue with documents of collections
// that survived
res = TRI_ERROR_NO_ERROR;
}
else {
TRI_document_collection_t* document = collection->_collection;
if (! TRI_StringifyArrayShapedJson(document->getShaper(), dump->_buffer, &shaped, true)) {
res = TRI_ERROR_OUT_OF_MEMORY;
}
TRI_ReleaseCollectionVocBase(vocbase, collection);
}
TRI_ReleaseDatabaseServer(dump->_vocbase->_server, vocbase);
return res;
}
else {
// marker has a legend, so use it
if (marker->_offsetJson - marker->_offsetLegend == 8) {
auto p = reinterpret_cast<int64_t const*>(legend);
legend += *p;
}
triagens::basics::LegendReader lr(legend);
if (! TRI_StringifyArrayShapedJson(&lr, dump->_buffer, &shaped, true)) {
return TRI_ERROR_OUT_OF_MEMORY;
}
return TRI_ERROR_NO_ERROR;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a document marker
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarkerDocument (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
auto m = reinterpret_cast<triagens::wal::document_marker_t const*>(marker);
int res = AppendContext(dump, m->_databaseId, m->_collectionId);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
APPEND_STRING(dump->_buffer, "\"tid\":\"");
APPEND_UINT64(dump->_buffer, m->_transactionId);
APPEND_STRING(dump->_buffer, "\",\"key\":\"");
APPEND_STRING(dump->_buffer, (char const*) m + m->_offsetKey);
APPEND_STRING(dump->_buffer, "\",\"rev\":\"");
APPEND_UINT64(dump->_buffer, m->_revisionId);
APPEND_STRING(dump->_buffer, "\",\"data\":{");
// common document meta-data
APPEND_STRING(dump->_buffer, "\"" TRI_VOC_ATTRIBUTE_KEY "\":\"");
APPEND_STRING(dump->_buffer, (char const*) m + m->_offsetKey);
APPEND_STRING(dump->_buffer, "\",\"" TRI_VOC_ATTRIBUTE_REV "\":\"");
APPEND_UINT64(dump->_buffer, (uint64_t) m->_revisionId);
APPEND_STRING(dump->_buffer, "\"");
res = AppendDocument(m, dump);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
APPEND_STRING(dump->_buffer, "}");
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify an edge marker
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarkerEdge (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
auto m = reinterpret_cast<triagens::wal::edge_marker_t const*>(marker);
int res = AppendContext(dump, m->_databaseId, m->_collectionId);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
APPEND_STRING(dump->_buffer, "\"tid\":\"");
APPEND_UINT64(dump->_buffer, m->_transactionId);
APPEND_STRING(dump->_buffer, "\",\"key\":\"");
APPEND_STRING(dump->_buffer, (char const*) m + m->_offsetKey);
APPEND_STRING(dump->_buffer, "\",\"rev\":\"");
APPEND_UINT64(dump->_buffer, m->_revisionId);
APPEND_STRING(dump->_buffer, "\",\"data\":{");
// common document meta-data
APPEND_STRING(dump->_buffer, "\"" TRI_VOC_ATTRIBUTE_KEY "\":\"");
APPEND_STRING(dump->_buffer, (char const*) m + m->_offsetKey);
APPEND_STRING(dump->_buffer, "\",\"" TRI_VOC_ATTRIBUTE_REV "\":\"");
APPEND_UINT64(dump->_buffer, (uint64_t) m->_revisionId);
// from
APPEND_STRING(dump->_buffer, "\",\"" TRI_VOC_ATTRIBUTE_FROM "\":\"");
APPEND_UINT64(dump->_buffer, (uint64_t) m->_fromCid);
APPEND_STRING(dump->_buffer, "\\/");
APPEND_STRING(dump->_buffer, (char const*) m + m->_offsetFromKey);
// to
APPEND_STRING(dump->_buffer, "\",\"" TRI_VOC_ATTRIBUTE_TO "\":\"");
APPEND_UINT64(dump->_buffer, (uint64_t) m->_toCid);
APPEND_STRING(dump->_buffer, "\\/");
APPEND_STRING(dump->_buffer, (char const*) m + m->_offsetToKey);
APPEND_STRING(dump->_buffer, "\"");
res = AppendDocument(reinterpret_cast<triagens::wal::document_marker_t const*>(m), dump);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
APPEND_STRING(dump->_buffer, "}");
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a remove marker
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarkerRemove (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
auto m = reinterpret_cast<triagens::wal::remove_marker_t const*>(marker);
int res = AppendContext(dump, m->_databaseId, m->_collectionId);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
APPEND_STRING(dump->_buffer, "\"tid\":\"");
APPEND_UINT64(dump->_buffer, m->_transactionId);
APPEND_STRING(dump->_buffer, "\",\"key\":\"");
APPEND_STRING(dump->_buffer, (char const*) m + sizeof(triagens::wal::remove_marker_t));
APPEND_STRING(dump->_buffer, "\",\"rev\":\"");
APPEND_UINT64(dump->_buffer, m->_revisionId);
APPEND_STRING(dump->_buffer, "\"");
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a transaction marker
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarkerTransaction (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
// note: the data layout of begin / commit / abort markers is identical, so
// we cast to a begin transaction marker in all cases
auto m = reinterpret_cast<triagens::wal::transaction_begin_marker_t const*>(marker);
APPEND_STRING(dump->_buffer, "\"database\":\"");
APPEND_UINT64(dump->_buffer, m->_databaseId);
APPEND_STRING(dump->_buffer, "\",\"tid\":\"");
APPEND_UINT64(dump->_buffer, m->_transactionId);
APPEND_STRING(dump->_buffer, "\"");
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a create collection marker
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarkerCreateCollection (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
auto m = reinterpret_cast<triagens::wal::collection_create_marker_t const*>(marker);
APPEND_STRING(dump->_buffer, "\"database\":\"");
APPEND_UINT64(dump->_buffer, m->_databaseId);
APPEND_STRING(dump->_buffer, "\",\"cid\":\"");
APPEND_UINT64(dump->_buffer, m->_collectionId);
APPEND_STRING(dump->_buffer, "\",\"collection\":");
APPEND_STRING(dump->_buffer, (char const*) m + sizeof(triagens::wal::collection_create_marker_t));
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a drop collection marker
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarkerDropCollection (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
auto m = reinterpret_cast<triagens::wal::collection_drop_marker_t const*>(marker);
APPEND_STRING(dump->_buffer, "\"database\":\"");
APPEND_UINT64(dump->_buffer, m->_databaseId);
APPEND_STRING(dump->_buffer, "\",\"cid\":\"");
APPEND_UINT64(dump->_buffer, m->_collectionId);
APPEND_STRING(dump->_buffer, "\"");
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a rename collection marker
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarkerRenameCollection (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
auto m = reinterpret_cast<triagens::wal::collection_rename_marker_t const*>(marker);
APPEND_STRING(dump->_buffer, "\"database\":\"");
APPEND_UINT64(dump->_buffer, m->_databaseId);
APPEND_STRING(dump->_buffer, "\",\"cid\":\"");
APPEND_UINT64(dump->_buffer, m->_collectionId);
APPEND_STRING(dump->_buffer, "\",\"collection\":{\"name\":\"");
APPEND_STRING(dump->_buffer, (char const*) m + sizeof(triagens::wal::collection_rename_marker_t));
APPEND_STRING(dump->_buffer, "\"}");
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a change collection marker
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarkerChangeCollection (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
auto m = reinterpret_cast<triagens::wal::collection_change_marker_t const*>(marker);
APPEND_STRING(dump->_buffer, "\"database\":\"");
APPEND_UINT64(dump->_buffer, m->_databaseId);
APPEND_STRING(dump->_buffer, "\",\"cid\":\"");
APPEND_UINT64(dump->_buffer, m->_collectionId);
APPEND_STRING(dump->_buffer, "\",\"collection\":");
APPEND_STRING(dump->_buffer, (char const*) m + sizeof(triagens::wal::collection_change_marker_t));
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a create index marker
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarkerCreateIndex (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
auto m = reinterpret_cast<triagens::wal::index_create_marker_t const*>(marker);
APPEND_STRING(dump->_buffer, "\"database\":\"");
APPEND_UINT64(dump->_buffer, m->_databaseId);
APPEND_STRING(dump->_buffer, "\",\"cid\":\"");
APPEND_UINT64(dump->_buffer, m->_collectionId);
APPEND_STRING(dump->_buffer, "\",\"id\":\"");
APPEND_UINT64(dump->_buffer, m->_indexId);
APPEND_STRING(dump->_buffer, "\",\"index\":");
APPEND_STRING(dump->_buffer, (char const*) m + sizeof(triagens::wal::index_create_marker_t));
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a drop index marker
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarkerDropIndex (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
auto m = reinterpret_cast<triagens::wal::index_drop_marker_t const*>(marker);
APPEND_STRING(dump->_buffer, "\"database\":\"");
APPEND_UINT64(dump->_buffer, m->_databaseId);
APPEND_STRING(dump->_buffer, "\",\"cid\":\"");
APPEND_UINT64(dump->_buffer, m->_collectionId);
APPEND_STRING(dump->_buffer, "\",\"id\":\"");
APPEND_UINT64(dump->_buffer, m->_indexId);
APPEND_STRING(dump->_buffer, "\"");
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not a marker should be replicated
////////////////////////////////////////////////////////////////////////////////
static inline bool MustReplicateWalMarkerType (TRI_df_marker_t const* marker) {
return (marker->_type == TRI_WAL_MARKER_DOCUMENT ||
marker->_type == TRI_WAL_MARKER_EDGE ||
marker->_type == TRI_WAL_MARKER_REMOVE ||
marker->_type == TRI_WAL_MARKER_BEGIN_TRANSACTION ||
marker->_type == TRI_WAL_MARKER_COMMIT_TRANSACTION ||
marker->_type == TRI_WAL_MARKER_ABORT_TRANSACTION ||
marker->_type == TRI_WAL_MARKER_CREATE_COLLECTION ||
marker->_type == TRI_WAL_MARKER_DROP_COLLECTION ||
marker->_type == TRI_WAL_MARKER_RENAME_COLLECTION ||
marker->_type == TRI_WAL_MARKER_CHANGE_COLLECTION ||
marker->_type == TRI_WAL_MARKER_CREATE_INDEX ||
marker->_type == TRI_WAL_MARKER_DROP_INDEX);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief translate a marker type to a replication type
////////////////////////////////////////////////////////////////////////////////
static TRI_replication_operation_e TranslateType (TRI_df_marker_t const* marker) {
switch (marker->_type) {
case TRI_WAL_MARKER_DOCUMENT:
return REPLICATION_MARKER_DOCUMENT;
case TRI_WAL_MARKER_EDGE:
return REPLICATION_MARKER_EDGE;
case TRI_WAL_MARKER_REMOVE:
return REPLICATION_MARKER_REMOVE;
case TRI_WAL_MARKER_BEGIN_TRANSACTION:
return REPLICATION_TRANSACTION_START;
case TRI_WAL_MARKER_COMMIT_TRANSACTION:
return REPLICATION_TRANSACTION_COMMIT;
case TRI_WAL_MARKER_ABORT_TRANSACTION:
return REPLICATION_TRANSACTION_ABORT;
case TRI_WAL_MARKER_CREATE_COLLECTION:
return REPLICATION_COLLECTION_CREATE;
case TRI_WAL_MARKER_DROP_COLLECTION:
return REPLICATION_COLLECTION_DROP;
case TRI_WAL_MARKER_RENAME_COLLECTION:
return REPLICATION_COLLECTION_RENAME;
case TRI_WAL_MARKER_CHANGE_COLLECTION:
return REPLICATION_COLLECTION_CHANGE;
case TRI_WAL_MARKER_CREATE_INDEX:
return REPLICATION_INDEX_CREATE;
case TRI_WAL_MARKER_DROP_INDEX:
return REPLICATION_INDEX_DROP;
default:
return REPLICATION_INVALID;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stringify a raw marker from a WAL logfile for a log dump
////////////////////////////////////////////////////////////////////////////////
static int StringifyWalMarker (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
TRI_ASSERT_EXPENSIVE(MustReplicateWalMarkerType(marker));
APPEND_STRING(dump->_buffer, "{\"tick\":\"");
APPEND_UINT64(dump->_buffer, (uint64_t) marker->_tick);
APPEND_STRING(dump->_buffer, "\",\"type\":");
APPEND_UINT64(dump->_buffer, (uint64_t) TranslateType(marker));
APPEND_STRING(dump->_buffer, ",");
int res = TRI_ERROR_INTERNAL;
switch (marker->_type) {
case TRI_WAL_MARKER_DOCUMENT: {
res = StringifyWalMarkerDocument(dump, marker);
break;
}
case TRI_WAL_MARKER_EDGE: {
res = StringifyWalMarkerEdge(dump, marker);
break;
}
case TRI_WAL_MARKER_REMOVE: {
res = StringifyWalMarkerRemove(dump, marker);
break;
}
case TRI_WAL_MARKER_BEGIN_TRANSACTION:
case TRI_WAL_MARKER_COMMIT_TRANSACTION:
case TRI_WAL_MARKER_ABORT_TRANSACTION: {
res = StringifyWalMarkerTransaction(dump, marker);
break;
}
case TRI_WAL_MARKER_CREATE_COLLECTION: {
res = StringifyWalMarkerCreateCollection(dump, marker);
break;
}
case TRI_WAL_MARKER_DROP_COLLECTION: {
res = StringifyWalMarkerDropCollection(dump, marker);
break;
}
case TRI_WAL_MARKER_RENAME_COLLECTION: {
res = StringifyWalMarkerRenameCollection(dump, marker);
break;
}
case TRI_WAL_MARKER_CHANGE_COLLECTION: {
res = StringifyWalMarkerChangeCollection(dump, marker);
break;
}
case TRI_WAL_MARKER_CREATE_INDEX: {
res = StringifyWalMarkerCreateIndex(dump, marker);
break;
}
case TRI_WAL_MARKER_DROP_INDEX: {
res = StringifyWalMarkerDropIndex(dump, marker);
break;
}
case TRI_WAL_MARKER_BEGIN_REMOTE_TRANSACTION:
case TRI_WAL_MARKER_COMMIT_REMOTE_TRANSACTION:
case TRI_WAL_MARKER_ABORT_REMOTE_TRANSACTION:
case TRI_WAL_MARKER_ATTRIBUTE:
case TRI_WAL_MARKER_SHAPE: {
TRI_ASSERT(false);
return TRI_ERROR_INTERNAL;
}
}
APPEND_STRING(dump->_buffer, "}\n");
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief helper function to extract a database id from a marker
////////////////////////////////////////////////////////////////////////////////
template<typename T>
static TRI_voc_tick_t GetDatabaseId (TRI_df_marker_t const* marker) {
T const* m = reinterpret_cast<T const*>(marker);
return m->_databaseId;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the database id from a marker
////////////////////////////////////////////////////////////////////////////////
static TRI_voc_tick_t GetDatabaseFromWalMarker (TRI_df_marker_t const* marker) {
TRI_ASSERT_EXPENSIVE(MustReplicateWalMarkerType(marker));
switch (marker->_type) {
case TRI_WAL_MARKER_ATTRIBUTE:
return GetDatabaseId<triagens::wal::attribute_marker_t>(marker);
case TRI_WAL_MARKER_SHAPE:
return GetDatabaseId<triagens::wal::shape_marker_t>(marker);
case TRI_WAL_MARKER_DOCUMENT:
return GetDatabaseId<triagens::wal::document_marker_t>(marker);
case TRI_WAL_MARKER_EDGE:
return GetDatabaseId<triagens::wal::edge_marker_t>(marker);
case TRI_WAL_MARKER_REMOVE:
return GetDatabaseId<triagens::wal::remove_marker_t>(marker);
case TRI_WAL_MARKER_BEGIN_TRANSACTION:
return GetDatabaseId<triagens::wal::transaction_begin_marker_t>(marker);
case TRI_WAL_MARKER_COMMIT_TRANSACTION:
return GetDatabaseId<triagens::wal::transaction_commit_marker_t>(marker);
case TRI_WAL_MARKER_ABORT_TRANSACTION:
return GetDatabaseId<triagens::wal::transaction_abort_marker_t>(marker);
case TRI_WAL_MARKER_CREATE_COLLECTION:
return GetDatabaseId<triagens::wal::collection_create_marker_t>(marker);
case TRI_WAL_MARKER_DROP_COLLECTION:
return GetDatabaseId<triagens::wal::collection_drop_marker_t>(marker);
case TRI_WAL_MARKER_RENAME_COLLECTION:
return GetDatabaseId<triagens::wal::collection_rename_marker_t>(marker);
case TRI_WAL_MARKER_CHANGE_COLLECTION:
return GetDatabaseId<triagens::wal::collection_change_marker_t>(marker);
case TRI_WAL_MARKER_CREATE_INDEX:
return GetDatabaseId<triagens::wal::index_create_marker_t>(marker);
case TRI_WAL_MARKER_DROP_INDEX:
return GetDatabaseId<triagens::wal::index_drop_marker_t>(marker);
case TRI_WAL_MARKER_CREATE_DATABASE:
return GetDatabaseId<triagens::wal::database_create_marker_t>(marker);
case TRI_WAL_MARKER_DROP_DATABASE:
return GetDatabaseId<triagens::wal::database_drop_marker_t>(marker);
default: {
return 0;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief helper function to extract a collection id from a marker
////////////////////////////////////////////////////////////////////////////////
template<typename T>
static TRI_voc_tick_t GetCollectionId (TRI_df_marker_t const* marker) {
T const* m = reinterpret_cast<T const*>(marker);
return m->_collectionId;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the collection id from a marker
////////////////////////////////////////////////////////////////////////////////
static TRI_voc_tick_t GetCollectionFromWalMarker (TRI_df_marker_t const* marker) {
switch (marker->_type) {
case TRI_WAL_MARKER_ATTRIBUTE:
return GetCollectionId<triagens::wal::attribute_marker_t>(marker);
case TRI_WAL_MARKER_SHAPE:
return GetCollectionId<triagens::wal::shape_marker_t>(marker);
case TRI_WAL_MARKER_DOCUMENT:
return GetCollectionId<triagens::wal::document_marker_t>(marker);
case TRI_WAL_MARKER_EDGE:
return GetCollectionId<triagens::wal::edge_marker_t>(marker);
case TRI_WAL_MARKER_REMOVE:
return GetCollectionId<triagens::wal::remove_marker_t>(marker);
case TRI_WAL_MARKER_CREATE_COLLECTION:
return GetCollectionId<triagens::wal::collection_create_marker_t>(marker);
case TRI_WAL_MARKER_DROP_COLLECTION:
return GetCollectionId<triagens::wal::collection_drop_marker_t>(marker);
case TRI_WAL_MARKER_RENAME_COLLECTION:
return GetCollectionId<triagens::wal::collection_rename_marker_t>(marker);
case TRI_WAL_MARKER_CHANGE_COLLECTION:
return GetCollectionId<triagens::wal::collection_change_marker_t>(marker);
case TRI_WAL_MARKER_CREATE_INDEX:
return GetCollectionId<triagens::wal::index_create_marker_t>(marker);
case TRI_WAL_MARKER_DROP_INDEX:
return GetCollectionId<triagens::wal::index_drop_marker_t>(marker);
default: {
return 0;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not a marker is replicated
////////////////////////////////////////////////////////////////////////////////
static bool MustReplicateWalMarker (TRI_replication_dump_t* dump,
TRI_df_marker_t const* marker) {
// first check the marker type
if (! MustReplicateWalMarkerType(marker)) {
return false;
}
// then check if the marker belongs to the "correct" database
if (dump->_vocbase->_id != GetDatabaseFromWalMarker(marker)) {
return false;
}
// finally check if the marker is for a collection that we want to ignore
TRI_voc_cid_t cid = GetCollectionFromWalMarker(marker);
if (cid != 0) {
char const* name = NameFromCid(dump, cid);
if (name != nullptr && TRI_ExcludeCollectionReplication(name)) {
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief dump data from a collection
////////////////////////////////////////////////////////////////////////////////
static int DumpCollection (TRI_replication_dump_t* dump,
TRI_document_collection_t* document,
TRI_voc_tick_t dataMin,
TRI_voc_tick_t dataMax,
bool withTicks,
bool translateCollectionIds,
triagens::arango::CollectionNameResolver* resolver) {
TRI_vector_t datafiles;
TRI_string_buffer_t* buffer;
TRI_voc_tick_t lastFoundTick;
TRI_voc_tid_t lastTid;
size_t i, n;
int res;
bool hasMore;
bool bufferFull;
bool ignoreMarkers;
// The following fake transaction allows us to access data pointers
// and shapers, essentially disabling the runtime checks. This is OK,
// since the dump only considers data files (and not WAL files), so
// the collector has no trouble. Also, the data files of the collection
// are protected from the compactor by a barrier and the dump only goes
// until a certain tick.
triagens::arango::TransactionBase trx(true);
LOG_TRACE("dumping collection %llu, tick range %llu - %llu",
(unsigned long long) document->_info._cid,
(unsigned long long) dataMin,
(unsigned long long) dataMax);
buffer = dump->_buffer;
datafiles = GetRangeDatafiles(document, dataMin, dataMax);
// setup some iteration state
lastFoundTick = 0;
lastTid = 0;
res = TRI_ERROR_NO_ERROR;
hasMore = true;
bufferFull = false;
ignoreMarkers = false;
n = datafiles._length;
for (i = 0; i < n; ++i) {
df_entry_t* e = (df_entry_t*) TRI_AtVector(&datafiles, i);
TRI_datafile_t* datafile = e->_data;
char const* ptr;
char const* end;
// we are reading from a journal that might be modified in parallel
// so we must read-lock it
if (e->_isJournal) {
TRI_READ_LOCK_DOCUMENTS_INDEXES_PRIMARY_COLLECTION(document);
}
else {
TRI_ASSERT(datafile->_isSealed);
}
ptr = datafile->_data;
if (res == TRI_ERROR_NO_ERROR) {
// no error so far. start iterating
end = ptr + datafile->_currentSize;
}
else {
// some error occurred. don't iterate
end = ptr;
}
while (ptr < end) {
TRI_df_marker_t* marker = (TRI_df_marker_t*) ptr;
TRI_voc_tick_t foundTick;
TRI_voc_tid_t tid;
if (marker->_size == 0 || marker->_type <= TRI_MARKER_MIN) {
// end of datafile
break;
}
ptr += TRI_DF_ALIGN_BLOCK(marker->_size);
if (marker->_type == TRI_DF_MARKER_ATTRIBUTE ||
marker->_type == TRI_DF_MARKER_SHAPE) {
// fully ignore these marker types. they don't need to be replicated,
// but we also cannot stop iteration if we find one of these
continue;
}
// get the marker's tick and check whether we should include it
foundTick = marker->_tick;
if (foundTick <= dataMin) {
// marker too old
continue;
}
if (foundTick > dataMax) {
// marker too new
hasMore = false;
goto NEXT_DF;
}
if (marker->_type != TRI_DOC_MARKER_KEY_DOCUMENT &&
marker->_type != TRI_DOC_MARKER_KEY_EDGE &&
marker->_type != TRI_DOC_MARKER_KEY_DELETION) {
// found a non-data marker...
// check if we can abort searching
if (foundTick >= dataMax ||
(foundTick >= e->_tickMax && i == (n - 1))) {
// fetched the last available marker
hasMore = false;
goto NEXT_DF;
}
continue;
}
// note the last tick we processed
lastFoundTick = foundTick;
// handle aborted/unfinished transactions
if (document->_failedTransactions == nullptr) {
// there are no failed transactions
ignoreMarkers = false;
}
else {
// get transaction id of marker
if (marker->_type == TRI_DOC_MARKER_KEY_DELETION) {
tid = ((TRI_doc_deletion_key_marker_t const*) marker)->_tid;
}
else {
tid = ((TRI_doc_document_key_marker_t const*) marker)->_tid;
}
// check if marker is from an aborted transaction
if (tid > 0) {
if (tid != lastTid) {
ignoreMarkers = (document->_failedTransactions->find(tid) != document->_failedTransactions->end());
}
lastTid = tid;
}
if (ignoreMarkers) {
continue;
}
}
res = StringifyMarkerDump(dump, document, marker, withTicks, translateCollectionIds, resolver);
if (res != TRI_ERROR_NO_ERROR) {
break; // will go to NEXT_DF
}
if (foundTick >= dataMax ||
(foundTick >= e->_tickMax && i == (n - 1))) {
// fetched the last available marker
hasMore = false;
goto NEXT_DF;
}
if ((uint64_t) TRI_LengthStringBuffer(buffer) > dump->_chunkSize) {
// abort the iteration
bufferFull = true;
goto NEXT_DF;
}
}
NEXT_DF:
if (e->_isJournal) {
// read-unlock the journal
TRI_READ_UNLOCK_DOCUMENTS_INDEXES_PRIMARY_COLLECTION(document);
}
if (res != TRI_ERROR_NO_ERROR || ! hasMore || bufferFull) {
break;
}
}
TRI_DestroyVector(&datafiles);
if (res == TRI_ERROR_NO_ERROR) {
if (lastFoundTick > 0) {
// data available for requested range
dump->_lastFoundTick = lastFoundTick;
dump->_hasMore = hasMore;
dump->_bufferFull = bufferFull;
}
else {
// no data available for requested range
dump->_lastFoundTick = 0;
dump->_hasMore = false;
dump->_bufferFull = false;
}
}
return res;
}
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief dump data from a collection
////////////////////////////////////////////////////////////////////////////////
int TRI_DumpCollectionReplication (TRI_replication_dump_t* dump,
TRI_vocbase_col_t* col,
TRI_voc_tick_t dataMin,
TRI_voc_tick_t dataMax,
bool withTicks,
bool translateCollectionIds) {
TRI_ASSERT(col != nullptr);
TRI_ASSERT(col->_collection != nullptr);
triagens::arango::CollectionNameResolver resolver(col->_vocbase);
TRI_document_collection_t* document = col->_collection;
// create a barrier so the underlying collection is not unloaded
TRI_barrier_t* b = TRI_CreateBarrierReplication(&document->_barrierList);
if (b == nullptr) {
return TRI_ERROR_OUT_OF_MEMORY;
}
// block compaction
TRI_ReadLockReadWriteLock(&document->_compactionLock);
int res = DumpCollection(dump, document, dataMin, dataMax, withTicks,
translateCollectionIds, &resolver);
TRI_ReadUnlockReadWriteLock(&document->_compactionLock);
TRI_FreeBarrier(b);
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief dump data from the replication log
////////////////////////////////////////////////////////////////////////////////
int TRI_DumpLogReplication (TRI_replication_dump_t* dump,
TRI_voc_tick_t tickMin,
TRI_voc_tick_t tickMax,
bool outputAsArray) {
LOG_TRACE("dumping log, tick range %llu - %llu",
(unsigned long long) tickMin,
(unsigned long long) tickMax);
// ask the logfile manager which datafiles qualify
std::vector<triagens::wal::Logfile*> logfiles = triagens::wal::LogfileManager::instance()->getLogfilesForTickRange(tickMin, tickMax);
size_t const n = logfiles.size();
// setup some iteration state
int res = TRI_ERROR_NO_ERROR;
TRI_voc_tick_t lastFoundTick = 0;
bool hasMore = true;
bool bufferFull = false;
if (outputAsArray) {
TRI_AppendStringStringBuffer(dump->_buffer, "[\n");
}
try {
bool first = true;
// iterate over the datafiles found
for (size_t i = 0; i < n; ++i) {
triagens::wal::Logfile* logfile = logfiles[i];
char const* ptr;
char const* end;
triagens::wal::LogfileManager::instance()->getActiveLogfileRegion(logfile, ptr, end);
while (ptr < end) {
TRI_df_marker_t const* marker = reinterpret_cast<TRI_df_marker_t const*>(ptr);
if (marker->_size == 0 || marker->_type <= TRI_MARKER_MIN) {
// end of datafile
break;
}
ptr += TRI_DF_ALIGN_BLOCK(marker->_size);
// get the marker's tick and check whether we should include it
TRI_voc_tick_t foundTick = marker->_tick;
if (foundTick <= tickMin) {
// marker too old
continue;
}
if (foundTick >= tickMax) {
hasMore = false;
}
if (foundTick > tickMax) {
// marker too new
break;
}
if (! MustReplicateWalMarker(dump, marker)) {
// check if we can abort searching
continue;
}
// note the last tick we processed
lastFoundTick = foundTick;
if (outputAsArray) {
if (! first) {
TRI_AppendStringStringBuffer(dump->_buffer, ", ");
}
else {
first = false;
}
}
res = StringifyWalMarker(dump, marker);
if (res != TRI_ERROR_NO_ERROR) {
THROW_ARANGO_EXCEPTION(res);
}
if ((uint64_t) TRI_LengthStringBuffer(dump->_buffer) >= dump->_chunkSize) {
// abort the iteration
bufferFull = true;
break;
}
}
if (! hasMore || bufferFull) {
break;
}
}
}
catch (triagens::arango::Exception const& ex) {
res = ex.code();
}
catch (...) {
res = TRI_ERROR_INTERNAL;
}
// always return the logfiles we have used
triagens::wal::LogfileManager::instance()->returnLogfiles(logfiles);
if (outputAsArray) {
TRI_AppendStringStringBuffer(dump->_buffer, "\n]");
}
if (res == TRI_ERROR_NO_ERROR) {
if (lastFoundTick > 0) {
// data available for requested range
dump->_lastFoundTick = lastFoundTick;
dump->_hasMore = hasMore;
dump->_bufferFull = bufferFull;
}
else {
// no data available for requested range
dump->_lastFoundTick = 0;
dump->_hasMore = false;
dump->_bufferFull = false;
}
}
return res;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
| 35.033356 | 135 | 0.563922 | [
"vector"
] |
2aeabe34b4bb07942b3baabc5f78ec574a1dd01a | 6,823 | cpp | C++ | plugins/community/repos/bsp/src/TunedDelayLine.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/bsp/src/TunedDelayLine.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/bsp/src/TunedDelayLine.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z | /*
Copyright (c) 2018 bsp
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.
*/
/// When defined, use linear interpolation when reading samples from delay line
// #define USE_FRAC defined
#include <math.h>
#include <stdlib.h> // memset
#include "bsp.hpp"
namespace rack_plugin_bsp {
struct TunedDelayLine : Module {
enum ParamIds {
DRYWET_PARAM,
FB_AMT_PARAM,
FINETUNE_PARAM, // or delaytime in seconds when no V/OCT input is connected
POSTFB_PARAM,
NUM_PARAMS
};
enum InputIds {
VOCT_INPUT,
AUDIO_INPUT,
FB_RET_INPUT,
NUM_INPUTS
};
enum OutputIds {
FB_SEND_OUTPUT,
AUDIO_OUTPUT,
NUM_OUTPUTS
};
#define BUF_SIZE (256u*1024u)
#define BUF_SIZE_MASK (BUF_SIZE - 1u)
float delay_buf[BUF_SIZE];
uint32_t delay_buf_idx;
float last_dly_val;
float sample_rate;
TunedDelayLine() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {
delay_buf_idx = 0u;
::memset((void*)delay_buf, 0, sizeof(delay_buf));
handleSampleRateChanged();
last_dly_val = 0.0f;
}
void handleSampleRateChanged(void) {
sample_rate = engineGetSampleRate();
}
void onSampleRateChange() override {
Module::onSampleRateChange();
handleSampleRateChanged();
}
void step() override;
};
void TunedDelayLine::step() {
// Calculate delay length
float dlySmpOff;
if(inputs[VOCT_INPUT].active)
{
// (note) Freq calculation borrowed from Fundamental.VCO
float pitch = inputs[VOCT_INPUT].value + params[FINETUNE_PARAM].value * (1.0f / 12.0f);
// Note C4
float freq = 261.626f * powf(2.0f, pitch);
dlySmpOff = (1.0f * sample_rate) / freq;
}
else
{
// No input connected, set delay time in the range 0..1 seconds
dlySmpOff = sample_rate * (0.5f + 0.5f * params[FINETUNE_PARAM].value);
}
// Read delayed sample from ring buffer
#ifdef USE_FRAC
uint32_t dlySmpOffI = uint32_t(dlySmpOff);
float dlySmpFrac = dlySmpOff - dlySmpOffI;
dlySmpOffI = (delay_buf_idx - dlySmpOffI) & BUF_SIZE_MASK;
float dlyVal = delay_buf[dlySmpOffI] + (delay_buf[(dlySmpOffI+1u) & BUF_SIZE_MASK] - delay_buf[dlySmpOffI]) * dlySmpFrac;
#else
uint32_t dlySmpOffI = uint32_t(delay_buf_idx - dlySmpOff) & BUF_SIZE_MASK;
float dlyVal = delay_buf[dlySmpOffI];
#endif
bool bPostFBOnly = (params[POSTFB_PARAM].value >= 0.5f);
// Add input signal
float inSmp = inputs[AUDIO_INPUT].value;
if(bPostFBOnly)
{
dlyVal += inSmp;
}
// Send it to external module(s)
outputs[FB_SEND_OUTPUT].value = dlyVal;
float fbVal;
// Read back processed feedback value
if(inputs[FB_RET_INPUT].active)
{
// Use externally processed feedback sample
// (note) this is actually shifted / delayed by one sample
fbVal = inputs[FB_RET_INPUT].value;
}
else
{
// Fallback: feedback send+return not connected, use builtin filter instead
fbVal = (last_dly_val + dlyVal) * 0.5f;
last_dly_val = dlyVal;
}
// Apply feedback amount
float fbAmt = params[FB_AMT_PARAM].value;
fbAmt = 1.0f - fbAmt;
fbAmt *= fbAmt;
fbAmt *= fbAmt;
fbAmt = 1.0f - fbAmt;
fbVal *= fbAmt;
if(!bPostFBOnly)
{
// Add input signal
fbVal += inSmp;
}
// Write new delay sample to ring buffer
delay_buf[delay_buf_idx] = fbVal;
delay_buf_idx = (delay_buf_idx + 1u) & BUF_SIZE_MASK;
// Final output
float outVal;
if(bPostFBOnly)
{
outVal = inSmp + (fbVal - inSmp) * params[DRYWET_PARAM].value;
}
else
{
outVal = inSmp + (dlyVal - inSmp) * params[DRYWET_PARAM].value;
}
outputs[AUDIO_OUTPUT].value = outVal;
#if 0
static int xxx = 0;
if(0 == (++xxx & 32767))
{
printf("xxx V/OCT=%f freq=%f inSmp=%f dlySmpOff=%f dlyVal=%f fbVal=%f outVal=%f fbAmt=%f\n", inputs[VOCT_INPUT].value, freq, inSmp, dlySmpOff, dlyVal, fbVal, outVal, fbAmt);
}
#endif
}
struct TunedDelayLineWidget : ModuleWidget {
TunedDelayLineWidget(TunedDelayLine *module);
};
TunedDelayLineWidget::TunedDelayLineWidget(TunedDelayLine *module) : ModuleWidget(module) {
setPanel(SVG::load(assetPlugin(plugin, "res/TunedDelayLine.svg")));
addChild(Widget::create<ScrewSilver>(Vec(15, 0)));
addChild(Widget::create<ScrewSilver>(Vec(15, 365)));
float cx;
float cy;
cx = 9.0f;
cy = 37.0f;
addInput(Port::create<PJ301MPort>(Vec(cx+2.0f, cy), Port::INPUT, module, TunedDelayLine::VOCT_INPUT));
addParam(ParamWidget::create<RoundBlackKnob>(Vec(cx, cy + 32), module, TunedDelayLine::FINETUNE_PARAM, -1.0f, 1.0f, 0.0f));
#define STY 32.0f
cx = 11.0f;
cy = 120.0f;
addOutput(Port::create<PJ301MPort>(Vec(cx, cy), Port::OUTPUT, module, TunedDelayLine::FB_SEND_OUTPUT));
cy += STY;
addInput(Port::create<PJ301MPort>(Vec(cx, cy), Port::INPUT, module, TunedDelayLine::FB_RET_INPUT));
cy += STY;
addParam(ParamWidget::create<RoundBlackKnob>(Vec(cx-2.0f, cy), module, TunedDelayLine::FB_AMT_PARAM, 0.0f, 1.0f, 0.3f));
#undef STY
cx = 16.0f;
cy = 218.0f;
addParam(ParamWidget::create<CKSS>(Vec(cx, cy), module, TunedDelayLine::POSTFB_PARAM, 0.0f, 1.0f, 1.0f));
cx = 9.0f;
cy = 245.0f;
addParam(ParamWidget::create<RoundBlackKnob>(Vec(cx, cy), module, TunedDelayLine::DRYWET_PARAM, 0.0f, 1.0f, 1.0f));
#define STY 40.0f
cx = 11.0f;
cy = 325.0f;
addInput(Port::create<PJ301MPort>(Vec(cx, cy - STY), Port::INPUT, module, TunedDelayLine::AUDIO_INPUT));
addOutput(Port::create<PJ301MPort>(Vec(cx, 325), Port::OUTPUT, module, TunedDelayLine::AUDIO_OUTPUT));
#undef STY
}
} // namespace rack_plugin_bsp
using namespace rack_plugin_bsp;
RACK_PLUGIN_MODEL_INIT(bsp, TunedDelayLine) {
Model *modelTunedDelayLine = Model::create<TunedDelayLine, TunedDelayLineWidget>("bsp", "TunedDelayLine", "Tuned Delay Line", ATTENUATOR_TAG, MIXER_TAG);
return modelTunedDelayLine;
}
| 29.034043 | 179 | 0.697933 | [
"model"
] |
2aee94170fc66e132ee5c1372780f380c4f1dd16 | 4,206 | cpp | C++ | jni/pendercanvasjs/pendercanvasjs.cpp | lorinbeer/vatedroid | dbc648ef2d39b9d55c247db8c68818fb11d2fdc8 | [
"Apache-2.0"
] | 7 | 2015-02-05T03:45:23.000Z | 2020-07-04T15:01:22.000Z | jni/pendercanvasjs/pendercanvasjs.cpp | lorinbeer/vatedroid | dbc648ef2d39b9d55c247db8c68818fb11d2fdc8 | [
"Apache-2.0"
] | null | null | null | jni/pendercanvasjs/pendercanvasjs.cpp | lorinbeer/vatedroid | dbc648ef2d39b9d55c247db8c68818fb11d2fdc8 | [
"Apache-2.0"
] | null | null | null |
#include <list>
#include <assert.h>
#include <android/log.h>
#include <stdio.h>
#include "pendercanvasjs.h"
v8::Handle<v8::Value> ParmenidesConstructorHelper(const v8::Arguments & args);
/*
* dynamically defines the canvas api
*/
PenderCanvasJS::PenderCanvasJS() {
HandleScope localscope;
Handle<FunctionTemplate> _object = FunctionTemplate::New(ParmenidesConstructorHelper);
_CanvasFunctionTemplate = Persistent<FunctionTemplate>::New(_object);
// _CanvasFunctionTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(ParmenidesConstructorHelper));
// read out canvasapi.def
list<string> apidef;
int i = 0;
//====================================================================================================
// Transformation Functions
_FunctionMap.insert (pair<string,int>("scale",i++));
_FunctionMap.insert (pair<string,int>("rotate",i++));
_FunctionMap.insert (pair<string,int>("translate",i++));
_FunctionMap.insert (pair<string,int>("transform",i++));
_FunctionMap.insert (pair<string,int>("settransform",i++));
_FunctionMap.insert (pair<string,int>("gettransform",i++));
//====================================================================================================
// Compositing
//====================================================================================================
// Image Smoothing
//====================================================================================================
// Colors and Styles
//====================================================================================================
// Shadows
//====================================================================================================
// Rects API
//====================================================================================================
// Path API
//====================================================================================================
// Text API
//====================================================================================================
// Image Draw API
_FunctionMap.insert (pair<string,int>("drawImage",i++));
//====================================================================================================
// Hit Regions
//====================================================================================================
// Pixel Manipulation
//====================================================================================================
}
void PenderCanvasJS::injectInto(Handle<Context> ctx) {
HandleScope localscope;
//Context::Scope execCtx(ctx);
//Handle<Object> global = ctx->Global();
char * str = new char[256];
sprintf (str,"%d",_CanvasFunctionTemplate);
__android_log_write(ANDROID_LOG_DEBUG,"PENDERCANVASJS INJECTINTO", str);
//asserit(ctx);
delete [] str;
Handle<ObjectTemplate> protoTemplate = _CanvasFunctionTemplate->PrototypeTemplate();
//assert(_CanvasFunctionTemplate);
// _CanvasFunctionTemplate->GetFunction();
//global->Set(String::New("Canvas"), _CanvasFunctionTemplate->GetFunction());
__android_log_write(ANDROID_LOG_DEBUG,"FUCK YEAH!, WE HAVE INJECTED!", "HAVE WE?");
}
void PenderCanvasJS::initCanvasFunctionTemplate() {
/*
HandleScope localscope;
Handle<ObjectTemplate> protoTemplate = _CanvasFunctionTemplate->PrototypeTemplate();
for (map<string,int>::iterator it = _FunctionMap.begin(); it != _FunctionMap.end(); it++) {
protoTemplate->Set(it->first.c_str(), FunctionTemplate::New(CanvasRenderHandler, Number::New(it->second)) );
}
*/
}
Handle<Value> PenderCanvasJS::CanvasRenderHandler(const Arguments & args) {
return String::New("canvas render handler message");
}
v8::Handle<v8::Value> ParmenidesConstructorHelper(const v8::Arguments & args) {
__android_log_write(ANDROID_LOG_DEBUG, "Pender NDK", "PARMENIDES CONSTRUCTOR HELPER");
using namespace v8;
// throw if called without `new'
if (!args.IsConstructCall()) {
return ThrowException(String::New("Cannot call constructor as function, use with new"));
}
HandleScope scope;
return v8::String::New("demicanadian battle-felon");
}
| 42.484848 | 119 | 0.503566 | [
"render",
"object",
"transform"
] |
2aef5b5d5a919cf6ad5e1df96db76371d518ce08 | 886 | hpp | C++ | libs/imagecolor/include/sge/image/color/any/compare.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/imagecolor/include/sge/image/color/any/compare.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/imagecolor/include/sge/image/color/any/compare.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// 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)
#ifndef SGE_IMAGE_COLOR_ANY_COMPARE_HPP_INCLUDED
#define SGE_IMAGE_COLOR_ANY_COMPARE_HPP_INCLUDED
#include <sge/image/color/any/object.hpp>
#include <mizuiro/color/compare.hpp>
#include <fcppt/variant/compare.hpp>
namespace sge::image::color::any
{
template <typename CompareChannels>
bool compare(
sge::image::color::any::object const &_a,
sge::image::color::any::object const &_b,
CompareChannels const &_compare_channels)
{
return fcppt::variant::compare(
_a.get(),
_b.get(),
[&_compare_channels](auto const &_left, auto const &_right)
{ return mizuiro::color::compare(_left, _right, _compare_channels); });
}
}
#endif
| 27.6875 | 77 | 0.713318 | [
"object"
] |
2af161509c6f505b1e585af8c0172b52ad9b614c | 4,834 | hpp | C++ | src/ct_icp/types.hpp | xiang-1208/ct_icp | 42928e584c24595c49e147e2ea120f8cc31ec716 | [
"MIT"
] | 123 | 2021-10-08T01:51:45.000Z | 2022-03-31T08:55:15.000Z | src/ct_icp/types.hpp | ZuoJiaxing/ct_icp | 1c371331aad833faec157c015fb8f72143019caa | [
"MIT"
] | 9 | 2021-10-19T07:25:46.000Z | 2022-03-31T03:20:19.000Z | src/ct_icp/types.hpp | ZuoJiaxing/ct_icp | 1c371331aad833faec157c015fb8f72143019caa | [
"MIT"
] | 23 | 2021-10-08T01:49:01.000Z | 2022-03-24T15:35:07.000Z | #ifndef CT_ICP_TYPES_HPP
#define CT_ICP_TYPES_HPP
#include <map>
#include <unordered_map>
#include <list>
#include <tsl/robin_map.h>
#include <Eigen/Dense>
#include <Eigen/StdVector>
#include <glog/logging.h>
#include "utils.hpp"
#define _USE_MATH_DEFINES
#include <math.h>
namespace ct_icp {
// A Point3D
struct Point3D {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Eigen::Vector3d raw_pt; // Raw point read from the sensor
Eigen::Vector3d pt; // Corrected point taking into account the motion of the sensor during frame acquisition
double alpha_timestamp = 0.0; // Relative timestamp in the frame in [0.0, 1.0]
double timestamp = 0.0; // The absolute timestamp (if applicable)
int index_frame = -1; // The frame index
Point3D() = default;
};
inline double AngularDistance(const Eigen::Matrix3d &rota,
const Eigen::Matrix3d &rotb) {
double norm = ((rota * rotb.transpose()).trace() - 1) / 2;
norm = std::acos(norm) * 180 / M_PI;
return norm;
}
// A Trajectory Frame
struct TrajectoryFrame {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
bool success = true;
double begin_timestamp = 0.0;
double end_timestamp = 1.0;
Eigen::Matrix3d begin_R;
Eigen::Vector3d begin_t;
Eigen::Matrix3d end_R;
Eigen::Vector3d end_t;
inline double EgoAngularDistance() const {
return AngularDistance(begin_R, end_R);
}
double TranslationDistance(const TrajectoryFrame &other) {
return (begin_t - other.begin_t).norm() + (end_t - other.end_t).norm();
}
double RotationDistance(const TrajectoryFrame &other) {
return (begin_R * other.begin_R.inverse() - Eigen::Matrix3d::Identity()).norm() +
(end_R * other.end_R.inverse() - Eigen::Matrix3d::Identity()).norm();
}
TrajectoryFrame() = default;
[[nodiscard]] inline Eigen::Matrix4d MidPose() const {
Eigen::Matrix4d mid_pose = Eigen::Matrix4d::Identity();
auto q_begin = Eigen::Quaterniond(begin_R);
auto q_end = Eigen::Quaterniond(end_R);
Eigen::Vector3d t_begin = begin_t;
Eigen::Vector3d t_end = end_t;
Eigen::Quaterniond q = q_begin.slerp(0.5, q_end);
q.normalize();
mid_pose.block<3, 3>(0, 0) = q.toRotationMatrix();
mid_pose.block<3, 1>(0, 3) = 0.5 * t_begin + 0.5 * t_end;
return mid_pose;
}
};
// Voxel
// Note: Coordinates range is in [-32 768, 32 767]
struct Voxel {
Voxel() = default;
Voxel(short x, short y, short z) : x(x), y(y), z(z) {}
bool operator==(const Voxel &vox) const { return x == vox.x && y == vox.y && z == vox.z; }
inline bool operator<(const Voxel &vox) const {
return x < vox.x || (x == vox.x && y < vox.y) || (x == vox.x && y == vox.y && z < vox.z);
}
inline static Voxel Coordinates(const Eigen::Vector3d &point, double voxel_size) {
return {short(point.x() / voxel_size),
short(point.y() / voxel_size),
short(point.z() / voxel_size)};
}
short x;
short y;
short z;
};
typedef std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> ArrayVector3d;
typedef std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>> ArrayMatrix4d;
typedef ArrayMatrix4d ArrayPoses;
struct VoxelBlock {
explicit VoxelBlock(int num_points = 20) : num_points_(num_points) { points.reserve(num_points); }
ArrayVector3d points;
bool IsFull() const { return num_points_ == points.size(); }
void AddPoint(const Eigen::Vector3d &point) {
CHECK(num_points_ >= points.size()) << "Voxel Is Full";
points.push_back(point);
}
inline int NumPoints() const { return points.size(); }
inline int Capacity() { return num_points_; }
private:
int num_points_;
};
typedef tsl::robin_map<Voxel, VoxelBlock> VoxelHashMap;
} // namespace Elastic_ICP
// Specialization of std::hash for our custom type Voxel
namespace std {
template<>
struct hash<ct_icp::Voxel> {
std::size_t operator()(const ct_icp::Voxel &vox) const {
#ifdef CT_ICP_IS_WINDOWS
const std::hash<int32_t> hasher;
return ((hasher(vox.x) ^ (hasher(vox.y) << 1)) >> 1) ^ (hasher(vox.z) << 1) >> 1;
#else
const size_t kP1 = 73856093;
const size_t kP2 = 19349669;
const size_t kP3 = 83492791;
return vox.x * kP1 + vox.y * kP2 + vox.z * kP3;
#endif
}
};
}
#endif //CT_ICP_TYPES_HPP
| 29.839506 | 116 | 0.590401 | [
"vector"
] |
2afb0499aad86a7301866f4e3907f60a04d56df1 | 2,729 | hpp | C++ | parser/ParseLimit.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 82 | 2016-04-18T03:59:06.000Z | 2019-02-04T11:46:08.000Z | parser/ParseLimit.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 265 | 2016-04-19T17:52:43.000Z | 2018-10-11T17:55:08.000Z | parser/ParseLimit.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 68 | 2016-04-18T05:00:34.000Z | 2018-10-30T12:41:02.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
#ifndef QUICKSTEP_PARSER_PARSE_LIMIT_HPP_
#define QUICKSTEP_PARSER_PARSE_LIMIT_HPP_
#include <memory>
#include <string>
#include <vector>
#include "parser/ParseLiteralValue.hpp"
#include "parser/ParseTreeNode.hpp"
#include "utility/Macros.hpp"
namespace quickstep {
/** \addtogroup Parser
* @{
*/
/**
* @brief A parsed representation of LIMIT.
*/
class ParseLimit : public ParseTreeNode {
public:
/**
* @brief Constructor.
*
* @param line_number The line number of "LIMIT" in the SQL statement.
* @param column_number The column number of "LIMIT" in the SQL statement.
* @param limit_expression The LIMIT value expression.
*/
ParseLimit(const int line_number, const int column_number, NumericParseLiteralValue *limit_expression)
: ParseTreeNode(line_number, column_number),
limit_expression_(limit_expression) {
}
/**
* @brief Destructor.
*/
~ParseLimit() override {}
/**
* @brief Gets the LIMIT expression.
*
* @return LIMIT expression
*/
const NumericParseLiteralValue* limit_expression() const {
return limit_expression_.get();
}
std::string getName() const override {
return "LIMIT";
}
protected:
void getFieldStringItems(std::vector<std::string> *inline_field_names,
std::vector<std::string> *inline_field_values,
std::vector<std::string> *non_container_child_field_names,
std::vector<const ParseTreeNode*> *non_container_child_fields,
std::vector<std::string> *container_child_field_names,
std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override;
private:
std::unique_ptr<NumericParseLiteralValue> limit_expression_;
DISALLOW_COPY_AND_ASSIGN(ParseLimit);
};
/** @} */
} // namespace quickstep
#endif /* QUICKSTEP_PARSER_PARSELIMIT_HPP_ */
| 29.989011 | 114 | 0.702089 | [
"vector"
] |
6304ba8d0c7eb60668c02a60d63ab2a739d801b3 | 912 | cpp | C++ | gui/qt-gui/processor/houghtransform.cpp | yleniaBattistini/ObjectTracker | 9f408d2c8e55209e80592ab17e6cddfddb38f5c4 | [
"MIT"
] | null | null | null | gui/qt-gui/processor/houghtransform.cpp | yleniaBattistini/ObjectTracker | 9f408d2c8e55209e80592ab17e6cddfddb38f5c4 | [
"MIT"
] | null | null | null | gui/qt-gui/processor/houghtransform.cpp | yleniaBattistini/ObjectTracker | 9f408d2c8e55209e80592ab17e6cddfddb38f5c4 | [
"MIT"
] | null | null | null | #include "houghtransform.h"
#include <opencv2\imgcodecs.hpp>
#include <opencv2\highgui.hpp>
#include <opencv2\imgproc.hpp>
#include <opencv2\core\types.hpp>
#include <vector>
using namespace cv;
using namespace std;
void HoughTransform::houghTransform(Mat& input, vector<Rect> &circles)
{
// Circle Detection Hough Transform
Mat gray;
cvtColor(input, gray, COLOR_RGB2GRAY);
medianBlur(gray, gray, 5);
vector<Vec3f> circlesAsVectors;
HoughCircles(
gray,
circlesAsVectors,
HOUGH_GRADIENT,
1.15, //or 1.5, without 100 & 30
gray.rows / 5 // change this value to detect circles with different distances to each other
);
circles.clear();
for (Vec3f &c : circlesAsVectors)
{
int radius = c[2];
int x = c[0];
int y = c[1];
circles.push_back(Rect(x - radius, y - radius, radius * 2, radius * 2));
}
}
| 25.333333 | 99 | 0.639254 | [
"vector",
"transform"
] |
630a4cde48abb39c17cc77b22b3c9076aa1e9bbb | 20,281 | hpp | C++ | src/libraries/core/interpolation/volPointInterpolation/volPointInterpolation.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/interpolation/volPointInterpolation/volPointInterpolation.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/interpolation/volPointInterpolation/volPointInterpolation.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::volPointInterpolation
Description
Interpolate from cell centres to points (vertices) using inverse distance
weighting
SourceFiles
volPointInterpolation.cpp
volPointInterpolate.cpp
\*---------------------------------------------------------------------------*/
#ifndef volPointInterpolation_H
#define volPointInterpolation_H
#include "MeshObject.hpp"
#include "scalarList.hpp"
#include "volFields.hpp"
#include "pointFields.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
class fvMesh;
class pointMesh;
/*---------------------------------------------------------------------------*\
Class volPointInterpolation Declaration
\*---------------------------------------------------------------------------*/
class volPointInterpolation
:
public MeshObject<fvMesh, volPointInterpolation>
{
// Private data
//- Interpolation scheme weighting factor array.
scalarListList pointWeights_;
// Boundary handling
//- Boundary addressing
autoPtr<primitivePatch> boundaryPtr_;
//- Per boundary face whether is on non-coupled patch
boolList boundaryIsPatchFace_;
//- Per mesh(!) point whether is on non-coupled patch (on any
// processor)
boolList isPatchPoint_;
//- Per boundary point the weights per pointFaces.
scalarListList boundaryPointWeights_;
// Private Member Functions
//- Construct addressing over all boundary faces
void calcBoundaryAddressing();
//- Make weights for internal and coupled-only boundarypoints
void makeInternalWeights(scalarField& sumWeights);
//- Make weights for points on uncoupled patches
void makeBoundaryWeights(scalarField& sumWeights);
//- Construct all point weighting factors
void makeWeights();
//- Helper: push master point data to collocated points
template<class Type>
void pushUntransformedData(List<Type>&) const;
//- Get boundary field in same order as boundary faces. Field is
// zero on all coupled and empty patches
template<class Type>
tmp<Field<Type> > flatBoundaryField
(
const GeometricField<Type, fvPatchField, volMesh>& vf
) const;
//- Add separated contributions
template<class Type>
void addSeparated
(
GeometricField<Type, pointPatchField, pointMesh>&
) const;
//- Disallow default bitwise copy construct
volPointInterpolation(const volPointInterpolation&);
//- Disallow default bitwise assignment
void operator=(const volPointInterpolation&);
public:
// Declare name of the class and its debug switch
ClassName("volPointInterpolation");
// Constructors
//- Constructor given fvMesh and pointMesh.
explicit volPointInterpolation(const fvMesh&);
//- Destructor
~volPointInterpolation();
// Member functions
// Edit
//- Update mesh topology using the morph engine
void updateMesh();
//- Correct weighting factors for moving mesh.
bool movePoints();
// Interpolation functions
//- Interpolate volField using inverse distance weighting
// returning pointField
template<class Type>
tmp<GeometricField<Type, pointPatchField, pointMesh> > interpolate
(
const GeometricField<Type, fvPatchField, volMesh>&
) const;
//- Interpolate tmp<volField> using inverse distance weighting
// returning pointField
template<class Type>
tmp<GeometricField<Type, pointPatchField, pointMesh> > interpolate
(
const tmp<GeometricField<Type, fvPatchField, volMesh> >&
) const;
//- Interpolate volField using inverse distance weighting
// returning pointField with the same patchField types. Assigns
// to any fixedValue boundary conditions to make them consistent
// with internal field
template<class Type>
tmp<GeometricField<Type, pointPatchField, pointMesh> > interpolate
(
const GeometricField<Type, fvPatchField, volMesh>&,
const wordList& patchFieldTypes
) const;
//- Interpolate tmp<volField> using inverse distance weighting
// returning pointField with the same patchField types. Assigns
// to any fixedValue boundary conditions to make them consistent
// with internal field
template<class Type>
tmp<GeometricField<Type, pointPatchField, pointMesh> > interpolate
(
const tmp<GeometricField<Type, fvPatchField, volMesh> >&,
const wordList& patchFieldTypes
) const;
// Low level
//- Interpolate internal field from volField to pointField
// using inverse distance weighting
template<class Type>
void interpolateInternalField
(
const GeometricField<Type, fvPatchField, volMesh>&,
GeometricField<Type, pointPatchField, pointMesh>&
) const;
//- Interpolate boundary field without applying constraints/boundary
// conditions
template<class Type>
void interpolateBoundaryField
(
const GeometricField<Type, fvPatchField, volMesh>& vf,
GeometricField<Type, pointPatchField, pointMesh>& pf
) const;
//- Interpolate boundary with constraints/boundary conditions
template<class Type>
void interpolateBoundaryField
(
const GeometricField<Type, fvPatchField, volMesh>& vf,
GeometricField<Type, pointPatchField, pointMesh>& pf,
const bool overrideFixedValue
) const;
//- Interpolate from volField to pointField
// using inverse distance weighting
template<class Type>
void interpolate
(
const GeometricField<Type, fvPatchField, volMesh>&,
GeometricField<Type, pointPatchField, pointMesh>&
) const;
//- Interpolate volField using inverse distance weighting
// returning pointField with name. Optionally caches
template<class Type>
tmp<GeometricField<Type, pointPatchField, pointMesh> > interpolate
(
const GeometricField<Type, fvPatchField, volMesh>&,
const word& name,
const bool cache
) const;
// Interpolation for displacement (applies 2D correction)
//- Interpolate from volField to pointField
// using inverse distance weighting
void interpolateDisplacement
(
const volVectorField&,
pointVectorField&
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "volFields.hpp"
#include "pointFields.hpp"
#include "emptyFvPatch.hpp"
#include "coupledPointPatchField.hpp"
#include "pointConstraints.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
template<class Type>
void CML::volPointInterpolation::pushUntransformedData
(
List<Type>& pointData
) const
{
// Transfer onto coupled patch
const globalMeshData& gmd = mesh().globalData();
const indirectPrimitivePatch& cpp = gmd.coupledPatch();
const labelList& meshPoints = cpp.meshPoints();
const mapDistribute& slavesMap = gmd.globalCoPointSlavesMap();
const labelListList& slaves = gmd.globalCoPointSlaves();
List<Type> elems(slavesMap.constructSize());
forAll(meshPoints, i)
{
elems[i] = pointData[meshPoints[i]];
}
// Combine master data with slave data
forAll(slaves, i)
{
const labelList& slavePoints = slaves[i];
// Copy master data to slave slots
forAll(slavePoints, j)
{
elems[slavePoints[j]] = elems[i];
}
}
// Push slave-slot data back to slaves
slavesMap.reverseDistribute(elems.size(), elems, false);
// Extract back onto mesh
forAll(meshPoints, i)
{
pointData[meshPoints[i]] = elems[i];
}
}
template<class Type>
void CML::volPointInterpolation::addSeparated
(
GeometricField<Type, pointPatchField, pointMesh>& pf
) const
{
if (debug)
{
Pout<< "volPointInterpolation::addSeparated" << endl;
}
typename GeometricField<Type, pointPatchField, pointMesh>::
GeometricBoundaryField& pfbf = pf.boundaryField();
forAll(pfbf, patchI)
{
if (pfbf[patchI].coupled())
{
refCast<coupledPointPatchField<Type> >
(pfbf[patchI]).initSwapAddSeparated
(
Pstream::nonBlocking,
pf.internalField()
);
}
}
// Block for any outstanding requests
Pstream::waitRequests();
forAll(pfbf, patchI)
{
if (pfbf[patchI].coupled())
{
refCast<coupledPointPatchField<Type> >
(pfbf[patchI]).swapAddSeparated
(
Pstream::nonBlocking,
pf.internalField()
);
}
}
}
template<class Type>
void CML::volPointInterpolation::interpolateInternalField
(
const GeometricField<Type, fvPatchField, volMesh>& vf,
GeometricField<Type, pointPatchField, pointMesh>& pf
) const
{
if (debug)
{
Pout<< "volPointInterpolation::interpolateInternalField("
<< "const GeometricField<Type, fvPatchField, volMesh>&, "
<< "GeometricField<Type, pointPatchField, pointMesh>&) : "
<< "interpolating field from cells to points"
<< endl;
}
const labelListList& pointCells = vf.mesh().pointCells();
// Multiply volField by weighting factor matrix to create pointField
forAll(pointCells, pointi)
{
if (!isPatchPoint_[pointi])
{
const scalarList& pw = pointWeights_[pointi];
const labelList& ppc = pointCells[pointi];
pf[pointi] = pTraits<Type>::zero;
forAll(ppc, pointCelli)
{
pf[pointi] += pw[pointCelli]*vf[ppc[pointCelli]];
}
}
}
}
template<class Type>
CML::tmp<CML::Field<Type> > CML::volPointInterpolation::flatBoundaryField
(
const GeometricField<Type, fvPatchField, volMesh>& vf
) const
{
const fvMesh& mesh = vf.mesh();
const fvBoundaryMesh& bm = mesh.boundary();
tmp<Field<Type> > tboundaryVals
(
new Field<Type>(mesh.nFaces()-mesh.nInternalFaces())
);
Field<Type>& boundaryVals = tboundaryVals();
forAll(vf.boundaryField(), patchI)
{
label bFaceI = bm[patchI].patch().start() - mesh.nInternalFaces();
if
(
!isA<emptyFvPatch>(bm[patchI])
&& !vf.boundaryField()[patchI].coupled()
)
{
SubList<Type>
(
boundaryVals,
vf.boundaryField()[patchI].size(),
bFaceI
).assign(vf.boundaryField()[patchI]);
}
else
{
const polyPatch& pp = bm[patchI].patch();
forAll(pp, i)
{
boundaryVals[bFaceI++] = pTraits<Type>::zero;
}
}
}
return tboundaryVals;
}
template<class Type>
void CML::volPointInterpolation::interpolateBoundaryField
(
const GeometricField<Type, fvPatchField, volMesh>& vf,
GeometricField<Type, pointPatchField, pointMesh>& pf
) const
{
const primitivePatch& boundary = boundaryPtr_();
Field<Type>& pfi = pf.internalField();
// Get face data in flat list
tmp<Field<Type> > tboundaryVals(flatBoundaryField(vf));
const Field<Type>& boundaryVals = tboundaryVals();
// Do points on 'normal' patches from the surrounding patch faces
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
forAll(boundary.meshPoints(), i)
{
label pointI = boundary.meshPoints()[i];
if (isPatchPoint_[pointI])
{
const labelList& pFaces = boundary.pointFaces()[i];
const scalarList& pWeights = boundaryPointWeights_[i];
Type& val = pfi[pointI];
val = pTraits<Type>::zero;
forAll(pFaces, j)
{
if (boundaryIsPatchFace_[pFaces[j]])
{
val += pWeights[j]*boundaryVals[pFaces[j]];
}
}
}
}
// Sum collocated contributions
pointConstraints::syncUntransformedData(mesh(), pfi, plusEqOp<Type>());
// And add separated contributions
addSeparated(pf);
// Push master data to slaves. It is possible (not sure how often) for
// a coupled point to have its master on a different patch so
// to make sure just push master data to slaves.
pushUntransformedData(pfi);
}
template<class Type>
void CML::volPointInterpolation::interpolateBoundaryField
(
const GeometricField<Type, fvPatchField, volMesh>& vf,
GeometricField<Type, pointPatchField, pointMesh>& pf,
const bool overrideFixedValue
) const
{
interpolateBoundaryField(vf, pf);
// Apply constraints
const pointConstraints& pcs = pointConstraints::New(pf.mesh());
pcs.constrain(pf, overrideFixedValue);
}
template<class Type>
void CML::volPointInterpolation::interpolate
(
const GeometricField<Type, fvPatchField, volMesh>& vf,
GeometricField<Type, pointPatchField, pointMesh>& pf
) const
{
if (debug)
{
Pout<< "volPointInterpolation::interpolate("
<< "const GeometricField<Type, fvPatchField, volMesh>&, "
<< "GeometricField<Type, pointPatchField, pointMesh>&) : "
<< "interpolating field from cells to points"
<< endl;
}
interpolateInternalField(vf, pf);
// Interpolate to the patches preserving fixed value BCs
interpolateBoundaryField(vf, pf, false);
}
template<class Type>
CML::tmp<CML::GeometricField<Type, CML::pointPatchField, CML::pointMesh> >
CML::volPointInterpolation::interpolate
(
const GeometricField<Type, fvPatchField, volMesh>& vf,
const wordList& patchFieldTypes
) const
{
const pointMesh& pm = pointMesh::New(vf.mesh());
// Construct tmp<pointField>
tmp<GeometricField<Type, pointPatchField, pointMesh> > tpf
(
new GeometricField<Type, pointPatchField, pointMesh>
(
IOobject
(
"volPointInterpolate(" + vf.name() + ')',
vf.instance(),
pm.thisDb()
),
pm,
vf.dimensions(),
patchFieldTypes
)
);
interpolateInternalField(vf, tpf());
// Interpolate to the patches overriding fixed value BCs
interpolateBoundaryField(vf, tpf(), true);
return tpf;
}
template<class Type>
CML::tmp<CML::GeometricField<Type, CML::pointPatchField, CML::pointMesh> >
CML::volPointInterpolation::interpolate
(
const tmp<GeometricField<Type, fvPatchField, volMesh> >& tvf,
const wordList& patchFieldTypes
) const
{
// Construct tmp<pointField>
tmp<GeometricField<Type, pointPatchField, pointMesh> > tpf =
interpolate(tvf(), patchFieldTypes);
tvf.clear();
return tpf;
}
template<class Type>
CML::tmp<CML::GeometricField<Type, CML::pointPatchField, CML::pointMesh> >
CML::volPointInterpolation::interpolate
(
const GeometricField<Type, fvPatchField, volMesh>& vf,
const word& name,
const bool cache
) const
{
typedef GeometricField<Type, pointPatchField, pointMesh> PointFieldType;
const pointMesh& pm = pointMesh::New(vf.mesh());
const objectRegistry& db = pm.thisDb();
if (!cache || vf.mesh().changing())
{
// Delete any old occurrences to avoid double registration
if (db.objectRegistry::template foundObject<PointFieldType>(name))
{
PointFieldType& pf = const_cast<PointFieldType&>
(
db.objectRegistry::template lookupObject<PointFieldType>(name)
);
if (pf.ownedByRegistry())
{
solution::cachePrintMessage("Deleting", name, vf);
pf.release();
delete &pf;
}
}
tmp<GeometricField<Type, pointPatchField, pointMesh> > tpf
(
new GeometricField<Type, pointPatchField, pointMesh>
(
IOobject
(
name,
vf.instance(),
pm.thisDb()
),
pm,
vf.dimensions()
)
);
interpolate(vf, tpf());
return tpf;
}
else
{
if (!db.objectRegistry::template foundObject<PointFieldType>(name))
{
solution::cachePrintMessage("Calculating and caching", name, vf);
tmp<PointFieldType> tpf = interpolate(vf, name, false);
PointFieldType* pfPtr = tpf.ptr();
regIOobject::store(pfPtr);
return *pfPtr;
}
else
{
PointFieldType& pf = const_cast<PointFieldType&>
(
db.objectRegistry::template lookupObject<PointFieldType>(name)
);
if (pf.upToDate(vf)) //TBD: , vf.mesh().points()))
{
solution::cachePrintMessage("Reusing", name, vf);
return pf;
}
else
{
solution::cachePrintMessage("Deleting", name, vf);
pf.release();
delete &pf;
solution::cachePrintMessage("Recalculating", name, vf);
tmp<PointFieldType> tpf = interpolate(vf, name, false);
solution::cachePrintMessage("Storing", name, vf);
PointFieldType* pfPtr = tpf.ptr();
regIOobject::store(pfPtr);
// Note: return reference, not pointer
return *pfPtr;
}
}
}
}
template<class Type>
CML::tmp<CML::GeometricField<Type, CML::pointPatchField, CML::pointMesh> >
CML::volPointInterpolation::interpolate
(
const GeometricField<Type, fvPatchField, volMesh>& vf
) const
{
return interpolate(vf, "volPointInterpolate(" + vf.name() + ')', false);
}
template<class Type>
CML::tmp<CML::GeometricField<Type, CML::pointPatchField, CML::pointMesh> >
CML::volPointInterpolation::interpolate
(
const tmp<GeometricField<Type, fvPatchField, volMesh> >& tvf
) const
{
// Construct tmp<pointField>
tmp<GeometricField<Type, pointPatchField, pointMesh> > tpf =
interpolate(tvf());
tvf.clear();
return tpf;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 28.685997 | 80 | 0.580001 | [
"mesh"
] |
debdcfcf54bdccb1437ecf3b8a42044d2975768e | 2,942 | cpp | C++ | src/stats/StatisticalFormulas.cpp | IreneGR92/Group-augmentation-Basic | 9225c44e6608981d25b45e5575fd9922a358d1e0 | [
"MIT"
] | 1 | 2018-12-22T08:49:09.000Z | 2018-12-22T08:49:09.000Z | src/stats/StatisticalFormulas.cpp | IreneGR92/Group-augmentation-Basic | 9225c44e6608981d25b45e5575fd9922a358d1e0 | [
"MIT"
] | null | null | null | src/stats/StatisticalFormulas.cpp | IreneGR92/Group-augmentation-Basic | 9225c44e6608981d25b45e5575fd9922a358d1e0 | [
"MIT"
] | 1 | 2018-12-22T08:49:10.000Z | 2018-12-22T08:49:10.000Z |
#include "StatisticalFormulas.h"
#include <cmath>
#include <numeric>
#include <algorithm>
#include <functional>
#include <assert.h>
double StatisticalFormulas::calculateMean() {
double sum = std::accumulate(individualValues.begin(), individualValues.end(), 0.0);
double counter = individualValues.size();
if (counter > 0) {
return sum / counter;
} else {
return 0; //TODO: or -1?
}
}
double StatisticalFormulas::calculateSD() {
double mean = this->calculateMean();
double stdev;
std::vector<double> diff(size());
std::transform(individualValues.begin(), individualValues.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
if (individualValues.size() > 0) {
stdev = std::sqrt(sq_sum / individualValues.size());
} else {
stdev = 0;
}
return stdev;
}
///Alternative implementation for SD, not so efficient
//double StatisticalFormulas::calculateStandardDeviation() {
//
// double mean = calculateMean();
// double value = 0;
//
// for (double attribute : individualValues) {
// value += pow(attribute - mean, 2);
// }
//
// return sqrt(value / individualValues.size());;
//}
double StatisticalFormulas::correlation(StatisticalFormulas y) {
double meanX = this->calculateMean();
double meanY = y.calculateMean();
double SD_X = this->calculateSD();
double SD_Y = y.calculateSD();
double Xi, Yi, X, Y;
double sumProductXY = 0.0;
double counter = this->size();
assert(size() == y.size());
double correlation;
for (int i = 0; i < counter; i++) {
Xi = this->getValues().at(i);
Yi = y.getValues().at(i);
X = (Xi - meanX);
Y = (Yi - meanY);
sumProductXY += X * Y;
}
if (SD_X * SD_Y * counter == 0) {
correlation = 0;
} else {
correlation = sumProductXY / (SD_X * SD_Y * counter);
}
assert(abs(correlation) <= 1 && "[ERROR] correlation out of range");
return correlation;
}
int StatisticalFormulas::getMaxValue() {
int max = *max_element(individualValues.begin(), individualValues.end());
return max;
}
void StatisticalFormulas::addValue(double toAdd) {
this->individualValues.push_back(toAdd);
}
void StatisticalFormulas::merge(const StatisticalFormulas statisticalFormulas) {
this->individualValues.insert(individualValues.end(), statisticalFormulas.getValues().begin(),
statisticalFormulas.getValues().end());
}
int StatisticalFormulas::size() {
return this->individualValues.size();
}
void StatisticalFormulas::addValues(const std::vector<double> &values) {
for (double value: values) {
this->addValue(value);
}
}
std::vector<double> StatisticalFormulas::getValues() const {
return this->individualValues;
}
| 25.807018 | 98 | 0.632223 | [
"vector",
"transform"
] |
debeaebd1cf8c98380e16e19e1ae43cb797cb0d8 | 1,884 | cpp | C++ | Amazon_group.cpp | sayantabonny/ElementsOfProgramming | 74c1c34eb856fc7e9d6c1c7e13829c1e48f8f881 | [
"MIT"
] | null | null | null | Amazon_group.cpp | sayantabonny/ElementsOfProgramming | 74c1c34eb856fc7e9d6c1c7e13829c1e48f8f881 | [
"MIT"
] | null | null | null | Amazon_group.cpp | sayantabonny/ElementsOfProgramming | 74c1c34eb856fc7e9d6c1c7e13829c1e48f8f881 | [
"MIT"
] | null | null | null | #include<iostream>
#include<set>
#include<vector>
using namespace std;
int main()
{
int m[4][4] = {{1,0,0,1},{0,1,1,0},{0,1,1,1},{1,0,1,1}};
int group=0;
vector<set<int>> groups {{1,1}};
//cout<<groups.size()<<endl;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(m[i][j]==1)
{
int flag=1;
for(int k=0;k<groups.size();k++)
{
cout<<" row "<<i<<" column "<<j<<endl;
auto it2 = groups[k].find(i+1);
auto it1 = groups[k].find(j+1);
if(it1 == groups[k].end())
{
cout<<" NOT FOUND "<<j+1<<" at "<<k<<endl;
}
if(it2 == groups[k].end())
{
cout<<" NOT FOUND "<<i+1<<" at "<<k<<endl;
}
if ( it1 != groups[k].end() || it2 != groups[k].end()) {
groups[k].insert(i+1);
groups[k].insert(j+1);
flag=-1;
}
}
if(flag==1)
{
set<int> temp {i+1,j+1} ;
groups.push_back(temp);
}
}
}
}
set<int>::iterator itr;
for(int k1=0;k1<groups.size();k1++)
{
cout<<"SET "<<k1+1<<endl;
for (itr = groups[k1].begin(); itr != groups[k1].end(); itr++)
{
cout <<*itr<<" ";
}
cout<<endl;
}
cout<<groups.size()<<endl;
} | 28.545455 | 86 | 0.288747 | [
"vector"
] |
dec0d6bf2cab3f537f84e31c8a1402bdae9ab0e9 | 137,426 | cpp | C++ | Dots/geometries/david.cpp | xjorma/HoloGrail | 678db2a5f98261b0d8d6c3cdaffe481a42802845 | [
"MIT"
] | 6 | 2021-04-05T05:57:59.000Z | 2022-02-20T00:14:15.000Z | Dots/geometries/david.cpp | xjorma/HoloGrail | 678db2a5f98261b0d8d6c3cdaffe481a42802845 | [
"MIT"
] | null | null | null | Dots/geometries/david.cpp | xjorma/HoloGrail | 678db2a5f98261b0d8d6c3cdaffe481a42802845 | [
"MIT"
] | null | null | null | #include "demopch.h"
#include "./headers/geometries.h"
Geometry David = Geometry
(
{
{0.195080563426, 0.0789999961853, 0.202600091696}, {0.195080563426, 0.121000006795, 0.202600091696}, {0.14423827827, 0.0789999961853, 0.0792968720198}, {0.14423827827, 0.121000006795, 0.0792968720198}, {0.093737795949, 0.0789999961853, 0.202600091696}, {0.093737795949, 0.121000006795, 0.202600091696}, {0.133898928761, 0.0789999961853, 0.202600091696}, {0.133898928761, 0.121000006795, 0.202600091696},
{0.144580081105, 0.0789999961853, 0.166198730469}, {0.144580081105, 0.121000006795, 0.166198730469}, {0.156372070312, 0.0789999961853, 0.202600091696}, {0.156372070312, 0.121000006795, 0.202600091696}, {0.232250973582, 0.0789999961853, 0.171154782176}, {0.232250973582, 0.121000006795, 0.171154782176}, {0.232250973582, 0.0789999961853, 0.0859619155526}, {0.232250973582, 0.121000006795, 0.0859619155526},
{0.20029297471, 0.0789999961853, 0.0859619155526}, {0.20029297471, 0.121000006795, 0.0859619155526}, {0.20029297471, 0.0789999961853, 0.171154782176}, {0.20029297471, 0.121000006795, 0.171154782176}, {0.544311523438, 0.0789999961853, 0.202600091696}, {0.544311523438, 0.121000006795, 0.202600091696}, {0.544311523438, 0.0789999961853, 0.0859619155526}, {0.544311523438, 0.121000006795, 0.0859619155526},
{0.512353539467, 0.0789999961853, 0.0859619155526}, {0.512353539467, 0.121000006795, 0.0859619155526}, {0.512353539467, 0.0789999961853, 0.202600091696}, {0.512353539467, 0.121000006795, 0.202600091696}, {-0.684405505657, -0.121000006795, -0.0844238251448}, {-0.684405505657, -0.0789999961853, -0.0844238251448}, {-0.724224865437, -0.121000006795, -0.17294922471}, {-0.724224865437, -0.0789999961853, -0.17294922471},
{-0.763531506062, -0.121000006795, -0.0844238251448}, {-0.763531506062, -0.0789999961853, -0.0844238251448}, {-0.733026146889, -0.121000006795, -0.0844238251448}, {-0.733026146889, -0.0789999961853, -0.0844238251448}, {-0.723968505859, -0.121000006795, -0.107409670949}, {-0.723968505859, -0.0789999961853, -0.107409670949}, {-0.714056372643, -0.121000006795, -0.0844238251448}, {-0.714056372643, -0.0789999961853, -0.0844238251448},
{-0.649029552937, -0.121000006795, -0.0844238251448}, {-0.649029552937, -0.0789999961853, -0.0844238251448}, {-0.649029552937, -0.121000006795, -0.169616699219}, {-0.649029552937, -0.0789999961853, -0.169616699219}, {-0.680987536907, -0.121000006795, -0.169616699219}, {-0.680987536907, -0.0789999961853, -0.169616699219}, {-0.680987536907, -0.121000006795, -0.0844238251448}, {-0.680987536907, -0.0789999961853, -0.0844238251448},
{-0.460357666016, -0.121000006795, -0.0997192412615}, {-0.460357666016, -0.0789999961853, -0.0997192412615}, {-0.47650757432, -0.121000006795, -0.0997192412615}, {-0.47650757432, -0.0789999961853, -0.0997192412615}, {-0.483001708984, -0.121000006795, -0.052978515625}, {-0.483001708984, -0.0789999961853, -0.052978515625}, {-0.453692615032, -0.121000006795, -0.052978515625}, {-0.453692615032, -0.0789999961853, -0.052978515625},
{-0.425152599812, -0.121000006795, -0.0997192412615}, {-0.425152599812, -0.0789999961853, -0.0997192412615}, {-0.441302478313, -0.121000006795, -0.0997192412615}, {-0.441302478313, -0.0789999961853, -0.0997192412615}, {-0.44779664278, -0.121000006795, -0.052978515625}, {-0.44779664278, -0.0789999961853, -0.052978515625}, {-0.418487548828, -0.121000006795, -0.052978515625}, {-0.418487548828, -0.0789999961853, -0.052978515625},
{0.0930969268084, -0.121000006795, -0.106555178761}, {0.0930969268084, -0.0789999961853, -0.106555178761}, {0.0930969268084, -0.121000006795, -0.12919922173}, {0.0930969268084, -0.0789999961853, -0.12919922173}, {0.0540466308594, -0.121000006795, -0.12919922173}, {0.0540466308594, -0.0789999961853, -0.12919922173}, {0.0540466308594, -0.121000006795, -0.106555178761}, {0.0540466308594, -0.0789999961853, -0.106555178761},
{0.185125738382, -0.121000006795, -0.052978515625}, {0.185125738382, -0.0789999961853, -0.052978515625}, {0.154791265726, -0.121000006795, -0.109716795385}, {0.154791265726, -0.0789999961853, -0.109716795385}, {0.186151117086, -0.121000006795, -0.169616699219}, {0.186151117086, -0.0789999961853, -0.169616699219}, {0.149664312601, -0.121000006795, -0.169616699219}, {0.149664312601, -0.0789999961853, -0.169616699219},
{0.13530883193, -0.121000006795, -0.141333013773}, {0.13530883193, -0.0789999961853, -0.141333013773}, {0.123175047338, -0.121000006795, -0.169616699219}, {0.123175047338, -0.0789999961853, -0.169616699219}, {0.087286375463, -0.121000006795, -0.169616699219}, {0.087286375463, -0.0789999961853, -0.169616699219}, {0.119329832494, -0.121000006795, -0.110656738281}, {0.119329832494, -0.0789999961853, -0.110656738281},
{0.088995359838, -0.121000006795, -0.052978515625}, {0.088995359838, -0.0789999961853, -0.052978515625}, {0.12514038384, -0.121000006795, -0.052978515625}, {0.12514038384, -0.0789999961853, -0.052978515625}, {0.13872680068, -0.121000006795, -0.0794677734375}, {0.13872680068, -0.0789999961853, -0.0794677734375}, {0.149664312601, -0.121000006795, -0.052978515625}, {0.149664312601, -0.0789999961853, -0.052978515625},
{0.214434817433, -0.121000006795, -0.0997192412615}, {0.214434817433, -0.0789999961853, -0.0997192412615}, {0.198284909129, -0.121000006795, -0.0997192412615}, {0.198284909129, -0.0789999961853, -0.0997192412615}, {0.191790774465, -0.121000006795, -0.052978515625}, {0.191790774465, -0.0789999961853, -0.052978515625}, {0.221099853516, -0.121000006795, -0.052978515625}, {0.221099853516, -0.0789999961853, -0.052978515625},
{0.249639898539, -0.121000006795, -0.0997192412615}, {0.249639898539, -0.0789999961853, -0.0997192412615}, {0.233489990234, -0.121000006795, -0.0997192412615}, {0.233489990234, -0.0789999961853, -0.0997192412615}, {0.22699585557, -0.121000006795, -0.052978515625}, {0.22699585557, -0.0789999961853, -0.052978515625}, {0.25630491972, -0.121000006795, -0.052978515625}, {0.25630491972, -0.0789999961853, -0.052978515625},
{0.562896728516, -0.121000006795, -0.052978515625}, {0.562896728516, -0.0789999961853, -0.052978515625}, {0.562896728516, -0.121000006795, -0.169616699219}, {0.562896728516, -0.0789999961853, -0.169616699219}, {0.530938744545, -0.121000006795, -0.169616699219}, {0.530938744545, -0.0789999961853, -0.169616699219}, {0.530938744545, -0.121000006795, -0.052978515625}, {0.530938744545, -0.0789999961853, -0.052978515625},
{0.613568127155, -0.121000006795, -0.052978515625}, {0.613568127155, -0.0789999961853, -0.052978515625}, {0.613568127155, -0.121000006795, -0.169616699219}, {0.613568127155, -0.0789999961853, -0.169616699219}, {0.58161008358, -0.121000006795, -0.169616699219}, {0.58161008358, -0.0789999961853, -0.169616699219}, {0.58161008358, -0.121000006795, -0.052978515625}, {0.58161008358, -0.0789999961853, -0.052978515625},
{-0.458349615335, 0.0789999961853, 0.142956539989}, {-0.458349615335, 0.121000006795, 0.142956539989}, {-0.422033697367, 0.0789999961853, 0.142016604543}, {-0.422033697367, 0.121000006795, 0.142016604543}, {-0.42434990406, 0.0789999961853, 0.129684627056}, {-0.42434990406, 0.121000006795, 0.129684627056}, {-0.429491013288, 0.0789999961853, 0.115365579724}, {-0.429491013288, 0.121000006795, 0.115365579724},
{-0.434886455536, 0.0789999961853, 0.106218986213}, {-0.434886455536, 0.121000006795, 0.106218986213}, {-0.439216583967, 0.0789999961853, 0.100879661739}, {-0.439216583967, 0.121000006795, 0.100879661739}, {-0.444104373455, 0.0789999961853, 0.0961622297764}, {-0.444104373455, 0.121000006795, 0.0961622297764}, {-0.449455857277, 0.0789999961853, 0.0921577364206}, {-0.449455857277, 0.121000006795, 0.0921577364206},
{-0.455268442631, 0.0789999961853, 0.0888813436031}, {-0.455268442631, 0.121000006795, 0.0888813436031}, {-0.464851915836, 0.0789999961853, 0.0853319093585}, {-0.464851915836, 0.121000006795, 0.0853319093585}, {-0.471817344427, 0.0789999961853, 0.0838757380843}, {-0.471817344427, 0.121000006795, 0.0838757380843}, {-0.47924387455, 0.0789999961853, 0.0831476449966}, {-0.47924387455, 0.121000006795, 0.0831476449966},
{-0.49094876647, 0.0789999961853, 0.0834692195058}, {-0.49094876647, 0.121000006795, 0.0834692195058}, {-0.498367160559, 0.0789999961853, 0.0847069695592}, {-0.498367160559, 0.121000006795, 0.0847069695592}, {-0.505385100842, 0.0789999961853, 0.0867698863149}, {-0.505385100842, 0.121000006795, 0.0867698863149}, {-0.512002646923, 0.0789999961853, 0.0896579697728}, {-0.512002646923, 0.121000006795, 0.0896579697728},
{-0.518219649792, 0.0789999961853, 0.0933712124825}, {-0.518219649792, 0.121000006795, 0.0933712124825}, {-0.524036288261, 0.0789999961853, 0.0979096293449}, {-0.524036288261, 0.121000006795, 0.0979096293449}, {-0.529385745525, 0.0789999961853, 0.103232771158}, {-0.529385745525, 0.121000006795, 0.103232771158}, {-0.53394639492, 0.0789999961853, 0.109019048512}, {-0.53394639492, 0.121000006795, 0.109019048512},
{-0.539232611656, 0.0789999961853, 0.118441723287}, {-0.539232611656, 0.121000006795, 0.118441723287}, {-0.542653083801, 0.0789999961853, 0.128756299615}, {-0.542653083801, 0.121000006795, 0.128756299615}, {-0.543896913528, 0.0789999961853, 0.136128202081}, {-0.543896913528, 0.121000006795, 0.136128202081}, {-0.544311523438, 0.0789999961853, 0.143896490335}, {-0.544311523438, 0.121000006795, 0.143896490335},
{-0.543888807297, 0.0789999961853, 0.151719391346}, {-0.543888807297, 0.121000006795, 0.151719391346}, {-0.542620718479, 0.0789999961853, 0.15914991498}, {-0.542620718479, 0.121000006795, 0.15914991498}, {-0.539133489132, 0.0789999961853, 0.169560074806}, {-0.539133489132, 0.121000006795, 0.169560074806}, {-0.53575193882, 0.0789999961853, 0.176009699702}, {-0.53575193882, 0.121000006795, 0.176009699702},
{-0.531524956226, 0.0789999961853, 0.182067006826}, {-0.531524956226, 0.121000006795, 0.182067006826}, {-0.526452660561, 0.0789999961853, 0.187731936574}, {-0.526452660561, 0.121000006795, 0.187731936574}, {-0.520735085011, 0.0789999961853, 0.192780032754}, {-0.520735085011, 0.121000006795, 0.192780032754}, {-0.514625191689, 0.0789999961853, 0.196986734867}, {-0.514625191689, 0.121000006795, 0.196986734867},
{-0.504724800587, 0.0789999961853, 0.201719298959}, {-0.504724800587, 0.121000006795, 0.201719298959}, {-0.497634023428, 0.0789999961853, 0.203822672367}, {-0.497634023428, 0.121000006795, 0.203822672367}, {-0.490150898695, 0.0789999961853, 0.205084696412}, {-0.490150898695, 0.121000006795, 0.205084696412}, {-0.478355884552, 0.0789999961853, 0.205402225256}, {-0.478355884552, 0.121000006795, 0.205402225256},
{-0.47082015872, 0.0789999961853, 0.204577073455}, {-0.47082015872, 0.121000006795, 0.204577073455}, {-0.460275024176, 0.0789999961853, 0.201792135835}, {-0.460275024176, 0.121000006795, 0.201792135835}, {-0.453750550747, 0.0789999961853, 0.198904052377}, {-0.453750550747, 0.121000006795, 0.198904052377}, {-0.44763058424, 0.0789999961853, 0.195190802217}, {-0.44763058424, 0.121000006795, 0.195190802217},
{-0.44191506505, 0.0789999961853, 0.190652400255}, {-0.44191506505, 0.121000006795, 0.190652400255}, {-0.435693919659, 0.0789999961853, 0.184142068028}, {-0.435693919659, 0.121000006795, 0.184142068028}, {-0.43251055479, 0.0789999961853, 0.179761394858}, {-0.43251055479, 0.121000006795, 0.179761394858}, {-0.428357422352, 0.0789999961853, 0.172348558903}, {-0.428357422352, 0.121000006795, 0.172348558903},
{-0.426003277302, 0.0789999961853, 0.166845440865}, {-0.426003277302, 0.121000006795, 0.166845440865}, {-0.422290027142, 0.0789999961853, 0.15449218452}, {-0.422290027142, 0.121000006795, 0.15449218452}, {-0.459460437298, 0.0789999961853, 0.152014166117}, {-0.459460437298, 0.121000006795, 0.152014166117}, {-0.4629355371, 0.0789999961853, 0.159828975797}, {-0.4629355371, 0.121000006795, 0.159828975797},
{-0.467602849007, 0.0789999961853, 0.165605157614}, {-0.467602849007, 0.121000006795, 0.165605157614}, {-0.475680589676, 0.0789999961853, 0.170135468245}, {-0.475680589676, 0.121000006795, 0.170135468245}, {-0.480514258146, 0.0789999961853, 0.171041533351}, {-0.480514258146, 0.121000006795, 0.171041533351}, {-0.486456871033, 0.0789999961853, 0.170972749591}, {-0.486456871033, 0.121000006795, 0.170972749591},
{-0.491106003523, 0.0789999961853, 0.170017138124}, {-0.491106003523, 0.121000006795, 0.170017138124}, {-0.497944444418, 0.0789999961853, 0.166604250669}, {-0.497944444418, 0.121000006795, 0.166604250669}, {-0.501501441002, 0.0789999961853, 0.163464352489}, {-0.501501441002, 0.121000006795, 0.163464352489}, {-0.505239009857, 0.0789999961853, 0.158335387707}, {-0.505239009857, 0.121000006795, 0.158335387707},
{-0.508296966553, 0.0789999961853, 0.149155423045}, {-0.508296966553, 0.121000006795, 0.149155423045}, {-0.508301496506, 0.0789999961853, 0.138821110129}, {-0.508301496506, 0.121000006795, 0.138821110129}, {-0.507168471813, 0.0789999961853, 0.134164378047}, {-0.507168471813, 0.121000006795, 0.134164378047}, {-0.503601312637, 0.0789999961853, 0.127333506942}, {-0.503601312637, 0.121000006795, 0.127333506942},
{-0.498113334179, 0.0789999961853, 0.121891543269}, {-0.498113334179, 0.121000006795, 0.121891543269}, {-0.494239270687, 0.0789999961853, 0.119648113847}, {-0.494239270687, 0.121000006795, 0.119648113847}, {-0.485289871693, 0.0789999961853, 0.117536664009}, {-0.485289871693, 0.121000006795, 0.117536664009}, {-0.477287948132, 0.0789999961853, 0.118115589023}, {-0.477287948132, 0.121000006795, 0.118115589023},
{-0.471790909767, 0.0789999961853, 0.119984343648}, {-0.471790909767, 0.121000006795, 0.119984343648}, {-0.465145140886, 0.0789999961853, 0.125118389726}, {-0.465145140886, 0.121000006795, 0.125118389726}, {-0.461860567331, 0.0789999961853, 0.129980400205}, {-0.461860567331, 0.121000006795, 0.129980400205}, {-0.460066139698, 0.0789999961853, 0.1343383044}, {-0.460066139698, 0.121000006795, 0.1343383044},
{-0.364846438169, 0.0789999961853, 0.172871857882}, {-0.364846438169, 0.121000006795, 0.172871857882}, {-0.356948167086, 0.0789999961853, 0.171711474657}, {-0.356948167086, 0.121000006795, 0.171711474657}, {-0.34728077054, 0.0789999961853, 0.167998224497}, {-0.34728077054, 0.121000006795, 0.167998224497}, {-0.338600367308, 0.0789999961853, 0.16180947423}, {-0.338600367308, 0.121000006795, 0.16180947423},
{-0.33128157258, 0.0789999961853, 0.153603315353}, {-0.33128157258, 0.121000006795, 0.153603315353}, {-0.326362907887, 0.0789999961853, 0.144376814365}, {-0.326362907887, 0.121000006795, 0.144376814365}, {-0.323903590441, 0.0789999961853, 0.134163364768}, {-0.323903590441, 0.121000006795, 0.134163364768}, {-0.323674023151, 0.0789999961853, 0.125879347324}, {-0.323674023151, 0.121000006795, 0.125879347324},
{-0.324296951294, 0.0789999961853, 0.120459124446}, {-0.324296951294, 0.121000006795, 0.120459124446}, {-0.326399296522, 0.0789999961853, 0.112814202905}, {-0.326399296522, 0.121000006795, 0.112814202905}, {-0.329903244972, 0.0789999961853, 0.105751752853}, {-0.329903244972, 0.121000006795, 0.105751752853}, {-0.33301782608, 0.0789999961853, 0.101367041469}, {-0.33301782608, 0.121000006795, 0.101367041469},
{-0.338799089193, 0.0789999961853, 0.0953198671341}, {-0.338799089193, 0.121000006795, 0.0953198671341}, {-0.34762108326, 0.0789999961853, 0.0891715660691}, {-0.34762108326, 0.121000006795, 0.0891715660691}, {-0.354917138815, 0.0789999961853, 0.0861742720008}, {-0.354917138815, 0.121000006795, 0.0861742720008}, {-0.365551292896, 0.0789999961853, 0.0843297839165}, {-0.365551292896, 0.121000006795, 0.0843297839165},
{-0.37394952774, 0.0789999961853, 0.0845603495836}, {-0.37394952774, 0.121000006795, 0.0845603495836}, {-0.379272669554, 0.0789999961853, 0.0854825899005}, {-0.379272669554, 0.121000006795, 0.0854825899005}, {-0.38677957654, 0.0789999961853, 0.0880187675357}, {-0.38677957654, 0.121000006795, 0.0880187675357}, {-0.393713116646, 0.0789999961853, 0.0919383093715}, {-0.393713116646, 0.121000006795, 0.0919383093715},
{-0.400073230267, 0.0789999961853, 0.0972412079573}, {-0.400073230267, 0.121000006795, 0.0972412079573}, {-0.40692538023, 0.0789999961853, 0.10578815639}, {-0.40692538023, 0.121000006795, 0.10578815639}, {-0.410429298878, 0.0789999961853, 0.112856678665}, {-0.410429298878, 0.121000006795, 0.112856678665}, {-0.412531644106, 0.0789999961853, 0.120489470661}, {-0.412531644106, 0.121000006795, 0.120489470661},
{-0.413154572248, 0.0789999961853, 0.131530120969}, {-0.413154572248, 0.121000006795, 0.131530120969}, {-0.412531644106, 0.0789999961853, 0.137004926801}, {-0.412531644106, 0.121000006795, 0.137004926801}, {-0.410429298878, 0.0789999961853, 0.144686251879}, {-0.410429298878, 0.121000006795, 0.144686251879}, {-0.40692538023, 0.0789999961853, 0.151730507612}, {-0.40692538023, 0.121000006795, 0.151730507612},
{-0.40381076932, 0.0789999961853, 0.156072750688}, {-0.40381076932, 0.121000006795, 0.156072750688}, {-0.398012369871, 0.0789999961853, 0.162027895451}, {-0.398012369871, 0.121000006795, 0.162027895451}, {-0.393672198057, 0.0789999961853, 0.165364965796}, {-0.393672198057, 0.121000006795, 0.165364965796}, {-0.386615723372, 0.0789999961853, 0.169232934713}, {-0.386615723372, 0.121000006795, 0.169232934713},
{-0.381547421217, 0.0789999961853, 0.171053141356}, {-0.381547421217, 0.121000006795, 0.171053141356}, {-0.37339887023, 0.0789999961853, 0.172645837069}, {-0.37339887023, 0.121000006795, 0.172645837069}, {-0.369998127222, 0.0789999961853, 0.141329467297}, {-0.369998127222, 0.121000006795, 0.141329467297}, {-0.374184638262, 0.0789999961853, 0.139994651079}, {-0.374184638262, 0.121000006795, 0.139994651079},
{-0.378192156553, 0.0789999961853, 0.136487677693}, {-0.378192156553, 0.121000006795, 0.136487677693}, {-0.380570590496, 0.0789999961853, 0.130994677544}, {-0.380570590496, 0.121000006795, 0.130994677544}, {-0.380570590496, 0.0789999961853, 0.126237824559}, {-0.380570590496, 0.121000006795, 0.126237824559}, {-0.378192156553, 0.0789999961853, 0.120736733079}, {-0.378192156553, 0.121000006795, 0.120736733079},
{-0.374144226313, 0.0789999961853, 0.117207504809}, {-0.374144226313, 0.121000006795, 0.117207504809}, {-0.370711088181, 0.0789999961853, 0.115983918309}, {-0.370711088181, 0.121000006795, 0.115983918309}, {-0.365447610617, 0.0789999961853, 0.116139642894}, {-0.365447610617, 0.121000006795, 0.116139642894}, {-0.362729430199, 0.0789999961853, 0.117207497358}, {-0.362729430199, 0.121000006795, 0.117207497358},
{-0.358241051435, 0.0789999961853, 0.121360637248}, {-0.358241051435, 0.121000006795, 0.121360637248}, {-0.356610447168, 0.0789999961853, 0.124753311276}, {-0.356610447168, 0.121000006795, 0.124753311276}, {-0.356258034706, 0.0789999961853, 0.130994662642}, {-0.356258034706, 0.121000006795, 0.130994662642}, {-0.358636528254, 0.0789999961853, 0.136487677693}, {-0.358636528254, 0.121000006795, 0.136487677693},
{-0.362656533718, 0.0789999961853, 0.139994636178}, {-0.362656533718, 0.121000006795, 0.139994636178}, {-0.369998127222, 0.0789999961853, 0.141329467297}, {-0.369998127222, 0.121000006795, 0.141329467297}, {-0.37339887023, 0.0789999961853, 0.172645837069}, {-0.37339887023, 0.121000006795, 0.172645837069}, {-0.257800281048, 0.0789999961853, 0.202600091696}, {-0.257800281048, 0.121000006795, 0.202600091696},
{-0.225842282176, 0.0789999961853, 0.202600091696}, {-0.225842282176, 0.121000006795, 0.202600091696}, {-0.225842282176, 0.0789999961853, 0.131591796875}, {-0.225842282176, 0.121000006795, 0.131591796875}, {-0.226813063025, 0.0789999961853, 0.120237663388}, {-0.226813063025, 0.121000006795, 0.120237663388}, {-0.229725405574, 0.0789999961853, 0.110258825123}, {-0.229725405574, 0.121000006795, 0.110258825123},
{-0.233183830976, 0.0789999961853, 0.103677205741}, {-0.233183830976, 0.121000006795, 0.103677205741}, {-0.237022489309, 0.0789999961853, 0.0986452996731}, {-0.237022489309, 0.121000006795, 0.0986452996731}, {-0.244582533836, 0.0789999961853, 0.0920904949307}, {-0.244582533836, 0.121000006795, 0.0920904949307}, {-0.25534299016, 0.0789999961853, 0.0867304503918}, {-0.25534299016, 0.121000006795, 0.0867304503918},
{-0.261038273573, 0.0789999961853, 0.0851448401809}, {-0.261038273573, 0.121000006795, 0.0851448401809}, {-0.268293857574, 0.0789999961853, 0.0842777043581}, {-0.268293857574, 0.121000006795, 0.0842777043581}, {-0.275484770536, 0.0789999961853, 0.0845562964678}, {-0.275484770536, 0.121000006795, 0.0845562964678}, {-0.28092315793, 0.0789999961853, 0.0854664072394}, {-0.28092315793, 0.121000006795, 0.0854664072394},
{-0.29095056653, 0.0789999961853, 0.0891068428755}, {-0.29095056653, 0.121000006795, 0.0891068428755}, {-0.299845337868, 0.0789999961853, 0.0951742380857}, {-0.299845337868, 0.121000006795, 0.0951742380857}, {-0.307229876518, 0.0789999961853, 0.103295460343}, {-0.307229876518, 0.121000006795, 0.103295460343}, {-0.311175227165, 0.0789999961853, 0.110139489174}, {-0.311175227165, 0.121000006795, 0.110139489174},
{-0.313728064299, 0.0789999961853, 0.117602393031}, {-0.313728064299, 0.121000006795, 0.117602393031}, {-0.314656376839, 0.0789999961853, 0.122921474278}, {-0.314656376839, 0.121000006795, 0.122921474278}, {-0.314888983965, 0.0789999961853, 0.131260618567}, {-0.314888983965, 0.121000006795, 0.131260618567}, {-0.31304448843, 0.0789999961853, 0.14166419208}, {-0.31304448843, 0.121000006795, 0.14166419208},
{-0.308740645647, 0.0789999961853, 0.151145502925}, {-0.308740645647, 0.121000006795, 0.151145502925}, {-0.303898841143, 0.0789999961853, 0.157651275396}, {-0.303898841143, 0.121000006795, 0.157651275396}, {-0.297867894173, 0.0789999961853, 0.163442105055}, {-0.297867894173, 0.121000006795, 0.163442105055}, {-0.288969039917, 0.0789999961853, 0.169048398733}, {-0.288969039917, 0.121000006795, 0.169048398733},
{-0.279164105654, 0.0789999961853, 0.172162979841}, {-0.279164105654, 0.121000006795, 0.172162979841}, {-0.273921847343, 0.0789999961853, 0.172785907984}, {-0.273921847343, 0.121000006795, 0.172785907984}, {-0.262670904398, 0.0789999961853, 0.172351077199}, {-0.262670904398, 0.121000006795, 0.172351077199}, {-0.262670904398, 0.0789999961853, 0.137145996094}, {-0.262670904398, 0.121000006795, 0.137145996094},
{-0.269322782755, 0.0789999961853, 0.140149369836}, {-0.269322782755, 0.121000006795, 0.140149369836}, {-0.274142324924, 0.0789999961853, 0.139678642154}, {-0.274142324924, 0.121000006795, 0.139678642154}, {-0.277347952127, 0.0789999961853, 0.138048022985}, {-0.277347952127, 0.121000006795, 0.138048022985}, {-0.281564801931, 0.0789999961853, 0.132907405496}, {-0.281564801931, 0.121000006795, 0.132907405496},
{-0.282394021749, 0.0789999961853, 0.130116388202}, {-0.282394021749, 0.121000006795, 0.130116388202}, {-0.28203701973, 0.0789999961853, 0.124221928418}, {-0.28203701973, 0.121000006795, 0.124221928418}, {-0.27890625596, 0.0789999961853, 0.119287110865}, {-0.27890625596, 0.121000006795, 0.119287110865}, {-0.272393882275, 0.0789999961853, 0.115970268846}, {-0.272393882275, 0.121000006795, 0.115970268846},
{-0.266610145569, 0.0789999961853, 0.11618616432}, {-0.266610145569, 0.121000006795, 0.11618616432}, {-0.262460052967, 0.0789999961853, 0.118299134076}, {-0.262460052967, 0.121000006795, 0.118299134076}, {-0.259620517492, 0.0789999961853, 0.122223228216}, {-0.259620517492, 0.121000006795, 0.122223228216}, {-0.25845554471, 0.0789999961853, 0.125845462084}, {-0.25845554471, 0.121000006795, 0.125845462084},
{-0.257800281048, 0.0789999961853, 0.132788091898}, {-0.257800281048, 0.121000006795, 0.132788091898}, {-0.125268548727, 0.0789999961853, 0.123388670385}, {-0.125268548727, 0.121000006795, 0.123388670385}, {-0.173718258739, 0.0789999961853, 0.123388670385}, {-0.173718258739, 0.121000006795, 0.123388670385}, {-0.174829095602, 0.0789999961853, 0.130139157176}, {-0.174829095602, 0.121000006795, 0.130139157176},
{-0.173291012645, 0.0789999961853, 0.138513177633}, {-0.173291012645, 0.121000006795, 0.138513177633}, {-0.157055661082, 0.0789999961853, 0.138513177633}, {-0.157055661082, 0.121000006795, 0.138513177633}, {-0.16018037498, 0.0789999961853, 0.145247995853}, {-0.16018037498, 0.121000006795, 0.145247995853}, {-0.165148049593, 0.0789999961853, 0.147773563862}, {-0.165148049593, 0.121000006795, 0.147773563862},
{-0.170379161835, 0.0789999961853, 0.14772503078}, {-0.170379161835, 0.121000006795, 0.14772503078}, {-0.174257263541, 0.0789999961853, 0.146056488156}, {-0.174257263541, 0.121000006795, 0.146056488156}, {-0.179013088346, 0.0789999961853, 0.140389531851}, {-0.179013088346, 0.121000006795, 0.140389531851}, {-0.180681616068, 0.0789999961853, 0.135565951467}, {-0.180681616068, 0.121000006795, 0.135565951467},
{-0.181046664715, 0.0789999961853, 0.126225695014}, {-0.181046664715, 0.121000006795, 0.126225695014}, {-0.179517701268, 0.0789999961853, 0.119921676815}, {-0.179517701268, 0.121000006795, 0.119921676815}, {-0.177648931742, 0.0789999961853, 0.116467282176}, {-0.177648931742, 0.121000006795, 0.116467282176}, {-0.17449387908, 0.0789999961853, 0.113281898201}, {-0.17449387908, 0.121000006795, 0.113281898201},
{-0.169840186834, 0.0789999961853, 0.111461684108}, {-0.169840186834, 0.121000006795, 0.111461684108}, {-0.165166258812, 0.0789999961853, 0.111793383956}, {-0.165166258812, 0.121000006795, 0.111793383956}, {-0.158850103617, 0.0789999961853, 0.116125486791}, {-0.158850103617, 0.121000006795, 0.116125486791}, {-0.140649408102, 0.0789999961853, 0.094250485301}, {-0.140649408102, 0.121000006795, 0.094250485301},
{-0.150860324502, 0.0789999961853, 0.0880389809608}, {-0.150860324502, 0.121000006795, 0.0880389809608}, {-0.159629762173, 0.0789999961853, 0.0851994454861}, {-0.159629762173, 0.121000006795, 0.0851994454861}, {-0.168933108449, 0.0789999961853, 0.0842529311776}, {-0.168933108449, 0.121000006795, 0.0842529311776}, {-0.180032387376, 0.0789999961853, 0.0854583159089}, {-0.180032387376, 0.121000006795, 0.0854583159089},
{-0.189982920885, 0.0789999961853, 0.0890744850039}, {-0.189982920885, 0.121000006795, 0.0890744850039}, {-0.198784694076, 0.0789999961853, 0.0951014310122}, {-0.198784694076, 0.121000006795, 0.0951014310122}, {-0.20447036624, 0.0789999961853, 0.101045973599}, {-0.20447036624, 0.121000006795, 0.101045973599}, {-0.209967434406, 0.0789999961853, 0.110029764473}, {-0.209967434406, 0.121000006795, 0.110029764473},
{-0.213021382689, 0.0789999961853, 0.120162315667}, {-0.213021382689, 0.121000006795, 0.120162315667}, {-0.213631644845, 0.0789999961853, 0.131360217929}, {-0.213631644845, 0.121000006795, 0.131360217929}, {-0.211787134409, 0.0789999961853, 0.142050981522}, {-0.211787134409, 0.121000006795, 0.142050981522}, {-0.208789825439, 0.0789999961853, 0.149347022176}, {-0.208789825439, 0.121000006795, 0.149347022176},
{-0.206023067236, 0.0789999961853, 0.15386724472}, {-0.206023067236, 0.121000006795, 0.15386724472}, {-0.200720220804, 0.0789999961853, 0.160131841898}, {-0.200720220804, 0.121000006795, 0.160131841898}, {-0.196557983756, 0.0789999961853, 0.163796544075}, {-0.196557983756, 0.121000006795, 0.163796544075}, {-0.189791321754, 0.0789999961853, 0.168148398399}, {-0.189791321754, 0.121000006795, 0.168148398399},
{-0.182396695018, 0.0789999961853, 0.171125948429}, {-0.182396695018, 0.121000006795, 0.171125948429}, {-0.177118062973, 0.0789999961853, 0.172347515821}, {-0.177118062973, 0.121000006795, 0.172347515821}, {-0.168676763773, 0.0789999961853, 0.173034667969}, {-0.168676763773, 0.121000006795, 0.173034667969}, {-0.157832279801, 0.0789999961853, 0.171837374568}, {-0.157832279801, 0.121000006795, 0.171837374568},
{-0.15044221282, 0.0789999961853, 0.169367939234}, {-0.15044221282, 0.121000006795, 0.169367939234}, {-0.145869404078, 0.0789999961853, 0.166973352432}, {-0.145869404078, 0.121000006795, 0.166973352432}, {-0.139541104436, 0.0789999961853, 0.162258982658}, {-0.139541104436, 0.121000006795, 0.162258982658}, {-0.133981361985, 0.0789999961853, 0.156383708119}, {-0.133981361985, 0.121000006795, 0.156383708119},
{-0.128593504429, 0.0789999961853, 0.147537440062}, {-0.128593504429, 0.121000006795, 0.147537440062}, {-0.126124054193, 0.0789999961853, 0.140170112252}, {-0.126124054193, 0.121000006795, 0.140170112252}, {-0.124926760793, 0.0789999961853, 0.129370123148}, {-0.124926760793, 0.121000006795, 0.129370123148}, {0.00196533207782, 0.0789999961853, 0.13603515923}, {0.00196533207782, 0.121000006795, 0.13603515923},
{-0.0201068557799, 0.0789999961853, 0.120489992201}, {-0.0201068557799, 0.121000006795, 0.120489992201}, {-0.0257202144712, 0.0789999961853, 0.128173828125}, {-0.0257202144712, 0.121000006795, 0.128173828125}, {-0.0295108240098, 0.0789999961853, 0.123423054814}, {-0.0295108240098, 0.121000006795, 0.123423054814}, {-0.0296726189554, 0.0789999961853, 0.118690475821}, {-0.0296726189554, 0.121000006795, 0.118690475821},
{-0.0270282439888, 0.0789999961853, 0.113926559687}, {-0.0270282439888, 0.121000006795, 0.113926559687}, {-0.0233473554254, 0.0789999961853, 0.1118555516}, {-0.0233473554254, 0.121000006795, 0.1118555516}, {-0.0181228201836, 0.0789999961853, 0.112265601754}, {-0.0181228201836, 0.121000006795, 0.112265601754}, {-0.0152954105288, 0.0789999961853, 0.113903805614}, {-0.0152954105288, 0.121000006795, 0.113903805614},
{-0.0201068557799, 0.0789999961853, 0.120489992201}, {-0.0201068557799, 0.121000006795, 0.120489992201}, {0.00196533207782, 0.0789999961853, 0.13603515923}, {0.00196533207782, 0.121000006795, 0.13603515923}, {0.0236694328487, 0.0789999961853, 0.13603515923}, {0.0236694328487, 0.121000006795, 0.13603515923}, {0.02389190346, 0.0789999961853, 0.127242475748}, {0.02389190346, 0.121000006795, 0.127242475748},
{0.0232654456049, 0.0789999961853, 0.122619122267}, {0.0232654456049, 0.121000006795, 0.122619122267}, {0.0210280939937, 0.0789999961853, 0.115196660161}, {0.0210280939937, 0.121000006795, 0.115196660161}, {0.0189697258174, 0.0789999961853, 0.110913082957}, {0.0189697258174, 0.121000006795, 0.110913082957}, {0.0353759750724, 0.0789999961853, 0.0859619155526}, {0.0353759750724, 0.121000006795, 0.0859619155526},
{0.00495605450124, 0.0789999961853, 0.0859619155526}, {0.00495605450124, 0.121000006795, 0.0859619155526}, {0.00153808598407, 0.0789999961853, 0.0900634750724}, {0.00153808598407, 0.121000006795, 0.0900634750724}, {-0.00155831128359, 0.0789999961853, 0.0880733579397}, {-0.00155831128359, 0.121000006795, 0.0880733579397}, {-0.0110901985317, 0.0789999961853, 0.0840931460261}, {-0.0110901985317, 0.121000006795, 0.0840931460261},
{-0.0176470391452, 0.0789999961853, 0.0830980986357}, {-0.0176470391452, 0.121000006795, 0.0830980986357}, {-0.0263224039227, 0.0789999961853, 0.0836345553398}, {-0.0263224039227, 0.121000006795, 0.0836345553398}, {-0.0349057540298, 0.0789999961853, 0.0862030908465}, {-0.0349057540298, 0.121000006795, 0.0862030908465}, {-0.0444062910974, 0.0789999961853, 0.092303365469}, {-0.0444062910974, 0.121000006795, 0.092303365469},
{-0.0506430752575, 0.0789999961853, 0.0991979464889}, {-0.0506430752575, 0.121000006795, 0.0991979464889}, {-0.0548174418509, 0.0789999961853, 0.107000619173}, {-0.0548174418509, 0.121000006795, 0.107000619173}, {-0.0569046288729, 0.0789999961853, 0.115660823882}, {-0.0569046288729, 0.121000006795, 0.115660823882}, {-0.0568055212498, 0.0789999961853, 0.125583052635}, {-0.0568055212498, 0.121000006795, 0.125583052635},
{-0.0539255253971, 0.0789999961853, 0.135408177972}, {-0.0539255253971, 0.121000006795, 0.135408177972}, {-0.0498755313456, 0.0789999961853, 0.142150580883}, {-0.0498755313456, 0.121000006795, 0.142150580883}, {-0.0419555678964, 0.0789999961853, 0.150305181742}, {-0.0419555678964, 0.121000006795, 0.150305181742}, {-0.0470521822572, 0.0789999961853, 0.158412739635}, {-0.0470521822572, 0.121000006795, 0.158412739635},
{-0.0489452108741, 0.0789999961853, 0.16336221993}, {-0.0489452108741, 0.121000006795, 0.16336221993}, {-0.0501101501286, 0.0789999961853, 0.170060619712}, {-0.0501101501286, 0.121000006795, 0.170060619712}, {-0.0496399253607, 0.0789999961853, 0.177967458963}, {-0.0496399253607, 0.121000006795, 0.177967458963}, {-0.0487176887691, 0.0789999961853, 0.181872844696}, {-0.0487176887691, 0.121000006795, 0.181872844696},
{-0.0454898253083, 0.0789999961853, 0.189113274217}, {-0.0454898253083, 0.121000006795, 0.189113274217}, {-0.0404174812138, 0.0789999961853, 0.195593267679}, {-0.0404174812138, 0.121000006795, 0.195593267679}, {-0.035672776401, 0.0789999961853, 0.199640214443}, {-0.035672776401, 0.121000006795, 0.199640214443}, {-0.0286952685565, 0.0789999961853, 0.203393921256}, {-0.0286952685565, 0.121000006795, 0.203393921256},
{-0.0229737106711, 0.0789999961853, 0.20497751236}, {-0.0229737106711, 0.121000006795, 0.20497751236}, {-0.0127420471981, 0.0789999961853, 0.20527882874}, {-0.0127420471981, 0.121000006795, 0.20527882874}, {-0.00509307999164, 0.0789999961853, 0.203466668725}, {-0.00509307999164, 0.121000006795, 0.203466668725}, {0.00184397795238, 0.0789999961853, 0.199842378497}, {0.00184397795238, 0.121000006795, 0.199842378497},
{0.00504554156214, 0.0789999961853, 0.197350680828}, {0.00504554156214, 0.121000006795, 0.197350680828}, {0.0105916569009, 0.0789999961853, 0.191326871514}, {0.0105916569009, 0.121000006795, 0.191326871514}, {0.0135570988059, 0.0789999961853, 0.186336442828}, {0.0135570988059, 0.121000006795, 0.186336442828}, {0.0161736682057, 0.0789999961853, 0.17716960609}, {0.0161736682057, 0.121000006795, 0.17716960609},
{0.0162353515625, 0.0789999961853, 0.168762207031}, {0.0162353515625, 0.121000006795, 0.168762207031}, {-0.0101684574038, 0.0789999961853, 0.168762207031}, {-0.0101684574038, 0.121000006795, 0.168762207031}, {-0.0113895200193, 0.0789999961853, 0.174177363515}, {-0.0113895200193, 0.121000006795, 0.174177363515}, {-0.0133674927056, 0.0789999961853, 0.176652878523}, {-0.0133674927056, 0.121000006795, 0.176652878523},
{-0.0162353515625, 0.0789999961853, 0.177478030324}, {-0.0162353515625, 0.121000006795, 0.177478030324}, {-0.02053107135, 0.0789999961853, 0.175633519888}, {-0.02053107135, 0.121000006795, 0.175633519888}, {-0.0212768558413, 0.0789999961853, 0.172607421875}, {-0.0212768558413, 0.121000006795, 0.172607421875}, {-0.0198242180049, 0.0789999961853, 0.168762207031}, {-0.0198242180049, 0.121000006795, 0.168762207031},
{0.217345908284, 0.0789999961853, 0.209152385592}, {0.217345908284, 0.121000006795, 0.209152385592}, {0.222830846906, 0.0789999961853, 0.207841843367}, {0.222830846906, 0.121000006795, 0.207841843367}, {0.22681760788, 0.0789999961853, 0.20524802804}, {0.22681760788, 0.121000006795, 0.20524802804}, {0.230949014425, 0.0789999961853, 0.200020954013}, {0.230949014425, 0.121000006795, 0.200020954013},
{0.232309624553, 0.0789999961853, 0.192787587643}, {0.232309624553, 0.121000006795, 0.192787587643}, {0.231023311615, 0.0789999961853, 0.187314778566}, {0.231023311615, 0.121000006795, 0.187314778566}, {0.229093894362, 0.0789999961853, 0.184232547879}, {0.229093894362, 0.121000006795, 0.184232547879}, {0.224830567837, 0.0789999961853, 0.180636614561}, {0.224830567837, 0.121000006795, 0.180636614561},
{0.219454854727, 0.0789999961853, 0.178816378117}, {0.219454854727, 0.121000006795, 0.178816378117}, {0.213255465031, 0.0789999961853, 0.178816378117}, {0.213255465031, 0.121000006795, 0.178816378117}, {0.207843348384, 0.0789999961853, 0.180636614561}, {0.207843348384, 0.121000006795, 0.180636614561}, {0.204821780324, 0.0789999961853, 0.182861328125}, {0.204821780324, 0.121000006795, 0.182861328125},
{0.201666727662, 0.0789999961853, 0.187314808369}, {0.201666727662, 0.121000006795, 0.187314808369}, {0.200406223536, 0.0789999961853, 0.19474837184}, {0.200406223536, 0.121000006795, 0.19474837184}, {0.202630907297, 0.0789999961853, 0.201616704464}, {0.202630907297, 0.121000006795, 0.201616704464}, {0.205824404955, 0.0789999961853, 0.20524802804}, {0.205824404955, 0.121000006795, 0.20524802804},
{0.209859237075, 0.0789999961853, 0.207841843367}, {0.209859237075, 0.121000006795, 0.207841843367}, {0.304455578327, 0.0789999961853, 0.169958502054}, {0.304455578327, 0.121000006795, 0.169958502054}, {0.304455578327, 0.0789999961853, 0.136291503906}, {0.304455578327, 0.121000006795, 0.136291503906}, {0.299116253853, 0.0789999961853, 0.135745435953}, {0.299116253853, 0.121000006795, 0.135745435953},
{0.296029448509, 0.0789999961853, 0.134456112981}, {0.296029448509, 0.121000006795, 0.134456112981}, {0.293786525726, 0.0789999961853, 0.131733894348}, {0.293786525726, 0.121000006795, 0.131733894348}, {0.292391002178, 0.0789999961853, 0.126983091235}, {0.292391002178, 0.121000006795, 0.126983091235}, {0.290171891451, 0.0789999961853, 0.113191895187}, {0.290171891451, 0.121000006795, 0.113191895187},
{0.28809684515, 0.0789999961853, 0.10696875304}, {0.28809684515, 0.121000006795, 0.10696875304}, {0.285326063633, 0.0789999961853, 0.10143326968}, {0.285326063633, 0.121000006795, 0.10143326968}, {0.2818595469, 0.0789999961853, 0.0965854153037}, {0.2818595469, 0.121000006795, 0.0965854153037}, {0.275355309248, 0.0789999961853, 0.0906029567122}, {0.275355309248, 0.121000006795, 0.0906029567122},
{0.271414518356, 0.0789999961853, 0.088168926537}, {0.271414518356, 0.121000006795, 0.088168926537}, {0.264825314283, 0.0789999961853, 0.0856610760093}, {0.264825314283, 0.121000006795, 0.0856610760093}, {0.254586577415, 0.0789999961853, 0.0839369297028}, {0.254586577415, 0.121000006795, 0.0839369297028}, {0.242932125926, 0.0789999961853, 0.0836547836661}, {0.242932125926, 0.121000006795, 0.0836547836661},
{0.242932125926, 0.0789999961853, 0.117492675781}, {0.242932125926, 0.121000006795, 0.117492675781}, {0.248696684837, 0.0789999961853, 0.117792017758}, {0.248696684837, 0.121000006795, 0.117792017758}, {0.255322277546, 0.0789999961853, 0.120654299855}, {0.255322277546, 0.121000006795, 0.120654299855}, {0.257797777653, 0.0789999961853, 0.124670900404}, {0.257797777653, 0.121000006795, 0.124670900404},
{0.258942991495, 0.0789999961853, 0.129575356841}, {0.258942991495, 0.121000006795, 0.129575356841}, {0.26001688838, 0.0789999961853, 0.142345249653}, {0.26001688838, 0.121000006795, 0.142345249653}, {0.262197136879, 0.0789999961853, 0.151933267713}, {0.262197136879, 0.121000006795, 0.151933267713}, {0.265127688646, 0.0789999961853, 0.156793281436}, {0.265127688646, 0.121000006795, 0.156793281436},
{0.270226836205, 0.0789999961853, 0.162167951465}, {0.270226836205, 0.121000006795, 0.162167951465}, {0.278961330652, 0.0789999961853, 0.167307555676}, {0.278961330652, 0.121000006795, 0.167307555676}, {0.289844721556, 0.0789999961853, 0.16974209249}, {0.289844721556, 0.121000006795, 0.16974209249}, {0.314880371094, 0.0789999961853, 0.169958502054}, {0.314880371094, 0.121000006795, 0.169958502054},
{0.346838384867, 0.0789999961853, 0.169958502054}, {0.346838384867, 0.121000006795, 0.169958502054}, {0.346838384867, 0.0789999961853, 0.121850587428}, {0.346838384867, 0.121000006795, 0.121850587428}, {0.348130732775, 0.0789999961853, 0.116693302989}, {0.348130732775, 0.121000006795, 0.116693302989}, {0.350428253412, 0.0789999961853, 0.114974193275}, {0.350428253412, 0.121000006795, 0.114974193275},
{0.355347424746, 0.0789999961853, 0.114974193275}, {0.355347424746, 0.121000006795, 0.114974193275}, {0.357612580061, 0.0789999961853, 0.116693302989}, {0.357612580061, 0.121000006795, 0.116693302989}, {0.35888671875, 0.0789999961853, 0.121850587428}, {0.35888671875, 0.121000006795, 0.121850587428}, {0.35888671875, 0.0789999961853, 0.169958502054}, {0.35888671875, 0.121000006795, 0.169958502054},
{0.390844732523, 0.0789999961853, 0.169958502054}, {0.390844732523, 0.121000006795, 0.169958502054}, {0.390844732523, 0.0789999961853, 0.122448727489}, {0.390844732523, 0.121000006795, 0.122448727489}, {0.390257745981, 0.0789999961853, 0.115070767701}, {0.390257745981, 0.121000006795, 0.115070767701}, {0.389214158058, 0.0789999961853, 0.110455498099}, {0.389214158058, 0.121000006795, 0.110455498099},
{0.386670410633, 0.0789999961853, 0.103987649083}, {0.386670410633, 0.121000006795, 0.103987649083}, {0.382952570915, 0.0789999961853, 0.0980658680201}, {0.382952570915, 0.121000006795, 0.0980658680201}, {0.378096610308, 0.0789999961853, 0.0927402079105}, {0.378096610308, 0.121000006795, 0.0927402079105}, {0.372569203377, 0.0789999961853, 0.0885036513209}, {0.372569203377, 0.121000006795, 0.0885036513209},
{0.368591010571, 0.0789999961853, 0.0863517448306}, {0.368591010571, 0.121000006795, 0.0863517448306}, {0.362183839083, 0.0789999961853, 0.0841325893998}, {0.362183839083, 0.121000006795, 0.0841325893998}, {0.352819830179, 0.0789999961853, 0.0830566436052}, {0.352819830179, 0.121000006795, 0.0830566436052}, {0.347387462854, 0.0789999961853, 0.0833701267838}, {0.347387462854, 0.121000006795, 0.0833701267838},
{0.337529957294, 0.0789999961853, 0.0858779847622}, {0.337529957294, 0.121000006795, 0.0858779847622}, {0.33101812005, 0.0789999961853, 0.0894046574831}, {0.33101812005, 0.121000006795, 0.0894046574831}, {0.327096581459, 0.0789999961853, 0.0925394818187}, {0.327096581459, 0.121000006795, 0.0925394818187}, {0.321059495211, 0.0789999961853, 0.0996727198362}, {0.321059495211, 0.121000006795, 0.0996727198362},
{0.317382663488, 0.0789999961853, 0.107556283474}, {0.317382663488, 0.121000006795, 0.107556283474}, {0.315339952707, 0.0789999961853, 0.116960771382}, {0.315339952707, 0.121000006795, 0.116960771382}, {0.314880371094, 0.0789999961853, 0.125012204051}, {0.314880371094, 0.121000006795, 0.125012204051}, {0.456811517477, 0.0789999961853, 0.117919921875}, {0.456811517477, 0.121000006795, 0.117919921875},
{0.456811517477, 0.0789999961853, 0.0848510712385}, {0.456811517477, 0.121000006795, 0.0848510712385}, {0.449633777142, 0.0789999961853, 0.0841674804688}, {0.449633777142, 0.121000006795, 0.0841674804688}, {0.438409090042, 0.0789999961853, 0.0853647813201}, {0.438409090042, 0.121000006795, 0.0853647813201}, {0.430786937475, 0.0789999961853, 0.0878342092037}, {0.430786937475, 0.121000006795, 0.0878342092037},
{0.423847347498, 0.0789999961853, 0.0916506126523}, {0.423847347498, 0.121000006795, 0.0916506126523}, {0.415694266558, 0.0789999961853, 0.0987975001335}, {0.415694266558, 0.121000006795, 0.0987975001335}, {0.409626871347, 0.0789999961853, 0.107490062714}, {0.409626871347, 0.121000006795, 0.107490062714}, {0.405986428261, 0.0789999961853, 0.117396093905}, {0.405986428261, 0.121000006795, 0.117396093905},
{0.404848784208, 0.0789999961853, 0.125621974468}, {0.404848784208, 0.121000006795, 0.125621974468}, {0.405460089445, 0.0789999961853, 0.136773362756}, {0.405460089445, 0.121000006795, 0.136773362756}, {0.408514022827, 0.0789999961853, 0.146849304438}, {0.408514022827, 0.121000006795, 0.146849304438}, {0.414011120796, 0.0789999961853, 0.155857369304}, {0.414011120796, 0.121000006795, 0.155857369304},
{0.419706851244, 0.0789999961853, 0.161869645119}, {0.419706851244, 0.121000006795, 0.161869645119}, {0.426194399595, 0.0789999961853, 0.166679561138}, {0.426194399595, 0.121000006795, 0.166679561138}, {0.430848121643, 0.0789999961853, 0.169122710824}, {0.430848121643, 0.121000006795, 0.169122710824}, {0.440944284201, 0.0789999961853, 0.172176614404}, {0.440944284201, 0.121000006795, 0.172176614404},
{0.449206531048, 0.0789999961853, 0.172863766551}, {0.449206531048, 0.121000006795, 0.172863766551}, {0.461098641157, 0.0789999961853, 0.171715006232}, {0.461098641157, 0.121000006795, 0.171715006232}, {0.466419756413, 0.0789999961853, 0.170279070735}, {0.466419756413, 0.121000006795, 0.170279070735}, {0.475812107325, 0.0789999961853, 0.165684014559}, {0.475812107325, 0.121000006795, 0.165684014559},
{0.479883313179, 0.0789999961853, 0.162524908781}, {0.479883313179, 0.121000006795, 0.162524908781}, {0.486646950245, 0.0789999961853, 0.154695942998}, {0.486646950245, 0.121000006795, 0.154695942998}, {0.491177290678, 0.0789999961853, 0.145178213716}, {0.491177290678, 0.121000006795, 0.145178213716}, {0.493442475796, 0.0789999961853, 0.133977785707}, {0.493442475796, 0.121000006795, 0.133977785707},
{0.493725597858, 0.0789999961853, 0.127746582031}, {0.493725597858, 0.121000006795, 0.127746582031}, {0.493725597858, 0.0789999961853, 0.0859619155526}, {0.493725597858, 0.121000006795, 0.0859619155526}, {0.461767584085, 0.0789999961853, 0.0859619155526}, {0.461767584085, 0.121000006795, 0.0859619155526}, {0.461767584085, 0.0789999961853, 0.125439450145}, {0.461767584085, 0.121000006795, 0.125439450145},
{0.460170358419, 0.0789999961853, 0.133475720882}, {0.460170358419, 0.121000006795, 0.133475720882}, {0.454946309328, 0.0789999961853, 0.139057740569}, {0.454946309328, 0.121000006795, 0.139057740569}, {0.448866248131, 0.0789999961853, 0.140200436115}, {0.448866248131, 0.121000006795, 0.140200436115}, {0.44394659996, 0.0789999961853, 0.138830721378}, {0.44394659996, 0.121000006795, 0.138830721378},
{0.440374433994, 0.0789999961853, 0.135974481702}, {0.440374433994, 0.121000006795, 0.135974481702}, {0.437439292669, 0.0789999961853, 0.13008607924}, {0.437439292669, 0.121000006795, 0.13008607924}, {0.437322556973, 0.0789999961853, 0.126246407628}, {0.437322556973, 0.121000006795, 0.126246407628}, {0.438840895891, 0.0789999961853, 0.121397547424}, {0.438840895891, 0.121000006795, 0.121397547424},
{0.443405002356, 0.0789999961853, 0.116992622614}, {0.443405002356, 0.121000006795, 0.116992622614}, {0.44825732708, 0.0789999961853, 0.115718469024}, {0.44825732708, 0.121000006795, 0.115718469024}, {0.451555669308, 0.0789999961853, 0.115908578038}, {0.451555669308, 0.121000006795, 0.115908578038}, {-0.942291259766, -0.121000006795, -0.0864746123552}, {-0.942291259766, -0.0789999961853, -0.0864746123552},
{-0.942291259766, -0.121000006795, -0.169616699219}, {-0.942291259766, -0.0789999961853, -0.169616699219}, {-0.97698366642, -0.121000006795, -0.169616699219}, {-0.97698366642, -0.0789999961853, -0.169616699219}, {-0.97698366642, -0.121000006795, -0.052978515625}, {-0.97698366642, -0.0789999961853, -0.052978515625}, {-0.931780993938, -0.121000006795, -0.052978515625}, {-0.931780993938, -0.0789999961853, -0.052978515625},
{-0.922936737537, -0.121000006795, -0.0532980710268}, {-0.922936737537, -0.0789999961853, -0.0532980710268}, {-0.914703249931, -0.121000006795, -0.0542567148805}, {-0.914703249931, -0.0789999961853, -0.0542567148805}, {-0.907080590725, -0.121000006795, -0.0558544658124}, {-0.907080590725, -0.0789999961853, -0.0558544658124}, {-0.900068759918, -0.121000006795, -0.0580913200974}, {-0.900068759918, -0.0789999961853, -0.0580913200974},
{-0.890696108341, -0.121000006795, -0.0626448988914}, {-0.890696108341, -0.0789999961853, -0.0626448988914}, {-0.882253289223, -0.121000006795, -0.0690323486924}, {-0.882253289223, -0.0789999961853, -0.0690323486924}, {-0.877047538757, -0.121000006795, -0.0745476186275}, {-0.877047538757, -0.0789999961853, -0.0745476186275}, {-0.871013522148, -0.121000006795, -0.0838443934917}, {-0.871013522148, -0.0789999961853, -0.0838443934917},
{-0.868174016476, -0.121000006795, -0.0907248333097}, {-0.868174016476, -0.0789999961853, -0.0907248333097}, {-0.866280913353, -0.121000006795, -0.0981513261795}, {-0.866280913353, -0.0789999961853, -0.0981513261795}, {-0.865334391594, -0.121000006795, -0.106123894453}, {-0.865334391594, -0.0789999961853, -0.106123894453}, {-0.865317225456, -0.121000006795, -0.114332571626}, {-0.865317225456, -0.0789999961853, -0.114332571626},
{-0.8661262393, -0.121000006795, -0.122022002935}, {-0.8661262393, -0.0789999961853, -0.122022002935}, {-0.867744207382, -0.121000006795, -0.129250302911}, {-0.867744207382, -0.0789999961853, -0.129250302911}, {-0.870171189308, -0.121000006795, -0.136017486453}, {-0.870171189308, -0.0789999961853, -0.136017486453}, {-0.875328540802, -0.121000006795, -0.145303636789}, {-0.875328540802, -0.0789999961853, -0.145303636789},
{-0.87977796793, -0.121000006795, -0.150918006897}, {-0.87977796793, -0.0789999961853, -0.150918006897}, {-0.887796938419, -0.121000006795, -0.158309102058}, {-0.887796938419, -0.0789999961853, -0.158309102058}, {-0.896905660629, -0.121000006795, -0.163957849145}, {-0.896905660629, -0.0789999961853, -0.163957849145}, {-0.903559565544, -0.121000006795, -0.166732653975}, {-0.903559565544, -0.0789999961853, -0.166732653975},
{-0.914412677288, -0.121000006795, -0.169408395886}, {-0.914412677288, -0.0789999961853, -0.169408395886}, {-0.92631226778, -0.121000006795, -0.170300289989}, {-0.92631226778, -0.0789999961853, -0.170300289989}, {-0.936651587486, -0.121000006795, -0.169958502054}, {-0.936651587486, -0.0789999961853, -0.169958502054}, {-0.936651587486, -0.121000006795, -0.135693356395}, {-0.936651587486, -0.0789999961853, -0.135693356395},
{-0.926610052586, -0.121000006795, -0.135543182492}, {-0.926610052586, -0.0789999961853, -0.135543182492}, {-0.918712377548, -0.121000006795, -0.134341850877}, {-0.918712377548, -0.0789999961853, -0.134341850877}, {-0.912250578403, -0.121000006795, -0.131939157844}, {-0.912250578403, -0.0789999961853, -0.131939157844}, {-0.907224774361, -0.121000006795, -0.128335118294}, {-0.907224774361, -0.0789999961853, -0.128335118294},
{-0.903634905815, -0.121000006795, -0.123529739678}, {-0.903634905815, -0.0789999961853, -0.123529739678}, {-0.901480972767, -0.121000006795, -0.117523014545}, {-0.901480972767, -0.0789999961853, -0.117523014545}, {-0.900762915611, -0.121000006795, -0.110314942896}, {-0.900762915611, -0.0789999961853, -0.110314942896}, {-0.901468813419, -0.121000006795, -0.103543713689}, {-0.901468813419, -0.0789999961853, -0.103543713689},
{-0.903586387634, -0.121000006795, -0.0979010388255}, {-0.903586387634, -0.0789999961853, -0.0979010388255}, {-0.907115578651, -0.121000006795, -0.0933869034052}, {-0.907115578651, -0.0789999961853, -0.0933869034052}, {-0.912056386471, -0.121000006795, -0.0900012925267}, {-0.912056386471, -0.0789999961853, -0.0900012925267}, {-0.918408930302, -0.121000006795, -0.0877442061901}, {-0.918408930302, -0.0789999961853, -0.0877442061901},
{-0.930584728718, -0.121000006795, -0.0864746123552}, {-0.930584728718, -0.0789999961853, -0.0864746123552}, {-0.803948998451, -0.121000006795, -0.137658685446}, {-0.803948998451, -0.0789999961853, -0.137658685446}, {-0.803948998451, -0.121000006795, -0.170727536082}, {-0.803948998451, -0.0789999961853, -0.170727536082}, {-0.809591710567, -0.121000006795, -0.171374738216}, {-0.809591710567, -0.0789999961853, -0.171374738216},
{-0.816890776157, -0.121000006795, -0.171111807227}, {-0.816890776157, -0.0789999961853, -0.171111807227}, {-0.824968039989, -0.121000006795, -0.16954036057}, {-0.824968039989, -0.0789999961853, -0.16954036057}, {-0.834675848484, -0.121000006795, -0.165349841118}, {-0.834675848484, -0.0789999961853, -0.165349841118}, {-0.839074671268, -0.121000006795, -0.162356585264}, {-0.839074671268, -0.0789999961853, -0.162356585264},
{-0.845066189766, -0.121000006795, -0.156781107187}, {-0.845066189766, -0.0789999961853, -0.156781107187}, {-0.849844276905, -0.121000006795, -0.150375455618}, {-0.849844276905, -0.0789999961853, -0.150375455618}, {-0.854091525078, -0.121000006795, -0.140772774816}, {-0.854091525078, -0.0789999961853, -0.140772774816}, {-0.855304956436, -0.121000006795, -0.135516390204}, {-0.855304956436, -0.0789999961853, -0.135516390204},
{-0.855911195278, -0.121000006795, -0.124243661761}, {-0.855911195278, -0.0789999961853, -0.124243661761}, {-0.855300366879, -0.121000006795, -0.118805244565}, {-0.855300366879, -0.0789999961853, -0.118805244565}, {-0.853238999844, -0.121000006795, -0.111148186028}, {-0.853238999844, -0.0789999961853, -0.111148186028}, {-0.851101279259, -0.121000006795, -0.106377184391}, {-0.851101279259, -0.0789999961853, -0.106377184391},
{-0.84674936533, -0.121000006795, -0.0997212380171}, {-0.84674936533, -0.0789999961853, -0.0997212380171}, {-0.838956832886, -0.121000006795, -0.0919529646635}, {-0.838956832886, -0.0789999961853, -0.0919529646635}, {-0.829912483692, -0.121000006795, -0.0864559113979}, {-0.829912483692, -0.0789999961853, -0.0864559113979}, {-0.819816231728, -0.121000006795, -0.0834019929171}, {-0.819816231728, -0.0789999961853, -0.0834019929171},
{-0.811553955078, -0.121000006795, -0.0827148407698}, {-0.811553955078, -0.0789999961853, -0.0827148407698}, {-0.799661815166, -0.121000006795, -0.0838636085391}, {-0.799661815166, -0.0789999961853, -0.0838636085391}, {-0.794340729713, -0.121000006795, -0.0852995589375}, {-0.794340729713, -0.0789999961853, -0.0852995589375}, {-0.784948408604, -0.121000006795, -0.0898946002126}, {-0.784948408604, -0.0789999961853, -0.0898946002126},
{-0.780877172947, -0.121000006795, -0.0930536985397}, {-0.780877172947, -0.0789999961853, -0.0930536985397}, {-0.774113535881, -0.121000006795, -0.100882664323}, {-0.774113535881, -0.0789999961853, -0.100882664323}, {-0.769583165646, -0.121000006795, -0.110400401056}, {-0.769583165646, -0.0789999961853, -0.110400401056}, {-0.767671883106, -0.121000006795, -0.11864297092}, {-0.767671883106, -0.0789999961853, -0.11864297092},
{-0.767034888268, -0.121000006795, -0.12783202529}, {-0.767034888268, -0.0789999961853, -0.12783202529}, {-0.767034888268, -0.121000006795, -0.169616699219}, {-0.767034888268, -0.0789999961853, -0.169616699219}, {-0.798992931843, -0.121000006795, -0.169616699219}, {-0.798992931843, -0.0789999961853, -0.169616699219}, {-0.798992931843, -0.121000006795, -0.130139157176}, {-0.798992931843, -0.0789999961853, -0.130139157176},
{-0.799702823162, -0.121000006795, -0.124490410089}, {-0.799702823162, -0.0789999961853, -0.124490410089}, {-0.803946912289, -0.121000006795, -0.117732845247}, {-0.803946912289, -0.0789999961853, -0.117732845247}, {-0.807195425034, -0.121000006795, -0.115950539708}, {-0.807195425034, -0.0789999961853, -0.115950539708}, {-0.812645554543, -0.121000006795, -0.115443408489}, {-0.812645554543, -0.0789999961853, -0.115443408489},
{-0.817451953888, -0.121000006795, -0.117117501795}, {-0.817451953888, -0.0789999961853, -0.117117501795}, {-0.820886194706, -0.121000006795, -0.120193682611}, {-0.820886194706, -0.0789999961853, -0.120193682611}, {-0.822973310947, -0.121000006795, -0.124070756137}, {-0.822973310947, -0.0789999961853, -0.124070756137}, {-0.823201358318, -0.121000006795, -0.13082882762}, {-0.823201358318, -0.0789999961853, -0.13082882762},
{-0.821130871773, -0.121000006795, -0.135366231203}, {-0.821130871773, -0.0789999961853, -0.135366231203}, {-0.817355453968, -0.121000006795, -0.138585984707}, {-0.817355453968, -0.0789999961853, -0.138585984707}, {-0.811724841595, -0.121000006795, -0.139880374074}, {-0.811724841595, -0.0789999961853, -0.139880374074}, {-0.663934648037, -0.121000006795, -0.0464262291789}, {-0.663934648037, -0.0789999961853, -0.0464262291789},
{-0.658449709415, -0.121000006795, -0.0477367863059}, {-0.658449709415, -0.0789999961853, -0.0477367863059}, {-0.654462873936, -0.121000006795, -0.0503305979073}, {-0.654462873936, -0.0789999961853, -0.0503305979073}, {-0.649963438511, -0.121000006795, -0.0563858672976}, {-0.649963438511, -0.0789999961853, -0.0563858672976}, {-0.648972392082, -0.121000006795, -0.0608302392066}, {-0.648972392082, -0.0789999961853, -0.0608302392066},
{-0.6502571702, -0.121000006795, -0.0682637989521}, {-0.6502571702, -0.0789999961853, -0.0682637989521}, {-0.652802944183, -0.121000006795, -0.0720458105206}, {-0.652802944183, -0.0789999961853, -0.0720458105206}, {-0.656450033188, -0.121000006795, -0.0749420002103}, {-0.656450033188, -0.0789999961853, -0.0749420002103}, {-0.661825716496, -0.121000006795, -0.0767622217536}, {-0.661825716496, -0.0789999961853, -0.0767622217536},
{-0.668025016785, -0.121000006795, -0.0767622217536}, {-0.668025016785, -0.0789999961853, -0.0767622217536}, {-0.671750426292, -0.121000006795, -0.0757509842515}, {-0.671750426292, -0.0789999961853, -0.0757509842515}, {-0.676458716393, -0.121000006795, -0.0727172866464}, {-0.676458716393, -0.0789999961853, -0.0727172866464}, {-0.678772509098, -0.121000006795, -0.06986156106}, {-0.678772509098, -0.0789999961853, -0.06986156106},
{-0.680796980858, -0.121000006795, -0.0637739449739}, {-0.680796980858, -0.0789999961853, -0.0637739449739}, {-0.680457115173, -0.121000006795, -0.0581029430032}, {-0.680457115173, -0.0789999961853, -0.0581029430032}, {-0.679122209549, -0.121000006795, -0.0547496899962}, {-0.679122209549, -0.0789999961853, -0.0547496899962}, {-0.675456106663, -0.121000006795, -0.0503305979073}, {-0.675456106663, -0.0789999961853, -0.0503305979073},
{-0.671421289444, -0.121000006795, -0.0477367863059}, {-0.671421289444, -0.0789999961853, -0.0477367863059}, {-0.577764868736, -0.121000006795, -0.052978515625}, {-0.577764868736, -0.0789999961853, -0.052978515625}, {-0.545806884766, -0.121000006795, -0.052978515625}, {-0.545806884766, -0.0789999961853, -0.052978515625}, {-0.545806884766, -0.121000006795, -0.123986817896}, {-0.545806884766, -0.0789999961853, -0.123986817896},
{-0.546777665615, -0.121000006795, -0.135340943933}, {-0.546777665615, -0.0789999961853, -0.135340943933}, {-0.547991156578, -0.121000006795, -0.140502288938}, {-0.547991156578, -0.0789999961853, -0.140502288938}, {-0.551874279976, -0.121000006795, -0.149793475866}, {-0.551874279976, -0.0789999961853, -0.149793475866}, {-0.554543912411, -0.121000006795, -0.153923362494}, {-0.554543912411, -0.0789999961853, -0.153923362494},
{-0.559996545315, -0.121000006795, -0.159948825836}, {-0.559996545315, -0.0789999961853, -0.159948825836}, {-0.56971257925, -0.121000006795, -0.16647733748}, {-0.56971257925, -0.0789999961853, -0.16647733748}, {-0.57672226429, -0.121000006795, -0.169318899512}, {-0.57672226429, -0.0789999961853, -0.169318899512}, {-0.588258504868, -0.121000006795, -0.171300917864}, {-0.588258504868, -0.0789999961853, -0.171300917864},
{-0.598203957081, -0.121000006795, -0.170643076301}, {-0.598203957081, -0.0789999961853, -0.170643076301}, {-0.606043040752, -0.121000006795, -0.168595299125}, {-0.606043040752, -0.0789999961853, -0.168595299125}, {-0.615504145622, -0.121000006795, -0.163741335273}, {-0.615504145622, -0.0789999961853, -0.163741335273}, {-0.619809985161, -0.121000006795, -0.160404235125}, {-0.619809985161, -0.0789999961853, -0.160404235125},
{-0.627194464207, -0.121000006795, -0.152283161879}, {-0.627194464207, -0.0789999961853, -0.152283161879}, {-0.629979431629, -0.121000006795, -0.147789224982}, {-0.629979431629, -0.0789999961853, -0.147789224982}, {-0.633692681789, -0.121000006795, -0.13797621429}, {-0.633692681789, -0.0789999961853, -0.13797621429}, {-0.634621024132, -0.121000006795, -0.132657125592}, {-0.634621024132, -0.0789999961853, -0.132657125592},
{-0.634853601456, -0.121000006795, -0.124317996204}, {-0.634853601456, -0.0789999961853, -0.124317996204}, {-0.633009076118, -0.121000006795, -0.113914422691}, {-0.633009076118, -0.0789999961853, -0.113914422691}, {-0.631164610386, -0.121000006795, -0.109058484435}, {-0.631164610386, -0.0789999961853, -0.109058484435}, {-0.625631093979, -0.121000006795, -0.100038297474}, {-0.625631093979, -0.0789999961853, -0.100038297474},
{-0.619915664196, -0.121000006795, -0.093927398324}, {-0.619915664196, -0.0789999961853, -0.093927398324}, {-0.615692734718, -0.121000006795, -0.0905013382435}, {-0.615692734718, -0.0789999961853, -0.0905013382435}, {-0.606567382812, -0.121000006795, -0.0855179801583}, {-0.606567382812, -0.0789999961853, -0.0855179801583}, {-0.60166490078, -0.121000006795, -0.0839606821537}, {-0.60166490078, -0.0789999961853, -0.0839606821537},
{-0.591180443764, -0.121000006795, -0.0827148407698}, {-0.591180443764, -0.0789999961853, -0.0827148407698}, {-0.582635521889, -0.121000006795, -0.0832275375724}, {-0.582635521889, -0.0789999961853, -0.0832275375724}, {-0.582635521889, -0.121000006795, -0.118432618678}, {-0.582635521889, -0.0789999961853, -0.118432618678}, {-0.58928757906, -0.121000006795, -0.115429252386}, {-0.58928757906, -0.0789999961853, -0.115429252386},
{-0.596078872681, -0.121000006795, -0.116747900844}, {-0.596078872681, -0.0789999961853, -0.116747900844}, {-0.600036859512, -0.121000006795, -0.120171427727}, {-0.600036859512, -0.0789999961853, -0.120171427727}, {-0.602462232113, -0.121000006795, -0.126205489039}, {-0.602462232113, -0.0789999961853, -0.126205489039}, {-0.602197289467, -0.121000006795, -0.130667030811}, {-0.602197289467, -0.0789999961853, -0.130667030811},
{-0.599414408207, -0.121000006795, -0.13573127985}, {-0.599414408207, -0.0789999961853, -0.13573127985}, {-0.595829665661, -0.121000006795, -0.138468191028}, {-0.595829665661, -0.0789999961853, -0.138468191028}, {-0.592358648777, -0.121000006795, -0.139608338475}, {-0.592358648777, -0.0789999961853, -0.139608338475}, {-0.586574792862, -0.121000006795, -0.139392450452}, {-0.586574792862, -0.0789999961853, -0.139392450452},
{-0.583662331104, -0.121000006795, -0.138185039163}, {-0.583662331104, -0.0789999961853, -0.138185039163}, {-0.580385923386, -0.121000006795, -0.134864658117}, {-0.580385923386, -0.0789999961853, -0.134864658117}, {-0.578056097031, -0.121000006795, -0.127620175481}, {-0.578056097031, -0.0789999961853, -0.127620175481}, {-0.577764868736, -0.121000006795, -0.122790530324}, {-0.577764868736, -0.0789999961853, -0.122790530324},
{-0.397723376751, -0.121000006795, -0.169616699219}, {-0.397723376751, -0.0789999961853, -0.169616699219}, {-0.397723376751, -0.121000006795, -0.0855346694589}, {-0.397723376751, -0.0789999961853, -0.0855346694589}, {-0.397218316793, -0.121000006795, -0.0786223784089}, {-0.397218316793, -0.0789999961853, -0.0786223784089}, {-0.395702987909, -0.121000006795, -0.0723198726773}, {-0.395702987909, -0.0789999961853, -0.0723198726773},
{-0.392111092806, -0.121000006795, -0.0648650601506}, {-0.392111092806, -0.0789999961853, -0.0648650601506}, {-0.385186642408, -0.121000006795, -0.0571700744331}, {-0.385186642408, -0.0789999961853, -0.0571700744331}, {-0.378281950951, -0.121000006795, -0.0529471635818}, {-0.378281950951, -0.0789999961853, -0.0529471635818}, {-0.372402638197, -0.121000006795, -0.0510116666555}, {-0.372402638197, -0.0789999961853, -0.0510116666555},
{-0.365922629833, -0.121000006795, -0.0501318871975}, {-0.365922629833, -0.0789999961853, -0.0501318871975}, {-0.355788528919, -0.121000006795, -0.0509514994919}, {-0.355788528919, -0.0789999961853, -0.0509514994919}, {-0.346707612276, -0.121000006795, -0.0548548549414}, {-0.346707612276, -0.0789999961853, -0.0548548549414}, {-0.342755705118, -0.121000006795, -0.0579775460064}, {-0.342755705118, -0.0789999961853, -0.0579775460064},
{-0.336029052734, -0.121000006795, -0.0665649399161}, {-0.336029052734, -0.0789999961853, -0.0665649399161}, {-0.329431772232, -0.121000006795, -0.0584811419249}, {-0.329431772232, -0.0789999961853, -0.0584811419249}, {-0.325439423323, -0.121000006795, -0.0551966540515}, {-0.325439423323, -0.0789999961853, -0.0551966540515}, {-0.318929135799, -0.121000006795, -0.0519162155688}, {-0.318929135799, -0.0789999961853, -0.0519162155688},
{-0.313876986504, -0.121000006795, -0.0506420582533}, {-0.313876986504, -0.0789999961853, -0.0506420582533}, {-0.306719958782, -0.121000006795, -0.0500732436776}, {-0.306719958782, -0.0789999961853, -0.0500732436776}, {-0.299854695797, -0.121000006795, -0.0506011024117}, {-0.299854695797, -0.0789999961853, -0.0506011024117}, {-0.291918545961, -0.121000006795, -0.0529471635818}, {-0.291918545961, -0.0789999961853, -0.0529471635818},
{-0.285373836756, -0.121000006795, -0.0571700744331}, {-0.285373836756, -0.0789999961853, -0.0571700744331}, {-0.279204308987, -0.121000006795, -0.0650243237615}, {-0.279204308987, -0.0789999961853, -0.0650243237615}, {-0.276033043861, -0.121000006795, -0.0731870010495}, {-0.276033043861, -0.0789999961853, -0.0731870010495}, {-0.275042057037, -0.121000006795, -0.0778872147202}, {-0.275042057037, -0.0789999961853, -0.0778872147202},
{-0.274249255657, -0.121000006795, -0.0885253921151}, {-0.274249255657, -0.0789999961853, -0.0885253921151}, {-0.274249255657, -0.121000006795, -0.169616699219}, {-0.274249255657, -0.0789999961853, -0.169616699219}, {-0.308941662312, -0.121000006795, -0.169616699219}, {-0.308941662312, -0.0789999961853, -0.169616699219}, {-0.308941662312, -0.121000006795, -0.093737795949}, {-0.308941662312, -0.0789999961853, -0.093737795949},
{-0.309297591448, -0.121000006795, -0.088252864778}, {-0.309297591448, -0.0789999961853, -0.088252864778}, {-0.310585409403, -0.121000006795, -0.0853248313069}, {-0.310585409403, -0.0789999961853, -0.0853248313069}, {-0.314228892326, -0.121000006795, -0.0844753980637}, {-0.314228892326, -0.0789999961853, -0.0844753980637}, {-0.31665584445, -0.121000006795, -0.0857131555676}, {-0.31665584445, -0.0789999961853, -0.0857131555676},
{-0.318597406149, -0.121000006795, -0.0931396484375}, {-0.318597406149, -0.0789999961853, -0.0931396484375}, {-0.318597406149, -0.121000006795, -0.169616699219}, {-0.318597406149, -0.0789999961853, -0.169616699219}, {-0.353289783001, -0.121000006795, -0.169616699219}, {-0.353289783001, -0.0789999961853, -0.169616699219}, {-0.353289783001, -0.121000006795, -0.093737795949}, {-0.353289783001, -0.0789999961853, -0.093737795949},
{-0.353962779045, -0.121000006795, -0.0869691073895}, {-0.353962779045, -0.0789999961853, -0.0869691073895}, {-0.355218142271, -0.121000006795, -0.0851357281208}, {-0.355218142271, -0.0789999961853, -0.0851357281208}, {-0.359360218048, -0.121000006795, -0.0846442878246}, {-0.359360218048, -0.0789999961853, -0.0846442878246}, {-0.361544519663, -0.121000006795, -0.0864078700542}, {-0.361544519663, -0.0789999961853, -0.0864078700542},
{-0.363030999899, -0.121000006795, -0.093737795949}, {-0.363030999899, -0.0789999961853, -0.093737795949}, {-0.363030999899, -0.121000006795, -0.169616699219}, {-0.363030999899, -0.0789999961853, -0.169616699219}, {-0.208282470703, -0.121000006795, -0.137658685446}, {-0.208282470703, -0.0789999961853, -0.137658685446}, {-0.208282470703, -0.121000006795, -0.170727536082}, {-0.208282470703, -0.0789999961853, -0.170727536082},
{-0.215460211039, -0.121000006795, -0.171411126852}, {-0.215460211039, -0.0789999961853, -0.171411126852}, {-0.226684898138, -0.121000006795, -0.170213848352}, {-0.226684898138, -0.0789999961853, -0.170213848352}, {-0.234307065606, -0.121000006795, -0.167744427919}, {-0.234307065606, -0.0789999961853, -0.167744427919}, {-0.241246640682, -0.121000006795, -0.163928046823}, {-0.241246640682, -0.0789999961853, -0.163928046823},
{-0.245493799448, -0.121000006795, -0.160635456443}, {-0.245493799448, -0.0789999961853, -0.160635456443}, {-0.251144111156, -0.121000006795, -0.154721736908}, {-0.251144111156, -0.0789999961853, -0.154721736908}, {-0.254177838564, -0.121000006795, -0.150375455618}, {-0.254177838564, -0.0789999961853, -0.150375455618}, {-0.258425056934, -0.121000006795, -0.140772774816}, {-0.258425056934, -0.0789999961853, -0.140772774816},
{-0.26001778245, -0.121000006795, -0.132774427533}, {-0.26001778245, -0.0789999961853, -0.132774427533}, {-0.260244697332, -0.121000006795, -0.124243661761}, {-0.260244697332, -0.0789999961853, -0.124243661761}, {-0.259633928537, -0.121000006795, -0.118805244565}, {-0.259633928537, -0.0789999961853, -0.118805244565}, {-0.257572501898, -0.121000006795, -0.111148186028}, {-0.257572501898, -0.0789999961853, -0.111148186028},
{-0.252686202526, -0.121000006795, -0.101873151958}, {-0.252686202526, -0.0789999961853, -0.101873151958}, {-0.24741820991, -0.121000006795, -0.0956176742911}, {-0.24741820991, -0.0789999961853, -0.0956176742911}, {-0.238899573684, -0.121000006795, -0.0888990461826}, {-0.238899573684, -0.0789999961853, -0.0888990461826}, {-0.229329258204, -0.121000006795, -0.0846235603094}, {-0.229329258204, -0.0789999961853, -0.0846235603094},
{-0.224149718881, -0.121000006795, -0.0834019929171}, {-0.224149718881, -0.0789999961853, -0.0834019929171}, {-0.215887457132, -0.121000006795, -0.0827148407698}, {-0.215887457132, -0.0789999961853, -0.0827148407698}, {-0.206812143326, -0.121000006795, -0.0833610221744}, {-0.206812143326, -0.0789999961853, -0.0833610221744}, {-0.196169912815, -0.121000006795, -0.0862329304218}, {-0.196169912815, -0.0789999961853, -0.0862329304218},
{-0.189281880856, -0.121000006795, -0.0898946002126}, {-0.189281880856, -0.0789999961853, -0.0898946002126}, {-0.1852106601, -0.121000006795, -0.0930536985397}, {-0.1852106601, -0.0789999961853, -0.0930536985397}, {-0.178447037935, -0.121000006795, -0.100882664323}, {-0.178447037935, -0.0789999961853, -0.100882664323}, {-0.173916712403, -0.121000006795, -0.110400401056}, {-0.173916712403, -0.0789999961853, -0.110400401056},
{-0.172500997782, -0.121000006795, -0.115790277719}, {-0.172500997782, -0.0789999961853, -0.115790277719}, {-0.171368405223, -0.121000006795, -0.12783202529}, {-0.171368405223, -0.0789999961853, -0.12783202529}, {-0.171368405223, -0.121000006795, -0.169616699219}, {-0.171368405223, -0.0789999961853, -0.169616699219}, {-0.203326418996, -0.121000006795, -0.169616699219}, {-0.203326418996, -0.0789999961853, -0.169616699219},
{-0.203326418996, -0.121000006795, -0.130139157176}, {-0.203326418996, -0.0789999961853, -0.130139157176}, {-0.204036310315, -0.121000006795, -0.124490410089}, {-0.204036310315, -0.0789999961853, -0.124490410089}, {-0.205712422729, -0.121000006795, -0.120673008263}, {-0.205712422729, -0.0789999961853, -0.120673008263}, {-0.210147678852, -0.121000006795, -0.116520874202}, {-0.210147678852, -0.0789999961853, -0.116520874202},
{-0.213805809617, -0.121000006795, -0.11545149982}, {-0.213805809617, -0.0789999961853, -0.11545149982}, {-0.218433231115, -0.121000006795, -0.115704298019}, {-0.218433231115, -0.0789999961853, -0.115704298019}, {-0.223013117909, -0.121000006795, -0.117987163365}, {-0.223013117909, -0.0789999961853, -0.117987163365}, {-0.226458877325, -0.121000006795, -0.12205940485}, {-0.226458877325, -0.0789999961853, -0.12205940485},
{-0.227830633521, -0.121000006795, -0.128550514579}, {-0.227830633521, -0.0789999961853, -0.128550514579}, {-0.226588308811, -0.121000006795, -0.133555114269}, {-0.226588308811, -0.0789999961853, -0.133555114269}, {-0.222884178162, -0.121000006795, -0.13785789907}, {-0.222884178162, -0.0789999961853, -0.13785789907}, {-0.216058343649, -0.121000006795, -0.139880374074}, {-0.216058343649, -0.0789999961853, -0.139880374074},
{-0.141204833984, -0.121000006795, -0.0844238251448}, {-0.141204833984, -0.0789999961853, -0.0844238251448}, {-0.109246827662, -0.121000006795, -0.0844238251448}, {-0.109246827662, -0.0789999961853, -0.0844238251448}, {-0.109246827662, -0.121000006795, -0.156372070312}, {-0.109246827662, -0.0789999961853, -0.156372070312}, {-0.109499633312, -0.121000006795, -0.163094758987}, {-0.109499633312, -0.0789999961853, -0.163094758987},
{-0.11082688719, -0.121000006795, -0.17235969007}, {-0.11082688719, -0.0789999961853, -0.17235969007}, {-0.114366203547, -0.121000006795, -0.183183923364}, {-0.114366203547, -0.0789999961853, -0.183183923364}, {-0.119927980006, -0.121000006795, -0.192260742188}, {-0.119927980006, -0.0789999961853, -0.192260742188}, {-0.124351114035, -0.121000006795, -0.197066128254}, {-0.124351114035, -0.0789999961853, -0.197066128254},
{-0.129259645939, -0.121000006795, -0.201070606709}, {-0.129259645939, -0.0789999961853, -0.201070606709}, {-0.134653568268, -0.121000006795, -0.204274207354}, {-0.134653568268, -0.0789999961853, -0.204274207354}, {-0.14053286612, -0.121000006795, -0.206676900387}, {-0.14053286612, -0.0789999961853, -0.206676900387}, {-0.146897569299, -0.121000006795, -0.208278700709}, {-0.146897569299, -0.0789999961853, -0.208278700709},
{-0.153747662902, -0.121000006795, -0.209079578519}, {-0.153747662902, -0.0789999961853, -0.209079578519}, {-0.16200235486, -0.121000006795, -0.208888426423}, {-0.16200235486, -0.0789999961853, -0.208888426423}, {-0.173760980368, -0.121000006795, -0.206103518605}, {-0.173760980368, -0.0789999961853, -0.206103518605}, {-0.173760980368, -0.121000006795, -0.175939947367}, {-0.173760980368, -0.0789999961853, -0.175939947367},
{-0.162870004773, -0.121000006795, -0.17949950695}, {-0.162870004773, -0.0789999961853, -0.17949950695}, {-0.157368391752, -0.121000006795, -0.179534390569}, {-0.157368391752, -0.0789999961853, -0.179534390569}, {-0.152429521084, -0.121000006795, -0.178211688995}, {-0.152429521084, -0.0789999961853, -0.178211688995}, {-0.146704927087, -0.121000006795, -0.173747599125}, {-0.146704927087, -0.0789999961853, -0.173747599125},
{-0.143000781536, -0.121000006795, -0.166307449341}, {-0.143000781536, -0.0789999961853, -0.166307449341}, {-0.141653805971, -0.121000006795, -0.159693971276}, {-0.141653805971, -0.0789999961853, -0.159693971276}, {-0.141204833984, -0.121000006795, -0.15175780654}, {-0.141204833984, -0.0789999961853, -0.15175780654}, {-0.125177294016, -0.121000006795, -0.0464262291789}, {-0.125177294016, -0.0789999961853, -0.0464262291789},
{-0.120553418994, -0.121000006795, -0.0473818406463}, {-0.120553418994, -0.0789999961853, -0.0473818406463}, {-0.117236576974, -0.121000006795, -0.049129255116}, {-0.117236576974, -0.0789999961853, -0.049129255116}, {-0.112480230629, -0.121000006795, -0.0539619363844}, {-0.112480230629, -0.0789999961853, -0.0539619363844}, {-0.110639765859, -0.121000006795, -0.0581029430032}, {-0.110639765859, -0.0789999961853, -0.0581029430032},
{-0.110427938402, -0.121000006795, -0.0647285357118}, {-0.110427938402, -0.0789999961853, -0.0647285357118}, {-0.112357370555, -0.121000006795, -0.0698615461588}, {-0.112357370555, -0.0789999961853, -0.0698615461588}, {-0.115414343774, -0.121000006795, -0.0733493119478}, {-0.115414343774, -0.0789999961853, -0.0733493119478}, {-0.119363203645, -0.121000006795, -0.0757509842515}, {-0.119363203645, -0.0789999961853, -0.0757509842515},
{-0.123068362474, -0.121000006795, -0.0767622217536}, {-0.123068362474, -0.0789999961853, -0.0767622217536}, {-0.131189078093, -0.121000006795, -0.0763577222824}, {-0.131189078093, -0.0789999961853, -0.0763577222824}, {-0.137701421976, -0.121000006795, -0.0727172866464}, {-0.137701421976, -0.0789999961853, -0.0727172866464}, {-0.141198262572, -0.121000006795, -0.0674224644899}, {-0.141198262572, -0.0789999961853, -0.0674224644899},
{-0.142116978765, -0.121000006795, -0.0608302392066}, {-0.142116978765, -0.0789999961853, -0.0608302392066}, {-0.139892265201, -0.121000006795, -0.0539619363844}, {-0.139892265201, -0.0789999961853, -0.0539619363844}, {-0.135145515203, -0.121000006795, -0.049129255116}, {-0.135145515203, -0.0789999961853, -0.049129255116}, {-0.131796315312, -0.121000006795, -0.0473818406463}, {-0.131796315312, -0.0789999961853, -0.0473818406463},
{-0.04466541484, -0.121000006795, -0.0829388201237}, {-0.04466541484, -0.0789999961853, -0.0829388201237}, {-0.0369522385299, -0.121000006795, -0.0845633670688}, {-0.0369522385299, -0.0789999961853, -0.0845633670688}, {-0.0275315921754, -0.121000006795, -0.0888954922557}, {-0.0275315921754, -0.0789999961853, -0.0888954922557}, {-0.0211138036102, -0.121000006795, -0.093769133091}, {-0.0211138036102, -0.0789999961853, -0.093769133091},
{-0.0154089229181, -0.121000006795, -0.0998228862882}, {-0.0154089229181, -0.0789999961853, -0.0998228862882}, {-0.0098754549399, -0.121000006795, -0.108802638948}, {-0.0098754549399, -0.0789999961853, -0.108802638948}, {-0.00733928149566, -0.121000006795, -0.116185151041}, {-0.00733928149566, -0.0789999961853, -0.116185151041}, {-0.00641703698784, -0.121000006795, -0.121415242553}, {-0.00641703698784, -0.0789999961853, -0.121415242553},
{-0.00642107846215, -0.121000006795, -0.132441744208}, {-0.00642107846215, -0.0789999961853, -0.132441744208}, {-0.00891275703907, -0.121000006795, -0.142764419317}, {-0.00891275703907, -0.0789999961853, -0.142764419317}, {-0.011092976667, -0.121000006795, -0.147537440062}, {-0.011092976667, -0.0789999961853, -0.147537440062}, {-0.0173221714795, -0.121000006795, -0.156306833029}, {-0.0173221714795, -0.0789999961853, -0.156306833029},
{-0.0234209224582, -0.121000006795, -0.162026375532}, {-0.0234209224582, -0.0789999961853, -0.162026375532}, {-0.0325017981231, -0.121000006795, -0.167559847236}, {-0.0325017981231, -0.0789999961853, -0.167559847236}, {-0.0399920046329, -0.121000006795, -0.170096039772}, {-0.0399920046329, -0.0789999961853, -0.170096039772}, {-0.0480646826327, -0.121000006795, -0.171248853207}, {-0.0480646826327, -0.0789999961853, -0.171248853207},
{-0.0564629733562, -0.121000006795, -0.171018272638}, {-0.0564629733562, -0.0789999961853, -0.171018272638}, {-0.0668544098735, -0.121000006795, -0.16855892539}, {-0.0668544098735, -0.0789999961853, -0.16855892539}, {-0.0739790648222, -0.121000006795, -0.165100485086}, {-0.0739790648222, -0.0789999961853, -0.165100485086}, {-0.0825866684318, -0.121000006795, -0.158337399364}, {-0.0825866684318, -0.0789999961853, -0.158337399364},
{-0.0863241925836, -0.121000006795, -0.15418933332}, {-0.0863241925836, -0.0789999961853, -0.15418933332}, {-0.090762488544, -0.121000006795, -0.147496983409}, {-0.090762488544, -0.0789999961853, -0.147496983409}, {-0.0937992185354, -0.121000006795, -0.140240371227}, {-0.0937992185354, -0.0789999961853, -0.140240371227}, {-0.0950450599194, -0.121000006795, -0.135089144111}, {-0.0950450599194, -0.0789999961853, -0.135089144111},
{-0.0956679880619, -0.121000006795, -0.124048501253}, {-0.0956679880619, -0.0789999961853, -0.124048501253}, {-0.0950450599194, -0.121000006795, -0.11857368052}, {-0.0950450599194, -0.0789999961853, -0.11857368052}, {-0.0929427072406, -0.121000006795, -0.110892355442}, {-0.0929427072406, -0.0789999961853, -0.110892355442}, {-0.0894387811422, -0.121000006795, -0.103848107159}, {-0.0894387811422, -0.0789999961853, -0.103848107159},
{-0.0863241702318, -0.121000006795, -0.0995058640838}, {-0.0863241702318, -0.0789999961853, -0.0995058640838}, {-0.080525778234, -0.121000006795, -0.0935507118702}, {-0.080525778234, -0.0789999961853, -0.0935507118702}, {-0.0715541169047, -0.121000006795, -0.0874833166599}, {-0.0715541169047, -0.0789999961853, -0.0874833166599}, {-0.0666314288974, -0.121000006795, -0.0853597298265}, {-0.0666314288974, -0.0789999961853, -0.0853597298265},
{-0.0559123530984, -0.121000006795, -0.0829327702522}, {-0.0559123530984, -0.0789999961853, -0.0829327702522}, {-0.0525115840137, -0.121000006795, -0.114249147475}, {-0.0525115840137, -0.0789999961853, -0.114249147475}, {-0.0566980838776, -0.121000006795, -0.115583963692}, {-0.0566980838776, -0.0789999961853, -0.115583963692}, {-0.0615550428629, -0.121000006795, -0.120342843235}, {-0.0615550428629, -0.0789999961853, -0.120342843235},
{-0.0631901994348, -0.121000006795, -0.125361576676}, {-0.0631901994348, -0.0789999961853, -0.125361576676}, {-0.0629353746772, -0.121000006795, -0.130092144012}, {-0.0629353746772, -0.0789999961853, -0.130092144012}, {-0.059686280787, -0.121000006795, -0.13603515923}, {-0.059686280787, -0.0789999961853, -0.13603515923}, {-0.054646294564, -0.121000006795, -0.139238744974}, {-0.054646294564, -0.0789999961853, -0.139238744974},
{-0.0501907989383, -0.121000006795, -0.139772668481}, {-0.0501907989383, -0.0789999961853, -0.139772668481}, {-0.0465655177832, -0.121000006795, -0.138994038105}, {-0.0465655177832, -0.0789999961853, -0.138994038105}, {-0.0407544709742, -0.121000006795, -0.134217977524}, {-0.0407544709742, -0.0789999961853, -0.134217977524}, {-0.0389281846583, -0.121000006795, -0.130092158914}, {-0.0389281846583, -0.0789999961853, -0.130092158914},
{-0.0389201007783, -0.121000006795, -0.123826533556}, {-0.0389201007783, -0.0789999961853, -0.123826533556}, {-0.0399394221604, -0.121000006795, -0.120999142528}, {-0.0399394221604, -0.0789999961853, -0.120999142528}, {-0.0433118864894, -0.121000006795, -0.11685205996}, {-0.0433118864894, -0.0789999961853, -0.11685205996}, {-0.0486512109637, -0.121000006795, -0.114360384643}, {-0.0486512109637, -0.0789999961853, -0.114360384643},
{-0.0525115840137, -0.121000006795, -0.114249147475}, {-0.0525115840137, -0.0789999961853, -0.114249147475}, {-0.0559123530984, -0.121000006795, -0.0829327702522}, {-0.0559123530984, -0.0789999961853, -0.0829327702522}, {0.0539611801505, -0.121000006795, -0.0835693329573}, {0.0539611801505, -0.0789999961853, -0.0835693329573}, {0.0539611801505, -0.121000006795, -0.117749020457}, {0.0539611801505, -0.0789999961853, -0.117749020457},
{0.0491881631315, -0.121000006795, -0.115969240665}, {0.0491881631315, -0.0789999961853, -0.115969240665}, {0.0443357564509, -0.121000006795, -0.116579025984}, {0.0443357564509, -0.0789999961853, -0.116579025984}, {0.0410350933671, -0.121000006795, -0.119734086096}, {0.0410350933671, -0.0789999961853, -0.119734086096}, {0.0393847562373, -0.121000006795, -0.125413164496}, {0.0393847562373, -0.0789999961853, -0.125413164496},
{0.039178468287, -0.121000006795, -0.12919922173}, {0.039178468287, -0.0789999961853, -0.12919922173}, {0.039178468287, -0.121000006795, -0.169616699219}, {0.039178468287, -0.0789999961853, -0.169616699219}, {0.00722045917064, -0.121000006795, -0.169616699219}, {0.00722045917064, -0.0789999961853, -0.169616699219}, {0.00722045917064, -0.121000006795, -0.123046875}, {0.00722045917064, -0.0789999961853, -0.123046875},
{0.00745911011472, -0.121000006795, -0.117545753717}, {0.00745911011472, -0.0789999961853, -0.117545753717}, {0.00936831906438, -0.121000006795, -0.107611402869}, {0.00936831906438, -0.0789999961853, -0.107611402869}, {0.01103887707, -0.121000006795, -0.103178143501}, {0.01103887707, -0.0789999961853, -0.103178143501}, {0.0158118996769, -0.121000006795, -0.0953795164824}, {0.0158118996769, -0.0789999961853, -0.0953795164824},
{0.0205657053739, -0.121000006795, -0.0905215591192}, {0.0205657053739, -0.0789999961853, -0.0905215591192}, {0.0241474937648, -0.121000006795, -0.0879125744104}, {0.0241474937648, -0.0789999961853, -0.0879125744104}, {0.0322697237134, -0.121000006795, -0.0842600092292}, {0.0322697237134, -0.0789999961853, -0.0842600092292}, {0.0416701510549, -0.121000006795, -0.082694619894}, {0.0416701510549, -0.0789999961853, -0.082694619894},
{0.37260133028, -0.121000006795, -0.104248046875}, {0.37260133028, -0.0789999961853, -0.104248046875}, {0.405670166016, -0.121000006795, -0.104248046875}, {0.405670166016, -0.0789999961853, -0.104248046875}, {0.411231964827, -0.121000006795, -0.112536117435}, {0.411231964827, -0.0789999961853, -0.112536117435}, {0.415340095758, -0.121000006795, -0.123282983899}, {0.415340095758, -0.0789999961853, -0.123282983899},
{0.41627702117, -0.121000006795, -0.134786784649}, {0.41627702117, -0.0789999961853, -0.134786784649}, {0.415682405233, -0.121000006795, -0.139786332846}, {0.415682405233, -0.0789999961853, -0.139786332846}, {0.413675636053, -0.121000006795, -0.146800234914}, {0.413675636053, -0.0789999961853, -0.146800234914}, {0.411594510078, -0.121000006795, -0.151152595878}, {0.411594510078, -0.0789999961853, -0.151152595878},
{0.407357931137, -0.121000006795, -0.157195702195}, {0.407357931137, -0.0789999961853, -0.157195702195}, {0.399814158678, -0.121000006795, -0.164201542735}, {0.399814158678, -0.0789999961853, -0.164201542735}, {0.391036629677, -0.121000006795, -0.16915255785}, {0.391036629677, -0.0789999961853, -0.16915255785}, {0.38115888834, -0.121000006795, -0.17190310359}, {0.38115888834, -0.0789999961853, -0.17190310359},
{0.369416475296, -0.121000006795, -0.172415301204}, {0.369416475296, -0.0789999961853, -0.172415301204}, {0.362447023392, -0.121000006795, -0.171561807394}, {0.362447023392, -0.0789999961853, -0.171561807394}, {0.355817347765, -0.121000006795, -0.169854834676}, {0.355817347765, -0.0789999961853, -0.169854834676}, {0.34952750802, -0.121000006795, -0.16729439795}, {0.34952750802, -0.0789999961853, -0.16729439795},
{0.343577355146, -0.121000006795, -0.163880482316}, {0.343577355146, -0.0789999961853, -0.163880482316}, {0.33528932929, -0.121000006795, -0.157159298658}, {0.33528932929, -0.0789999961853, -0.157159298658}, {0.330244272947, -0.121000006795, -0.151671841741}, {0.330244272947, -0.0789999961853, -0.151671841741}, {0.325928360224, -0.121000006795, -0.145752087235}, {0.325928360224, -0.0789999961853, -0.145752087235},
{0.322397142649, -0.121000006795, -0.139460191131}, {0.322397142649, -0.0789999961853, -0.139460191131}, {0.319650620222, -0.121000006795, -0.132796168327}, {0.319650620222, -0.0789999961853, -0.132796168327}, {0.317688822746, -0.121000006795, -0.125760003924}, {0.317688822746, -0.0789999961853, -0.125760003924}, {0.316511750221, -0.121000006795, -0.118351712823}, {0.316511750221, -0.0789999961853, -0.118351712823},
{0.316219002008, -0.121000006795, -0.106626473367}, {0.316219002008, -0.0789999961853, -0.106626473367}, {0.317713081837, -0.121000006795, -0.0954108759761}, {0.317713081837, -0.0789999961853, -0.0954108759761}, {0.319705218077, -0.121000006795, -0.0884495377541}, {0.319705218077, -0.0789999961853, -0.0884495377541}, {0.322494208813, -0.121000006795, -0.0819007903337}, {0.322494208813, -0.0789999961853, -0.0819007903337},
{0.326080024242, -0.121000006795, -0.0757646262646}, {0.326080024242, -0.0789999961853, -0.0757646262646}, {0.33295288682, -0.121000006795, -0.0673339813948}, {0.33295288682, -0.0789999961853, -0.0673339813948}, {0.338356912136, -0.121000006795, -0.0624315217137}, {0.338356912136, -0.0789999961853, -0.0624315217137}, {0.344157338142, -0.121000006795, -0.0583461374044}, {0.344157338142, -0.0789999961853, -0.0583461374044},
{0.350354194641, -0.121000006795, -0.0550778284669}, {0.350354194641, -0.0789999961853, -0.0550778284669}, {0.356947422028, -0.121000006795, -0.0526266023517}, {0.356947422028, -0.0789999961853, -0.0526266023517}, {0.363937079906, -0.121000006795, -0.0509924478829}, {0.363937079906, -0.0789999961853, -0.0509924478829}, {0.375164806843, -0.121000006795, -0.0500732436776}, {0.375164806843, -0.0789999961853, -0.0500732436776},
{0.382081657648, -0.121000006795, -0.0505914948881}, {0.382081657648, -0.0789999961853, -0.0505914948881}, {0.394305408001, -0.121000006795, -0.0535766594112}, {0.394305408001, -0.0789999961853, -0.0535766594112}, {0.394305408001, -0.121000006795, -0.0882690399885}, {0.394305408001, -0.0789999961853, -0.0882690399885}, {0.383643597364, -0.121000006795, -0.0847878605127}, {0.383643597364, -0.0789999961853, -0.0847878605127},
{0.37935179472, -0.121000006795, -0.0844238251448}, {0.37935179472, -0.0789999961853, -0.0844238251448}, {0.372252911329, -0.121000006795, -0.0851438194513}, {0.372252911329, -0.0789999961853, -0.0851438194513}, {0.365995407104, -0.121000006795, -0.0873038172722}, {0.365995407104, -0.0789999961853, -0.0873038172722}, {0.359356701374, -0.121000006795, -0.092028811574}, {0.359356701374, -0.0789999961853, -0.092028811574},
{0.356216788292, -0.121000006795, -0.0957799777389}, {0.356216788292, -0.0789999961853, -0.0957799777389}, {0.353304475546, -0.121000006795, -0.101531863213}, {0.353304475546, -0.0789999961853, -0.101531863213}, {0.351711779833, -0.121000006795, -0.109927624464}, {0.351711779833, -0.0789999961853, -0.109927624464}, {0.352048516273, -0.121000006795, -0.117213062942}, {0.352048516273, -0.0789999961853, -0.117213062942},
{0.354384452105, -0.121000006795, -0.125075414777}, {0.354384452105, -0.0789999961853, -0.125075414777}, {0.35778221488, -0.121000006795, -0.130273148417}, {0.35778221488, -0.0789999961853, -0.130273148417}, {0.362425208092, -0.121000006795, -0.134386330843}, {0.362425208092, -0.0789999961853, -0.134386330843}, {0.368035495281, -0.121000006795, -0.137136891484}, {0.368035495281, -0.0789999961853, -0.137136891484},
{0.372869670391, -0.121000006795, -0.13829728961}, {0.372869670391, -0.0789999961853, -0.13829728961}, {0.379391223192, -0.121000006795, -0.138657286763}, {0.379391223192, -0.0789999961853, -0.138657286763}, {0.384866595268, -0.121000006795, -0.136969044805}, {0.384866595268, -0.0789999961853, -0.136969044805}, {0.385258406401, -0.121000006795, -0.132031679153}, {0.385258406401, -0.0789999961853, -0.132031679153},
{0.380889892578, -0.121000006795, -0.130737304688}, {0.380889892578, -0.0789999961853, -0.130737304688}, {0.37260133028, -0.121000006795, -0.130737304688}, {0.37260133028, -0.0789999961853, -0.130737304688}, {0.475396722555, -0.121000006795, -0.137658685446}, {0.475396722555, -0.0789999961853, -0.137658685446}, {0.475396722555, -0.121000006795, -0.170727536082}, {0.475396722555, -0.0789999961853, -0.170727536082},
{0.469754040241, -0.121000006795, -0.171374738216}, {0.469754040241, -0.0789999961853, -0.171374738216}, {0.462454974651, -0.121000006795, -0.171111807227}, {0.462454974651, -0.0789999961853, -0.171111807227}, {0.45699429512, -0.121000006795, -0.170213848352}, {0.45699429512, -0.0789999961853, -0.170213848352}, {0.449372142553, -0.121000006795, -0.167744427919}, {0.449372142553, -0.0789999961853, -0.167744427919},
{0.442432552576, -0.121000006795, -0.163928046823}, {0.442432552576, -0.0789999961853, -0.163928046823}, {0.434279471636, -0.121000006795, -0.156781107187}, {0.434279471636, -0.0789999961853, -0.156781107187}, {0.428212076426, -0.121000006795, -0.148088529706}, {0.428212076426, -0.0789999961853, -0.148088529706}, {0.424571633339, -0.121000006795, -0.138182505965}, {0.424571633339, -0.0789999961853, -0.138182505965},
{0.423661530018, -0.121000006795, -0.132774427533}, {0.423661530018, -0.0789999961853, -0.132774427533}, {0.423434525728, -0.121000006795, -0.124243661761}, {0.423434525728, -0.0789999961853, -0.124243661761}, {0.424045294523, -0.121000006795, -0.118805244565}, {0.424045294523, -0.0789999961853, -0.118805244565}, {0.427099227905, -0.121000006795, -0.108729310334}, {0.427099227905, -0.0789999961853, -0.108729310334},
{0.42954236269, -0.121000006795, -0.104091793299}, {0.42954236269, -0.0789999961853, -0.104091793299}, {0.436260998249, -0.121000006795, -0.0956176742911}, {0.436260998249, -0.0789999961853, -0.0956176742911}, {0.442551344633, -0.121000006795, -0.0903496593237}, {0.442551344633, -0.0789999961853, -0.0903496593237}, {0.449433326721, -0.121000006795, -0.0864559113979}, {0.449433326721, -0.0789999961853, -0.0864559113979},
{0.456906825304, -0.121000006795, -0.0839364230633}, {0.456906825304, -0.0789999961853, -0.0839364230633}, {0.467791736126, -0.121000006795, -0.0827148407698}, {0.467791736126, -0.0789999961853, -0.0827148407698}, {0.476867049932, -0.121000006795, -0.0833610221744}, {0.476867049932, -0.0789999961853, -0.0833610221744}, {0.482396483421, -0.121000006795, -0.0845097899437}, {0.482396483421, -0.0789999961853, -0.0845097899437},
{0.4922054708, -0.121000006795, -0.0885304510593}, {0.4922054708, -0.0789999961853, -0.0885304510593}, {0.498468518257, -0.121000006795, -0.0930536985397}, {0.498468518257, -0.0789999961853, -0.0930536985397}, {0.505232155323, -0.121000006795, -0.100882664323}, {0.505232155323, -0.0789999961853, -0.100882664323}, {0.509762525558, -0.121000006795, -0.110400401056}, {0.509762525558, -0.0789999961853, -0.110400401056},
{0.512027680874, -0.121000006795, -0.121600821614}, {0.512027680874, -0.0789999961853, -0.121600821614}, {0.512310802937, -0.121000006795, -0.12783202529}, {0.512310802937, -0.0789999961853, -0.12783202529}, {0.512310802937, -0.121000006795, -0.169616699219}, {0.512310802937, -0.0789999961853, -0.169616699219}, {0.480352789164, -0.121000006795, -0.169616699219}, {0.480352789164, -0.0789999961853, -0.169616699219},
{0.480352789164, -0.121000006795, -0.130139157176}, {0.480352789164, -0.0789999961853, -0.130139157176}, {0.478755563498, -0.121000006795, -0.122102886438}, {0.478755563498, -0.0789999961853, -0.122102886438}, {0.47650706768, -0.121000006795, -0.118778459728}, {0.47650706768, -0.0789999961853, -0.118778459728}, {0.472150146961, -0.121000006795, -0.115950539708}, {0.472150146961, -0.0789999961853, -0.115950539708},
{0.46821898222, -0.121000006795, -0.115356445312}, {0.46821898222, -0.0789999961853, -0.115356445312}, {0.462531805038, -0.121000006795, -0.116747900844}, {0.462531805038, -0.0789999961853, -0.116747900844}, {0.458959639072, -0.121000006795, -0.11960413307}, {0.458959639072, -0.0789999961853, -0.11960413307}, {0.456024497747, -0.121000006795, -0.125492542982}, {0.456024497747, -0.0789999961853, -0.125492542982},
{0.455907762051, -0.121000006795, -0.129332199693}, {0.455907762051, -0.0789999961853, -0.129332199693}, {0.457426100969, -0.121000006795, -0.134181067348}, {0.457426100969, -0.0789999961853, -0.134181067348}, {0.461990207434, -0.121000006795, -0.138585984707}, {0.461990207434, -0.0789999961853, -0.138585984707}, {0.466842532158, -0.121000006795, -0.139860138297}, {0.466842532158, -0.0789999961853, -0.139860138297},
{0.470140874386, -0.121000006795, -0.139670029283}, {0.470140874386, -0.0789999961853, -0.139670029283}, {0.67962038517, -0.121000006795, -0.137658685446}, {0.67962038517, -0.0789999961853, -0.137658685446}, {0.67962038517, -0.121000006795, -0.170727536082}, {0.67962038517, -0.0789999961853, -0.170727536082}, {0.673977673054, -0.121000006795, -0.171374738216}, {0.673977673054, -0.0789999961853, -0.171374738216},
{0.666678607464, -0.121000006795, -0.171111807227}, {0.666678607464, -0.0789999961853, -0.171111807227}, {0.661217927933, -0.121000006795, -0.170213848352}, {0.661217927933, -0.0789999961853, -0.170213848352}, {0.651206791401, -0.121000006795, -0.16662196815}, {0.651206791401, -0.0789999961853, -0.16662196815}, {0.646656215191, -0.121000006795, -0.163928046823}, {0.646656215191, -0.0789999961853, -0.163928046823},
{0.638503134251, -0.121000006795, -0.156781107187}, {0.638503134251, -0.0789999961853, -0.156781107187}, {0.632435679436, -0.121000006795, -0.148088529706}, {0.632435679436, -0.0789999961853, -0.148088529706}, {0.629477798939, -0.121000006795, -0.140772774816}, {0.629477798939, -0.0789999961853, -0.140772774816}, {0.62826436758, -0.121000006795, -0.135516390204}, {0.62826436758, -0.0789999961853, -0.135516390204},
{0.627658188343, -0.121000006795, -0.124243661761}, {0.627658188343, -0.0789999961853, -0.124243661761}, {0.628268897533, -0.121000006795, -0.118805244565}, {0.628268897533, -0.0789999961853, -0.118805244565}, {0.630330324173, -0.121000006795, -0.111148186028}, {0.630330324173, -0.0789999961853, -0.111148186028}, {0.632468104362, -0.121000006795, -0.106377184391}, {0.632468104362, -0.0789999961853, -0.106377184391},
{0.636819899082, -0.121000006795, -0.0997212380171}, {0.636819899082, -0.0789999961853, -0.0997212380171}, {0.644612491131, -0.121000006795, -0.0919529646635}, {0.644612491131, -0.0789999961853, -0.0919529646635}, {0.651297211647, -0.121000006795, -0.0876011326909}, {0.651297211647, -0.0789999961853, -0.0876011326909}, {0.658573567867, -0.121000006795, -0.0846235603094}, {0.658573567867, -0.0789999961853, -0.0846235603094},
{0.663753092289, -0.121000006795, -0.0834019929171}, {0.663753092289, -0.0789999961853, -0.0834019929171}, {0.672015368938, -0.121000006795, -0.0827148407698}, {0.672015368938, -0.0789999961853, -0.0827148407698}, {0.681090712547, -0.121000006795, -0.0833610221744}, {0.681090712547, -0.0789999961853, -0.0833610221744}, {0.686620116234, -0.121000006795, -0.0845097899437}, {0.686620116234, -0.0789999961853, -0.0845097899437},
{0.694133102894, -0.121000006795, -0.0873098894954}, {0.694133102894, -0.0789999961853, -0.0873098894954}, {0.702692210674, -0.121000006795, -0.0930536985397}, {0.702692210674, -0.0789999961853, -0.0930536985397}, {0.70945584774, -0.121000006795, -0.100882664323}, {0.70945584774, -0.0789999961853, -0.100882664323}, {0.713986158371, -0.121000006795, -0.110400401056}, {0.713986158371, -0.0789999961853, -0.110400401056},
{0.71589744091, -0.121000006795, -0.11864297092}, {0.71589744091, -0.0789999961853, -0.11864297092}, {0.716534435749, -0.121000006795, -0.12783202529}, {0.716534435749, -0.0789999961853, -0.12783202529}, {0.716534435749, -0.121000006795, -0.169616699219}, {0.716534435749, -0.0789999961853, -0.169616699219}, {0.684576392174, -0.121000006795, -0.169616699219}, {0.684576392174, -0.0789999961853, -0.169616699219},
{0.684576392174, -0.121000006795, -0.130139157176}, {0.684576392174, -0.0789999961853, -0.130139157176}, {0.682979166508, -0.121000006795, -0.122102886438}, {0.682979166508, -0.0789999961853, -0.122102886438}, {0.680730640888, -0.121000006795, -0.118778459728}, {0.680730640888, -0.0789999961853, -0.118778459728}, {0.674097001553, -0.121000006795, -0.11545149982}, {0.674097001553, -0.0789999961853, -0.11545149982},
{0.666755437851, -0.121000006795, -0.116747900844}, {0.666755437851, -0.0789999961853, -0.116747900844}, {0.661443889141, -0.121000006795, -0.12205940485}, {0.661443889141, -0.0789999961853, -0.12205940485}, {0.660139381886, -0.121000006795, -0.126227706671}, {0.660139381886, -0.0789999961853, -0.126227706671}, {0.660367965698, -0.121000006795, -0.13082882762}, {0.660367965698, -0.0789999961853, -0.13082882762},
{0.661649703979, -0.121000006795, -0.134181067348}, {0.661649703979, -0.0789999961853, -0.134181067348}, {0.666843295097, -0.121000006795, -0.138889357448}, {0.666843295097, -0.0789999961853, -0.138889357448}, {0.674364507198, -0.121000006795, -0.139670029283}, {0.674364507198, -0.0789999961853, -0.139670029283}, {0.781903088093, -0.121000006795, -0.0835693329573}, {0.781903088093, -0.0789999961853, -0.0835693329573},
{0.781903088093, -0.121000006795, -0.117749020457}, {0.781903088093, -0.0789999961853, -0.117749020457}, {0.777575492859, -0.121000006795, -0.116047114134}, {0.777575492859, -0.0789999961853, -0.116047114134}, {0.772277653217, -0.121000006795, -0.116579025984}, {0.772277653217, -0.0789999961853, -0.116579025984}, {0.769647240639, -0.121000006795, -0.118708692491}, {0.769647240639, -0.0789999961853, -0.118708692491},
{0.767584443092, -0.121000006795, -0.123756766319}, {0.767584443092, -0.0789999961853, -0.123756766319}, {0.767120361328, -0.121000006795, -0.12919922173}, {0.767120361328, -0.0789999961853, -0.12919922173}, {0.767120361328, -0.121000006795, -0.169616699219}, {0.767120361328, -0.0789999961853, -0.169616699219}, {0.735162377357, -0.121000006795, -0.169616699219}, {0.735162377357, -0.0789999961853, -0.169616699219},
{0.735162377357, -0.121000006795, -0.123046875}, {0.735162377357, -0.0789999961853, -0.123046875}, {0.736117005348, -0.121000006795, -0.112400606275}, {0.736117005348, -0.0789999961853, -0.112400606275}, {0.73898088932, -0.121000006795, -0.103178143501}, {0.73898088932, -0.0789999961853, -0.103178143501}, {0.741128802299, -0.121000006795, -0.0991008579731}, {0.741128802299, -0.0789999961853, -0.0991008579731},
{0.746836543083, -0.121000006795, -0.0920217260718}, {0.746836543083, -0.0789999961853, -0.0920217260718}, {0.752089381218, -0.121000006795, -0.0879125744104}, {0.752089381218, -0.0789999961853, -0.0879125744104}, {0.755990743637, -0.121000006795, -0.0858253985643}, {0.755990743637, -0.0789999961853, -0.0858253985643}, {0.764752089977, -0.121000006795, -0.083216406405}, {0.764752089977, -0.0789999961853, -0.083216406405},
{0.769612073898, -0.121000006795, -0.082694619894}, {0.769612073898, -0.0789999961853, -0.082694619894}, {0.843768298626, -0.121000006795, -0.052978515625}, {0.843768298626, -0.0789999961853, -0.052978515625}, {0.875726342201, -0.121000006795, -0.052978515625}, {0.875726342201, -0.0789999961853, -0.052978515625}, {0.875726342201, -0.121000006795, -0.123986817896}, {0.875726342201, -0.0789999961853, -0.123986817896},
{0.874755561352, -0.121000006795, -0.135340943933}, {0.874755561352, -0.0789999961853, -0.135340943933}, {0.87275326252, -0.121000006795, -0.142954006791}, {0.87275326252, -0.0789999961853, -0.142954006791}, {0.868384718895, -0.121000006795, -0.15190140903}, {0.868384718895, -0.0789999961853, -0.15190140903}, {0.864546179771, -0.121000006795, -0.156933322549}, {0.864546179771, -0.0789999961853, -0.156933322549},
{0.858181536198, -0.121000006795, -0.162654861808}, {0.858181536198, -0.0789999961853, -0.162654861808}, {0.854480445385, -0.121000006795, -0.165051490068}, {0.854480445385, -0.0789999961853, -0.165051490068}, {0.846225619316, -0.121000006795, -0.16884817183}, {0.846225619316, -0.0789999961853, -0.16884817183}, {0.839091360569, -0.121000006795, -0.17070633173}, {0.839091360569, -0.0789999961853, -0.17070633173},
{0.833274722099, -0.121000006795, -0.171300917864}, {0.833274722099, -0.0789999961853, -0.171300917864}, {0.823329269886, -0.121000006795, -0.170643076301}, {0.823329269886, -0.0789999961853, -0.170643076301}, {0.815490067005, -0.121000006795, -0.168595299125}, {0.815490067005, -0.0789999961853, -0.168595299125}, {0.808288156986, -0.121000006795, -0.165182352066}, {0.808288156986, -0.0789999961853, -0.165182352066},
{0.803840756416, -0.121000006795, -0.16214863956}, {0.803840756416, -0.0789999961853, -0.16214863956}, {0.797742545605, -0.121000006795, -0.156502008438}, {0.797742545605, -0.0789999961853, -0.156502008438}, {0.79433876276, -0.121000006795, -0.152283161879}, {0.79433876276, -0.0789999961853, -0.152283161879}, {0.790393412113, -0.121000006795, -0.145439103246}, {0.790393412113, -0.0789999961853, -0.145439103246},
{0.788536727428, -0.121000006795, -0.140532612801}, {0.788536727428, -0.0789999961853, -0.140532612801}, {0.78691226244, -0.121000006795, -0.132657125592}, {0.78691226244, -0.0789999961853, -0.132657125592}, {0.786679625511, -0.121000006795, -0.124317996204}, {0.786679625511, -0.0789999961853, -0.124317996204}, {0.788524150848, -0.121000006795, -0.113914422691}, {0.788524150848, -0.0789999961853, -0.113914422691},
{0.790368616581, -0.121000006795, -0.109058484435}, {0.790368616581, -0.0789999961853, -0.109058484435}, {0.795902132988, -0.121000006795, -0.100038297474}, {0.795902132988, -0.0789999961853, -0.100038297474}, {0.801617562771, -0.121000006795, -0.093927398324}, {0.801617562771, -0.0789999961853, -0.093927398324}, {0.808036863804, -0.121000006795, -0.0890219062567}, {0.808036863804, -0.0789999961853, -0.0890219062567},
{0.812599480152, -0.121000006795, -0.0865302234888}, {0.812599480152, -0.0789999961853, -0.0865302234888}, {0.819868326187, -0.121000006795, -0.0839606821537}, {0.819868326187, -0.0789999961853, -0.0839606821537}, {0.830352783203, -0.121000006795, -0.0827148407698}, {0.830352783203, -0.0789999961853, -0.0827148407698}, {0.838897705078, -0.121000006795, -0.0832275375724}, {0.838897705078, -0.0789999961853, -0.0832275375724},
{0.838897705078, -0.121000006795, -0.118432618678}, {0.838897705078, -0.0789999961853, -0.118432618678}, {0.832245647907, -0.121000006795, -0.115429252386}, {0.832245647907, -0.0789999961853, -0.115429252386}, {0.827426254749, -0.121000006795, -0.115899972618}, {0.827426254749, -0.0789999961853, -0.115899972618}, {0.82362818718, -0.121000006795, -0.117987163365}, {0.82362818718, -0.0789999961853, -0.117987163365},
{0.821060955524, -0.121000006795, -0.120769068599}, {0.821060955524, -0.0789999961853, -0.120769068599}, {0.819174587727, -0.121000006795, -0.125462219119}, {0.819174587727, -0.0789999961853, -0.125462219119}, {0.819335997105, -0.121000006795, -0.130667030811}, {0.819335997105, -0.0789999961853, -0.130667030811}, {0.820749163628, -0.121000006795, -0.133953526616}, {0.820749163628, -0.0789999961853, -0.133953526616},
{0.825703561306, -0.121000006795, -0.138468191028}, {0.825703561306, -0.0789999961853, -0.138468191028}, {0.831463634968, -0.121000006795, -0.139794915915}, {0.831463634968, -0.0789999961853, -0.139794915915}, {0.837870836258, -0.121000006795, -0.138185039163}, {0.837870836258, -0.0789999961853, -0.138185039163}, {0.840200722218, -0.121000006795, -0.136172682047}, {0.840200722218, -0.0789999961853, -0.136172682047},
{0.843113183975, -0.121000006795, -0.129733145237}, {0.843113183975, -0.0789999961853, -0.129733145237}, {0.843768298626, -0.121000006795, -0.122790530324}, {0.843768298626, -0.0789999961853, -0.122790530324}, {0.938427865505, -0.121000006795, -0.0829388201237}, {0.938427865505, -0.0789999961853, -0.0829388201237}, {0.946141064167, -0.121000006795, -0.0845633670688}, {0.946141064167, -0.0789999961853, -0.0845633670688},
{0.950974702835, -0.121000006795, -0.0864199995995}, {0.950974702835, -0.0789999961853, -0.0864199995995}, {0.957762658596, -0.121000006795, -0.0903653204441}, {0.957762658596, -0.0789999961853, -0.0903653204441}, {0.961979448795, -0.121000006795, -0.093769133091}, {0.961979448795, -0.0789999961853, -0.093769133091}, {0.967684388161, -0.121000006795, -0.0998228862882}, {0.967684388161, -0.0789999961853, -0.0998228862882},
{0.973217844963, -0.121000006795, -0.108802638948}, {0.973217844963, -0.0789999961853, -0.108802638948}, {0.976292014122, -0.121000006795, -0.118769355118}, {0.976292014122, -0.0789999961853, -0.118769355118}, {0.976906895638, -0.121000006795, -0.124122828245}, {0.976906895638, -0.0789999961853, -0.124122828245}, {0.976672232151, -0.121000006795, -0.132441744208}, {0.976672232151, -0.0789999961853, -0.132441744208},
{0.974180519581, -0.121000006795, -0.142764419317}, {0.974180519581, -0.0789999961853, -0.142764419317}, {0.969197154045, -0.121000006795, -0.152051582932}, {0.969197154045, -0.0789999961853, -0.152051582932}, {0.961780786514, -0.121000006795, -0.160258740187}, {0.961780786514, -0.0789999961853, -0.160258740187}, {0.955261409283, -0.121000006795, -0.165100514889}, {0.955261409283, -0.0789999961853, -0.165100514889},
{0.945662796497, -0.121000006795, -0.169404342771}, {0.945662796497, -0.0789999961853, -0.169404342771}, {0.935028672218, -0.121000006795, -0.171248853207}, {0.935028672218, -0.0789999961853, -0.171248853207}, {0.926630318165, -0.121000006795, -0.171018272638}, {0.926630318165, -0.0789999961853, -0.171018272638}, {0.921307146549, -0.121000006795, -0.17009600997}, {0.921307146549, -0.0789999961853, -0.17009600997},
{0.911425411701, -0.121000006795, -0.1664070189}, {0.911425411701, -0.0789999961853, -0.1664070189}, {0.904682993889, -0.121000006795, -0.162026315928}, {0.904682993889, -0.0789999961853, -0.162026315928}, {0.896768987179, -0.121000006795, -0.15418933332}, {0.896768987179, -0.0789999961853, -0.15418933332}, {0.891162753105, -0.121000006795, -0.145140811801}, {0.891162753105, -0.0789999961853, -0.145140811801},
{0.888593256474, -0.121000006795, -0.137696102262}, {0.888593256474, -0.0789999961853, -0.137696102262}, {0.887658834457, -0.121000006795, -0.132419496775}, {0.887658834457, -0.0789999961853, -0.132419496775}, {0.887425243855, -0.121000006795, -0.124048501253}, {0.887425243855, -0.0789999961853, -0.124048501253}, {0.888593256474, -0.121000006795, -0.115942455828}, {0.888593256474, -0.0789999961853, -0.115942455828},
{0.891162753105, -0.121000006795, -0.108473487198}, {0.891162753105, -0.0789999961853, -0.108473487198}, {0.896768987179, -0.121000006795, -0.0995058640838}, {0.896768987179, -0.0789999961853, -0.0995058640838}, {0.902567446232, -0.121000006795, -0.0935507118702}, {0.902567446232, -0.0789999961853, -0.0935507118702}, {0.90690767765, -0.121000006795, -0.0902136489749}, {0.90690767765, -0.0789999961853, -0.0902136489749},
{0.916461825371, -0.121000006795, -0.0853597298265}, {0.916461825371, -0.0789999961853, -0.0853597298265}, {0.927180826664, -0.121000006795, -0.0829327702522}, {0.927180826664, -0.0789999961853, -0.0829327702522}, {0.930581688881, -0.121000006795, -0.114249147475}, {0.930581688881, -0.0789999961853, -0.114249147475}, {0.925145328045, -0.121000006795, -0.116384856403}, {0.925145328045, -0.0789999961853, -0.116384856403},
{0.921177268028, -0.121000006795, -0.120999135077}, {0.921177268028, -0.0789999961853, -0.120999135077}, {0.919902980328, -0.121000006795, -0.128571256995}, {0.919902980328, -0.0789999961853, -0.128571256995}, {0.921176970005, -0.121000006795, -0.132915496826}, {0.921176970005, -0.0789999961853, -0.132915496826}, {0.925797581673, -0.121000006795, -0.13799290359}, {0.925797581673, -0.0789999961853, -0.13799290359},
{0.929868757725, -0.121000006795, -0.139594689012}, {0.929868757725, -0.0789999961853, -0.139594689012}, {0.936527788639, -0.121000006795, -0.138994038105}, {0.936527788639, -0.0789999961853, -0.138994038105}, {0.940277338028, -0.121000006795, -0.136591345072}, {0.940277338028, -0.0789999961853, -0.136591345072}, {0.94275188446, -0.121000006795, -0.133575841784}, {0.94275188446, -0.0789999961853, -0.133575841784},
{0.944426000118, -0.121000006795, -0.128571271896}, {0.944426000118, -0.0789999961853, -0.128571271896}, {0.943982243538, -0.121000006795, -0.12308935076}, {0.943982243538, -0.0789999961853, -0.12308935076}, {0.941455304623, -0.121000006795, -0.118495330215}, {0.941455304623, -0.0789999961853, -0.118495330215}, {0.938561856747, -0.121000006795, -0.115962177515}, {0.938561856747, -0.0789999961853, -0.115962177515},
{0.933688282967, -0.121000006795, -0.114249154925}, {0.933688282967, -0.0789999961853, -0.114249154925}, {0.930581688881, -0.121000006795, -0.114249147475}, {0.930581688881, -0.0789999961853, -0.114249147475}, {0.927180826664, -0.121000006795, -0.0829327702522}, {0.927180826664, -0.0789999961853, -0.0829327702522}
},
{
{0, 2}, {1, 3}, {2, 4}, {3, 5}, {4, 6}, {5, 7}, {6, 8}, {7, 9}, {8, 10}, {9, 11}, {10, 0}, {11, 1}, {2, 3}, {4, 5}, {6, 7}, {10, 11}, {0, 1}, {12, 14}, {13, 15}, {14, 16}, {15, 17}, {16, 18}, {17, 19}, {18, 12}, {19, 13}, {14, 15}, {16, 17}, {18, 19}, {12, 13}, {20, 22}, {21, 23}, {22, 24},
{23, 25}, {24, 26}, {25, 27}, {26, 20}, {27, 21}, {22, 23}, {24, 25}, {26, 27}, {20, 21}, {28, 30}, {29, 31}, {30, 32}, {31, 33}, {32, 34}, {33, 35}, {34, 36}, {35, 37}, {36, 38}, {37, 39}, {38, 28}, {39, 29}, {30, 31}, {32, 33}, {34, 35}, {36, 37}, {38, 39}, {28, 29}, {40, 42}, {41, 43}, {42, 44}, {43, 45}, {44, 46},
{45, 47}, {46, 40}, {47, 41}, {42, 43}, {44, 45}, {46, 47}, {40, 41}, {48, 50}, {49, 51}, {50, 52}, {51, 53}, {52, 54}, {53, 55}, {54, 48}, {55, 49}, {50, 51}, {52, 53}, {54, 55}, {48, 49}, {56, 58}, {57, 59}, {58, 60}, {59, 61}, {60, 62}, {61, 63}, {62, 56}, {63, 57}, {58, 59}, {60, 61}, {62, 63}, {56, 57}, {64, 66},
{65, 67}, {66, 68}, {67, 69}, {68, 70}, {69, 71}, {70, 64}, {71, 65}, {66, 67}, {68, 69}, {70, 71}, {64, 65}, {72, 74}, {73, 75}, {74, 76}, {75, 77}, {76, 78}, {77, 79}, {78, 80}, {79, 81}, {80, 82}, {81, 83}, {82, 84}, {83, 85}, {84, 86}, {85, 87}, {86, 88}, {87, 89}, {88, 90}, {89, 91}, {90, 92}, {91, 93}, {92, 94},
{93, 95}, {94, 72}, {95, 73}, {74, 75}, {76, 77}, {78, 79}, {80, 81}, {82, 83}, {84, 85}, {86, 87}, {88, 89}, {90, 91}, {92, 93}, {94, 95}, {72, 73}, {96, 98}, {97, 99}, {98, 100}, {99, 101}, {100, 102}, {101, 103}, {102, 96}, {103, 97}, {98, 99}, {100, 101}, {102, 103}, {96, 97}, {104, 106}, {105, 107}, {106, 108}, {107, 109}, {108, 110},
{109, 111}, {110, 104}, {111, 105}, {106, 107}, {108, 109}, {110, 111}, {104, 105}, {112, 114}, {113, 115}, {114, 116}, {115, 117}, {116, 118}, {117, 119}, {118, 112}, {119, 113}, {114, 115}, {116, 117}, {118, 119}, {112, 113}, {120, 122}, {121, 123}, {122, 124}, {123, 125}, {124, 126}, {125, 127}, {126, 120}, {127, 121}, {122, 123}, {124, 125}, {126, 127}, {120, 121}, {128, 130},
{129, 131}, {130, 132}, {131, 133}, {132, 134}, {133, 135}, {134, 136}, {135, 137}, {136, 138}, {137, 139}, {138, 140}, {139, 141}, {140, 142}, {141, 143}, {142, 144}, {143, 145}, {144, 146}, {145, 147}, {146, 148}, {147, 149}, {148, 150}, {149, 151}, {150, 152}, {151, 153}, {152, 154}, {153, 155}, {154, 156}, {155, 157}, {156, 158}, {157, 159}, {158, 160}, {159, 161}, {160, 162},
{161, 163}, {162, 164}, {163, 165}, {164, 166}, {165, 167}, {166, 168}, {167, 169}, {168, 170}, {169, 171}, {170, 172}, {171, 173}, {172, 174}, {173, 175}, {174, 176}, {175, 177}, {176, 178}, {177, 179}, {178, 180}, {179, 181}, {180, 182}, {181, 183}, {182, 184}, {183, 185}, {184, 186}, {185, 187}, {186, 188}, {187, 189}, {188, 190}, {189, 191}, {190, 192}, {191, 193}, {192, 194},
{193, 195}, {194, 196}, {195, 197}, {196, 198}, {197, 199}, {198, 200}, {199, 201}, {200, 202}, {201, 203}, {202, 204}, {203, 205}, {204, 206}, {205, 207}, {206, 208}, {207, 209}, {208, 210}, {209, 211}, {210, 212}, {211, 213}, {212, 214}, {213, 215}, {214, 216}, {215, 217}, {216, 218}, {217, 219}, {218, 220}, {219, 221}, {220, 222}, {221, 223}, {222, 224}, {223, 225}, {224, 226},
{225, 227}, {226, 228}, {227, 229}, {228, 230}, {229, 231}, {230, 232}, {231, 233}, {232, 234}, {233, 235}, {234, 236}, {235, 237}, {236, 238}, {237, 239}, {238, 240}, {239, 241}, {240, 242}, {241, 243}, {242, 244}, {243, 245}, {244, 246}, {245, 247}, {246, 248}, {247, 249}, {248, 250}, {249, 251}, {250, 252}, {251, 253}, {252, 254}, {253, 255}, {254, 256}, {255, 257}, {256, 258},
{257, 259}, {258, 260}, {259, 261}, {260, 262}, {261, 263}, {262, 128}, {263, 129}, {130, 131}, {218, 219}, {220, 221}, {128, 129}, {264, 266}, {265, 267}, {266, 268}, {267, 269}, {268, 270}, {269, 271}, {270, 272}, {271, 273}, {272, 274}, {273, 275}, {274, 276}, {275, 277}, {276, 278}, {277, 279}, {278, 280}, {279, 281}, {280, 282}, {281, 283}, {282, 284}, {283, 285}, {284, 286},
{285, 287}, {286, 288}, {287, 289}, {288, 290}, {289, 291}, {290, 292}, {291, 293}, {292, 294}, {293, 295}, {294, 296}, {295, 297}, {296, 298}, {297, 299}, {298, 300}, {299, 301}, {300, 302}, {301, 303}, {302, 304}, {303, 305}, {304, 306}, {305, 307}, {306, 308}, {307, 309}, {308, 310}, {309, 311}, {310, 312}, {311, 313}, {312, 314}, {313, 315}, {314, 316}, {315, 317}, {316, 318},
{317, 319}, {318, 320}, {319, 321}, {320, 322}, {321, 323}, {322, 324}, {323, 325}, {324, 326}, {325, 327}, {326, 328}, {327, 329}, {328, 330}, {329, 331}, {332, 334}, {333, 335}, {334, 336}, {335, 337}, {336, 338}, {337, 339}, {338, 340}, {339, 341}, {340, 342}, {341, 343}, {342, 344}, {343, 345}, {344, 346}, {345, 347}, {346, 348}, {347, 349}, {348, 350}, {349, 351}, {350, 352},
{351, 353}, {352, 354}, {353, 355}, {354, 356}, {355, 357}, {356, 358}, {357, 359}, {358, 360}, {359, 361}, {360, 362}, {361, 363}, {364, 264}, {365, 265}, {366, 368}, {367, 369}, {368, 370}, {369, 371}, {370, 372}, {371, 373}, {372, 374}, {373, 375}, {374, 376}, {375, 377}, {376, 378}, {377, 379}, {378, 380}, {379, 381}, {380, 382}, {381, 383}, {382, 384}, {383, 385}, {384, 386},
{385, 387}, {386, 388}, {387, 389}, {388, 390}, {389, 391}, {390, 392}, {391, 393}, {392, 394}, {393, 395}, {394, 396}, {395, 397}, {396, 398}, {397, 399}, {398, 400}, {399, 401}, {400, 402}, {401, 403}, {402, 404}, {403, 405}, {404, 406}, {405, 407}, {406, 408}, {407, 409}, {408, 410}, {409, 411}, {410, 412}, {411, 413}, {412, 414}, {413, 415}, {414, 416}, {415, 417}, {416, 418},
{417, 419}, {418, 420}, {419, 421}, {420, 422}, {421, 423}, {422, 424}, {423, 425}, {424, 426}, {425, 427}, {426, 428}, {427, 429}, {428, 430}, {429, 431}, {430, 432}, {431, 433}, {432, 434}, {433, 435}, {434, 436}, {435, 437}, {436, 438}, {437, 439}, {438, 440}, {439, 441}, {440, 442}, {441, 443}, {442, 444}, {443, 445}, {444, 446}, {445, 447}, {446, 448}, {447, 449}, {448, 366},
{449, 367}, {368, 369}, {420, 421}, {422, 423}, {366, 367}, {450, 452}, {451, 453}, {452, 454}, {453, 455}, {454, 456}, {455, 457}, {456, 458}, {457, 459}, {458, 460}, {459, 461}, {460, 462}, {461, 463}, {462, 464}, {463, 465}, {464, 466}, {465, 467}, {466, 468}, {467, 469}, {468, 470}, {469, 471}, {470, 472}, {471, 473}, {472, 474}, {473, 475}, {474, 476}, {475, 477}, {476, 478},
{477, 479}, {478, 480}, {479, 481}, {480, 482}, {481, 483}, {482, 484}, {483, 485}, {484, 486}, {485, 487}, {486, 488}, {487, 489}, {488, 490}, {489, 491}, {490, 492}, {491, 493}, {492, 494}, {493, 495}, {494, 496}, {495, 497}, {496, 498}, {497, 499}, {498, 500}, {499, 501}, {500, 502}, {501, 503}, {502, 504}, {503, 505}, {504, 506}, {505, 507}, {506, 508}, {507, 509}, {508, 510},
{509, 511}, {510, 512}, {511, 513}, {512, 514}, {513, 515}, {514, 516}, {515, 517}, {516, 518}, {517, 519}, {518, 520}, {519, 521}, {520, 522}, {521, 523}, {522, 524}, {523, 525}, {524, 526}, {525, 527}, {526, 528}, {527, 529}, {528, 530}, {529, 531}, {530, 532}, {531, 533}, {532, 534}, {533, 535}, {534, 536}, {535, 537}, {536, 538}, {537, 539}, {538, 540}, {539, 541}, {540, 450},
{541, 451}, {452, 453}, {456, 457}, {458, 459}, {484, 485}, {486, 487}, {450, 451}, {544, 546}, {545, 547}, {546, 548}, {547, 549}, {548, 550}, {549, 551}, {550, 552}, {551, 553}, {552, 554}, {553, 555}, {554, 556}, {555, 557}, {556, 558}, {557, 559}, {558, 560}, {559, 561}, {562, 564}, {563, 565}, {564, 566}, {565, 567}, {566, 568}, {567, 569}, {568, 570}, {569, 571}, {570, 572},
{571, 573}, {572, 574}, {573, 575}, {574, 576}, {575, 577}, {576, 578}, {577, 579}, {578, 580}, {579, 581}, {580, 582}, {581, 583}, {582, 584}, {583, 585}, {584, 586}, {585, 587}, {586, 588}, {587, 589}, {588, 590}, {589, 591}, {590, 592}, {591, 593}, {592, 594}, {593, 595}, {594, 596}, {595, 597}, {596, 598}, {597, 599}, {598, 600}, {599, 601}, {600, 602}, {601, 603}, {602, 604},
{603, 605}, {604, 606}, {605, 607}, {606, 608}, {607, 609}, {608, 610}, {609, 611}, {610, 612}, {611, 613}, {612, 614}, {613, 615}, {614, 616}, {615, 617}, {616, 618}, {617, 619}, {618, 620}, {619, 621}, {620, 622}, {621, 623}, {622, 624}, {623, 625}, {624, 626}, {625, 627}, {626, 628}, {627, 629}, {628, 630}, {629, 631}, {630, 632}, {631, 633}, {632, 634}, {633, 635}, {634, 636},
{635, 637}, {636, 638}, {637, 639}, {638, 640}, {639, 641}, {640, 642}, {641, 643}, {642, 644}, {643, 645}, {644, 646}, {645, 647}, {646, 648}, {647, 649}, {648, 650}, {649, 651}, {650, 652}, {651, 653}, {652, 654}, {653, 655}, {654, 542}, {655, 543}, {546, 547}, {558, 559}, {564, 565}, {572, 573}, {574, 575}, {576, 577}, {578, 579}, {604, 605}, {640, 641}, {642, 643}, {650, 651},
{656, 658}, {657, 659}, {658, 660}, {659, 661}, {660, 662}, {661, 663}, {662, 664}, {663, 665}, {664, 666}, {665, 667}, {666, 668}, {667, 669}, {668, 670}, {669, 671}, {670, 672}, {671, 673}, {672, 674}, {673, 675}, {674, 676}, {675, 677}, {676, 678}, {677, 679}, {678, 680}, {679, 681}, {680, 682}, {681, 683}, {682, 684}, {683, 685}, {684, 686}, {685, 687}, {686, 688}, {687, 689},
{688, 656}, {689, 657}, {690, 692}, {691, 693}, {692, 694}, {693, 695}, {694, 696}, {695, 697}, {696, 698}, {697, 699}, {698, 700}, {699, 701}, {700, 702}, {701, 703}, {702, 704}, {703, 705}, {704, 706}, {705, 707}, {706, 708}, {707, 709}, {708, 710}, {709, 711}, {710, 712}, {711, 713}, {712, 714}, {713, 715}, {714, 716}, {715, 717}, {716, 718}, {717, 719}, {718, 720}, {719, 721},
{720, 722}, {721, 723}, {722, 724}, {723, 725}, {724, 726}, {725, 727}, {726, 728}, {727, 729}, {728, 730}, {729, 731}, {730, 732}, {731, 733}, {732, 734}, {733, 735}, {734, 736}, {735, 737}, {736, 738}, {737, 739}, {738, 740}, {739, 741}, {740, 690}, {741, 691}, {692, 693}, {718, 719}, {720, 721}, {690, 691}, {742, 744}, {743, 745}, {744, 746}, {745, 747}, {746, 748}, {747, 749},
{748, 750}, {749, 751}, {750, 752}, {751, 753}, {752, 754}, {753, 755}, {754, 756}, {755, 757}, {756, 758}, {757, 759}, {758, 760}, {759, 761}, {760, 762}, {761, 763}, {762, 764}, {763, 765}, {764, 766}, {765, 767}, {766, 768}, {767, 769}, {768, 770}, {769, 771}, {770, 772}, {771, 773}, {772, 774}, {773, 775}, {774, 776}, {775, 777}, {776, 778}, {777, 779}, {778, 780}, {779, 781},
{780, 782}, {781, 783}, {782, 784}, {783, 785}, {784, 786}, {785, 787}, {786, 788}, {787, 789}, {788, 790}, {789, 791}, {790, 792}, {791, 793}, {792, 794}, {793, 795}, {794, 796}, {795, 797}, {796, 742}, {797, 743}, {744, 745}, {758, 759}, {760, 761}, {742, 743}, {798, 800}, {799, 801}, {800, 802}, {801, 803}, {802, 804}, {803, 805}, {804, 806}, {805, 807}, {806, 808}, {807, 809},
{808, 810}, {809, 811}, {810, 812}, {811, 813}, {812, 814}, {813, 815}, {814, 816}, {815, 817}, {816, 818}, {817, 819}, {818, 820}, {819, 821}, {820, 822}, {821, 823}, {822, 824}, {823, 825}, {824, 826}, {825, 827}, {826, 828}, {827, 829}, {828, 830}, {829, 831}, {830, 832}, {831, 833}, {832, 834}, {833, 835}, {834, 836}, {835, 837}, {836, 838}, {837, 839}, {838, 840}, {839, 841},
{840, 842}, {841, 843}, {842, 844}, {843, 845}, {844, 846}, {845, 847}, {846, 848}, {847, 849}, {848, 850}, {849, 851}, {850, 852}, {851, 853}, {852, 854}, {853, 855}, {854, 856}, {855, 857}, {856, 858}, {857, 859}, {858, 860}, {859, 861}, {860, 862}, {861, 863}, {862, 864}, {863, 865}, {864, 866}, {865, 867}, {866, 868}, {867, 869}, {868, 870}, {869, 871}, {870, 872}, {871, 873},
{872, 874}, {873, 875}, {874, 876}, {875, 877}, {876, 798}, {877, 799}, {800, 801}, {850, 851}, {852, 853}, {798, 799}, {878, 880}, {879, 881}, {880, 882}, {881, 883}, {882, 884}, {883, 885}, {884, 886}, {885, 887}, {886, 888}, {887, 889}, {888, 890}, {889, 891}, {890, 892}, {891, 893}, {892, 894}, {893, 895}, {894, 896}, {895, 897}, {896, 898}, {897, 899}, {898, 900}, {899, 901},
{900, 902}, {901, 903}, {902, 904}, {903, 905}, {904, 906}, {905, 907}, {906, 908}, {907, 909}, {908, 910}, {909, 911}, {910, 912}, {911, 913}, {912, 914}, {913, 915}, {914, 916}, {915, 917}, {916, 918}, {917, 919}, {918, 920}, {919, 921}, {920, 922}, {921, 923}, {922, 924}, {923, 925}, {924, 926}, {925, 927}, {926, 928}, {927, 929}, {928, 930}, {929, 931}, {930, 932}, {931, 933},
{932, 934}, {933, 935}, {934, 936}, {935, 937}, {936, 938}, {937, 939}, {938, 940}, {939, 941}, {940, 942}, {941, 943}, {942, 944}, {943, 945}, {944, 946}, {945, 947}, {946, 948}, {947, 949}, {948, 950}, {949, 951}, {950, 952}, {951, 953}, {952, 954}, {953, 955}, {954, 956}, {955, 957}, {956, 958}, {957, 959}, {958, 960}, {959, 961}, {960, 878}, {961, 879}, {880, 881}, {882, 883},
{884, 885}, {932, 933}, {934, 935}, {878, 879}, {962, 964}, {963, 965}, {964, 966}, {965, 967}, {966, 968}, {967, 969}, {968, 970}, {969, 971}, {970, 972}, {971, 973}, {972, 974}, {973, 975}, {974, 976}, {975, 977}, {976, 978}, {977, 979}, {978, 980}, {979, 981}, {980, 982}, {981, 983}, {982, 984}, {983, 985}, {984, 986}, {985, 987}, {986, 988}, {987, 989}, {988, 990}, {989, 991},
{990, 992}, {991, 993}, {992, 994}, {993, 995}, {994, 996}, {995, 997}, {996, 998}, {997, 999}, {998, 1000}, {999, 1001}, {1000, 1002}, {1001, 1003}, {1002, 1004}, {1003, 1005}, {1004, 1006}, {1005, 1007}, {1006, 1008}, {1007, 1009}, {1008, 1010}, {1009, 1011}, {1010, 1012}, {1011, 1013}, {1012, 1014}, {1013, 1015}, {1014, 1016}, {1015, 1017}, {1016, 1018}, {1017, 1019}, {1018, 1020}, {1019, 1021}, {1020, 1022}, {1021, 1023},
{1022, 1024}, {1023, 1025}, {1024, 1026}, {1025, 1027}, {1026, 1028}, {1027, 1029}, {1028, 1030}, {1029, 1031}, {1030, 1032}, {1031, 1033}, {1032, 1034}, {1033, 1035}, {1034, 1036}, {1035, 1037}, {1036, 1038}, {1037, 1039}, {1038, 1040}, {1039, 1041}, {1040, 1042}, {1041, 1043}, {1042, 1044}, {1043, 1045}, {1044, 962}, {1045, 963}, {964, 965}, {1018, 1019}, {1020, 1021}, {962, 963}, {1046, 1048}, {1047, 1049}, {1048, 1050}, {1049, 1051},
{1050, 1052}, {1051, 1053}, {1052, 1054}, {1053, 1055}, {1054, 1056}, {1055, 1057}, {1056, 1058}, {1057, 1059}, {1058, 1060}, {1059, 1061}, {1060, 1062}, {1061, 1063}, {1062, 1064}, {1063, 1065}, {1064, 1066}, {1065, 1067}, {1066, 1068}, {1067, 1069}, {1068, 1070}, {1069, 1071}, {1070, 1072}, {1071, 1073}, {1072, 1074}, {1073, 1075}, {1074, 1076}, {1075, 1077}, {1076, 1078}, {1077, 1079}, {1078, 1080}, {1079, 1081}, {1080, 1046}, {1081, 1047},
{1082, 1084}, {1083, 1085}, {1084, 1086}, {1085, 1087}, {1086, 1088}, {1087, 1089}, {1088, 1090}, {1089, 1091}, {1090, 1092}, {1091, 1093}, {1092, 1094}, {1093, 1095}, {1094, 1096}, {1095, 1097}, {1096, 1098}, {1097, 1099}, {1098, 1100}, {1099, 1101}, {1100, 1102}, {1101, 1103}, {1102, 1104}, {1103, 1105}, {1104, 1106}, {1105, 1107}, {1106, 1108}, {1107, 1109}, {1108, 1110}, {1109, 1111}, {1110, 1112}, {1111, 1113}, {1112, 1114}, {1113, 1115},
{1114, 1116}, {1115, 1117}, {1116, 1118}, {1117, 1119}, {1118, 1120}, {1119, 1121}, {1120, 1122}, {1121, 1123}, {1122, 1124}, {1123, 1125}, {1124, 1126}, {1125, 1127}, {1126, 1128}, {1127, 1129}, {1128, 1130}, {1129, 1131}, {1130, 1132}, {1131, 1133}, {1132, 1134}, {1133, 1135}, {1134, 1136}, {1135, 1137}, {1136, 1138}, {1137, 1139}, {1138, 1140}, {1139, 1141}, {1140, 1142}, {1141, 1143}, {1142, 1144}, {1143, 1145}, {1144, 1146}, {1145, 1147},
{1146, 1148}, {1147, 1149}, {1148, 1150}, {1149, 1151}, {1150, 1152}, {1151, 1153}, {1152, 1154}, {1153, 1155}, {1154, 1156}, {1155, 1157}, {1156, 1158}, {1157, 1159}, {1158, 1160}, {1159, 1161}, {1160, 1162}, {1161, 1163}, {1162, 1164}, {1163, 1165}, {1164, 1166}, {1165, 1167}, {1166, 1082}, {1167, 1083}, {1084, 1085}, {1138, 1139}, {1140, 1141}, {1082, 1083}, {1168, 1170}, {1169, 1171}, {1170, 1172}, {1171, 1173}, {1172, 1174}, {1173, 1175},
{1174, 1176}, {1175, 1177}, {1176, 1178}, {1177, 1179}, {1178, 1180}, {1179, 1181}, {1180, 1182}, {1181, 1183}, {1182, 1184}, {1183, 1185}, {1184, 1186}, {1185, 1187}, {1186, 1188}, {1187, 1189}, {1188, 1190}, {1189, 1191}, {1190, 1192}, {1191, 1193}, {1192, 1194}, {1193, 1195}, {1194, 1196}, {1195, 1197}, {1196, 1198}, {1197, 1199}, {1198, 1200}, {1199, 1201}, {1200, 1202}, {1201, 1203}, {1202, 1204}, {1203, 1205}, {1204, 1206}, {1205, 1207},
{1206, 1208}, {1207, 1209}, {1208, 1210}, {1209, 1211}, {1210, 1212}, {1211, 1213}, {1212, 1214}, {1213, 1215}, {1214, 1216}, {1215, 1217}, {1216, 1218}, {1217, 1219}, {1218, 1220}, {1219, 1221}, {1220, 1222}, {1221, 1223}, {1222, 1224}, {1223, 1225}, {1224, 1226}, {1225, 1227}, {1226, 1228}, {1227, 1229}, {1228, 1230}, {1229, 1231}, {1230, 1232}, {1231, 1233}, {1232, 1234}, {1233, 1235}, {1234, 1236}, {1235, 1237}, {1236, 1238}, {1237, 1239},
{1238, 1240}, {1239, 1241}, {1240, 1242}, {1241, 1243}, {1242, 1244}, {1243, 1245}, {1244, 1246}, {1245, 1247}, {1246, 1248}, {1247, 1249}, {1248, 1250}, {1249, 1251}, {1250, 1168}, {1251, 1169}, {1192, 1193}, {1218, 1219}, {1220, 1221}, {1226, 1227}, {1228, 1229}, {1230, 1231}, {1234, 1235}, {1236, 1237}, {1242, 1243}, {1244, 1245}, {1250, 1251}, {1168, 1169}, {1252, 1254}, {1253, 1255}, {1254, 1256}, {1255, 1257}, {1256, 1258}, {1257, 1259},
{1258, 1260}, {1259, 1261}, {1260, 1262}, {1261, 1263}, {1262, 1264}, {1263, 1265}, {1264, 1266}, {1265, 1267}, {1266, 1268}, {1267, 1269}, {1268, 1270}, {1269, 1271}, {1270, 1272}, {1271, 1273}, {1272, 1274}, {1273, 1275}, {1274, 1276}, {1275, 1277}, {1276, 1278}, {1277, 1279}, {1278, 1280}, {1279, 1281}, {1280, 1282}, {1281, 1283}, {1282, 1284}, {1283, 1285}, {1284, 1286}, {1285, 1287}, {1286, 1288}, {1287, 1289}, {1288, 1290}, {1289, 1291},
{1290, 1292}, {1291, 1293}, {1292, 1294}, {1293, 1295}, {1294, 1296}, {1295, 1297}, {1296, 1298}, {1297, 1299}, {1298, 1300}, {1299, 1301}, {1300, 1302}, {1301, 1303}, {1302, 1304}, {1303, 1305}, {1304, 1306}, {1305, 1307}, {1306, 1308}, {1307, 1309}, {1308, 1310}, {1309, 1311}, {1310, 1312}, {1311, 1313}, {1312, 1314}, {1313, 1315}, {1314, 1316}, {1315, 1317}, {1316, 1318}, {1317, 1319}, {1318, 1320}, {1319, 1321}, {1320, 1322}, {1321, 1323},
{1322, 1324}, {1323, 1325}, {1324, 1326}, {1325, 1327}, {1326, 1328}, {1327, 1329}, {1328, 1330}, {1329, 1331}, {1330, 1332}, {1331, 1333}, {1332, 1334}, {1333, 1335}, {1334, 1252}, {1335, 1253}, {1254, 1255}, {1308, 1309}, {1310, 1311}, {1252, 1253}, {1336, 1338}, {1337, 1339}, {1338, 1340}, {1339, 1341}, {1340, 1342}, {1341, 1343}, {1342, 1344}, {1343, 1345}, {1344, 1346}, {1345, 1347}, {1346, 1348}, {1347, 1349}, {1348, 1350}, {1349, 1351},
{1350, 1352}, {1351, 1353}, {1352, 1354}, {1353, 1355}, {1354, 1356}, {1355, 1357}, {1356, 1358}, {1357, 1359}, {1358, 1360}, {1359, 1361}, {1360, 1362}, {1361, 1363}, {1362, 1364}, {1363, 1365}, {1364, 1366}, {1365, 1367}, {1366, 1368}, {1367, 1369}, {1368, 1370}, {1369, 1371}, {1370, 1372}, {1371, 1373}, {1372, 1374}, {1373, 1375}, {1374, 1376}, {1375, 1377}, {1376, 1378}, {1377, 1379}, {1378, 1380}, {1379, 1381}, {1380, 1336}, {1381, 1337},
{1338, 1339}, {1364, 1365}, {1366, 1367}, {1336, 1337}, {1382, 1384}, {1383, 1385}, {1384, 1386}, {1385, 1387}, {1386, 1388}, {1387, 1389}, {1388, 1390}, {1389, 1391}, {1390, 1392}, {1391, 1393}, {1392, 1394}, {1393, 1395}, {1394, 1396}, {1395, 1397}, {1396, 1398}, {1397, 1399}, {1398, 1400}, {1399, 1401}, {1400, 1402}, {1401, 1403}, {1402, 1404}, {1403, 1405}, {1404, 1406}, {1405, 1407}, {1406, 1408}, {1407, 1409}, {1408, 1410}, {1409, 1411},
{1410, 1412}, {1411, 1413}, {1412, 1414}, {1413, 1415}, {1414, 1382}, {1415, 1383}, {1416, 1418}, {1417, 1419}, {1418, 1420}, {1419, 1421}, {1420, 1422}, {1421, 1423}, {1422, 1424}, {1423, 1425}, {1424, 1426}, {1425, 1427}, {1426, 1428}, {1427, 1429}, {1428, 1430}, {1429, 1431}, {1430, 1432}, {1431, 1433}, {1432, 1434}, {1433, 1435}, {1434, 1436}, {1435, 1437}, {1436, 1438}, {1437, 1439}, {1438, 1440}, {1439, 1441}, {1440, 1442}, {1441, 1443},
{1442, 1444}, {1443, 1445}, {1444, 1446}, {1445, 1447}, {1446, 1448}, {1447, 1449}, {1448, 1450}, {1449, 1451}, {1450, 1452}, {1451, 1453}, {1452, 1454}, {1453, 1455}, {1454, 1456}, {1455, 1457}, {1456, 1458}, {1457, 1459}, {1458, 1460}, {1459, 1461}, {1460, 1462}, {1461, 1463}, {1462, 1464}, {1463, 1465}, {1464, 1466}, {1465, 1467}, {1466, 1468}, {1467, 1469}, {1468, 1470}, {1469, 1471}, {1470, 1472}, {1471, 1473}, {1472, 1474}, {1473, 1475},
{1474, 1476}, {1475, 1477}, {1476, 1478}, {1477, 1479}, {1478, 1480}, {1479, 1481}, {1482, 1484}, {1483, 1485}, {1484, 1486}, {1485, 1487}, {1486, 1488}, {1487, 1489}, {1488, 1490}, {1489, 1491}, {1490, 1492}, {1491, 1493}, {1492, 1494}, {1493, 1495}, {1494, 1496}, {1495, 1497}, {1496, 1498}, {1497, 1499}, {1498, 1500}, {1499, 1501}, {1500, 1502}, {1501, 1503}, {1502, 1504}, {1503, 1505}, {1504, 1506}, {1505, 1507}, {1506, 1508}, {1507, 1509},
{1508, 1510}, {1509, 1511}, {1510, 1512}, {1511, 1513}, {1514, 1416}, {1515, 1417}, {1516, 1518}, {1517, 1519}, {1518, 1520}, {1519, 1521}, {1520, 1522}, {1521, 1523}, {1522, 1524}, {1523, 1525}, {1524, 1526}, {1525, 1527}, {1526, 1528}, {1527, 1529}, {1528, 1530}, {1529, 1531}, {1530, 1532}, {1531, 1533}, {1532, 1534}, {1533, 1535}, {1534, 1536}, {1535, 1537}, {1536, 1538}, {1537, 1539}, {1538, 1540}, {1539, 1541}, {1540, 1542}, {1541, 1543},
{1542, 1544}, {1543, 1545}, {1544, 1546}, {1545, 1547}, {1546, 1548}, {1547, 1549}, {1548, 1550}, {1549, 1551}, {1550, 1516}, {1551, 1517}, {1518, 1519}, {1530, 1531}, {1532, 1533}, {1516, 1517}, {1552, 1554}, {1553, 1555}, {1554, 1556}, {1555, 1557}, {1556, 1558}, {1557, 1559}, {1558, 1560}, {1559, 1561}, {1560, 1562}, {1561, 1563}, {1562, 1564}, {1563, 1565}, {1564, 1566}, {1565, 1567}, {1566, 1568}, {1567, 1569}, {1568, 1570}, {1569, 1571},
{1570, 1572}, {1571, 1573}, {1572, 1574}, {1573, 1575}, {1574, 1576}, {1575, 1577}, {1576, 1578}, {1577, 1579}, {1578, 1580}, {1579, 1581}, {1580, 1582}, {1581, 1583}, {1582, 1584}, {1583, 1585}, {1584, 1586}, {1585, 1587}, {1586, 1588}, {1587, 1589}, {1588, 1590}, {1589, 1591}, {1590, 1592}, {1591, 1593}, {1592, 1594}, {1593, 1595}, {1594, 1596}, {1595, 1597}, {1596, 1598}, {1597, 1599}, {1598, 1600}, {1599, 1601}, {1600, 1602}, {1601, 1603},
{1602, 1604}, {1603, 1605}, {1604, 1606}, {1605, 1607}, {1606, 1608}, {1607, 1609}, {1608, 1610}, {1609, 1611}, {1610, 1612}, {1611, 1613}, {1612, 1614}, {1613, 1615}, {1614, 1616}, {1615, 1617}, {1616, 1618}, {1617, 1619}, {1618, 1620}, {1619, 1621}, {1620, 1622}, {1621, 1623}, {1622, 1624}, {1623, 1625}, {1624, 1626}, {1625, 1627}, {1626, 1628}, {1627, 1629}, {1628, 1630}, {1629, 1631}, {1630, 1632}, {1631, 1633}, {1632, 1634}, {1633, 1635},
{1634, 1636}, {1635, 1637}, {1636, 1638}, {1637, 1639}, {1638, 1640}, {1639, 1641}, {1640, 1642}, {1641, 1643}, {1642, 1644}, {1643, 1645}, {1644, 1646}, {1645, 1647}, {1646, 1648}, {1647, 1649}, {1648, 1650}, {1649, 1651}, {1650, 1652}, {1651, 1653}, {1652, 1654}, {1653, 1655}, {1654, 1656}, {1655, 1657}, {1656, 1658}, {1657, 1659}, {1658, 1660}, {1659, 1661}, {1660, 1662}, {1661, 1663}, {1662, 1664}, {1663, 1665}, {1664, 1666}, {1665, 1667},
{1666, 1552}, {1667, 1553}, {1554, 1555}, {1626, 1627}, {1628, 1629}, {1660, 1661}, {1662, 1663}, {1666, 1667}, {1552, 1553}, {1668, 1670}, {1669, 1671}, {1670, 1672}, {1671, 1673}, {1672, 1674}, {1673, 1675}, {1674, 1676}, {1675, 1677}, {1676, 1678}, {1677, 1679}, {1678, 1680}, {1679, 1681}, {1680, 1682}, {1681, 1683}, {1682, 1684}, {1683, 1685}, {1684, 1686}, {1685, 1687}, {1686, 1688}, {1687, 1689}, {1688, 1690}, {1689, 1691}, {1690, 1692},
{1691, 1693}, {1692, 1694}, {1693, 1695}, {1694, 1696}, {1695, 1697}, {1696, 1698}, {1697, 1699}, {1698, 1700}, {1699, 1701}, {1700, 1702}, {1701, 1703}, {1702, 1704}, {1703, 1705}, {1704, 1706}, {1705, 1707}, {1706, 1708}, {1707, 1709}, {1708, 1710}, {1709, 1711}, {1710, 1712}, {1711, 1713}, {1712, 1714}, {1713, 1715}, {1714, 1716}, {1715, 1717}, {1716, 1718}, {1717, 1719}, {1718, 1720}, {1719, 1721}, {1720, 1722}, {1721, 1723}, {1722, 1724},
{1723, 1725}, {1724, 1726}, {1725, 1727}, {1726, 1728}, {1727, 1729}, {1728, 1730}, {1729, 1731}, {1730, 1732}, {1731, 1733}, {1732, 1734}, {1733, 1735}, {1734, 1736}, {1735, 1737}, {1736, 1738}, {1737, 1739}, {1738, 1740}, {1739, 1741}, {1740, 1742}, {1741, 1743}, {1742, 1744}, {1743, 1745}, {1744, 1746}, {1745, 1747}, {1746, 1748}, {1747, 1749}, {1748, 1750}, {1749, 1751}, {1750, 1752}, {1751, 1753}, {1752, 1668}, {1753, 1669}, {1670, 1671},
{1724, 1725}, {1726, 1727}, {1668, 1669}, {1754, 1756}, {1755, 1757}, {1756, 1758}, {1757, 1759}, {1758, 1760}, {1759, 1761}, {1760, 1762}, {1761, 1763}, {1762, 1764}, {1763, 1765}, {1764, 1766}, {1765, 1767}, {1766, 1768}, {1767, 1769}, {1768, 1770}, {1769, 1771}, {1770, 1772}, {1771, 1773}, {1772, 1774}, {1773, 1775}, {1774, 1776}, {1775, 1777}, {1776, 1778}, {1777, 1779}, {1778, 1780}, {1779, 1781}, {1780, 1782}, {1781, 1783}, {1782, 1784},
{1783, 1785}, {1784, 1786}, {1785, 1787}, {1786, 1788}, {1787, 1789}, {1788, 1790}, {1789, 1791}, {1790, 1792}, {1791, 1793}, {1792, 1794}, {1793, 1795}, {1794, 1796}, {1795, 1797}, {1796, 1798}, {1797, 1799}, {1798, 1800}, {1799, 1801}, {1800, 1802}, {1801, 1803}, {1802, 1804}, {1803, 1805}, {1804, 1806}, {1805, 1807}, {1806, 1808}, {1807, 1809}, {1808, 1810}, {1809, 1811}, {1810, 1812}, {1811, 1813}, {1812, 1814}, {1813, 1815}, {1814, 1816},
{1815, 1817}, {1816, 1818}, {1817, 1819}, {1818, 1820}, {1819, 1821}, {1820, 1822}, {1821, 1823}, {1822, 1824}, {1823, 1825}, {1824, 1826}, {1825, 1827}, {1826, 1828}, {1827, 1829}, {1828, 1830}, {1829, 1831}, {1830, 1832}, {1831, 1833}, {1832, 1834}, {1833, 1835}, {1834, 1836}, {1835, 1837}, {1836, 1754}, {1837, 1755}, {1756, 1757}, {1812, 1813}, {1814, 1815}, {1754, 1755}, {1838, 1840}, {1839, 1841}, {1840, 1842}, {1841, 1843}, {1842, 1844},
{1843, 1845}, {1844, 1846}, {1845, 1847}, {1846, 1848}, {1847, 1849}, {1848, 1850}, {1849, 1851}, {1850, 1852}, {1851, 1853}, {1852, 1854}, {1853, 1855}, {1854, 1856}, {1855, 1857}, {1856, 1858}, {1857, 1859}, {1858, 1860}, {1859, 1861}, {1860, 1862}, {1861, 1863}, {1862, 1864}, {1863, 1865}, {1864, 1866}, {1865, 1867}, {1866, 1868}, {1867, 1869}, {1868, 1870}, {1869, 1871}, {1870, 1872}, {1871, 1873}, {1872, 1838}, {1873, 1839}, {1840, 1841},
{1852, 1853}, {1854, 1855}, {1838, 1839}, {1874, 1876}, {1875, 1877}, {1876, 1878}, {1877, 1879}, {1878, 1880}, {1879, 1881}, {1880, 1882}, {1881, 1883}, {1882, 1884}, {1883, 1885}, {1884, 1886}, {1885, 1887}, {1886, 1888}, {1887, 1889}, {1888, 1890}, {1889, 1891}, {1890, 1892}, {1891, 1893}, {1892, 1894}, {1893, 1895}, {1894, 1896}, {1895, 1897}, {1896, 1898}, {1897, 1899}, {1898, 1900}, {1899, 1901}, {1900, 1902}, {1901, 1903}, {1902, 1904},
{1903, 1905}, {1904, 1906}, {1905, 1907}, {1906, 1908}, {1907, 1909}, {1908, 1910}, {1909, 1911}, {1910, 1912}, {1911, 1913}, {1912, 1914}, {1913, 1915}, {1914, 1916}, {1915, 1917}, {1916, 1918}, {1917, 1919}, {1918, 1920}, {1919, 1921}, {1920, 1922}, {1921, 1923}, {1922, 1924}, {1923, 1925}, {1924, 1926}, {1925, 1927}, {1926, 1928}, {1927, 1929}, {1928, 1930}, {1929, 1931}, {1930, 1932}, {1931, 1933}, {1932, 1934}, {1933, 1935}, {1934, 1936},
{1935, 1937}, {1936, 1938}, {1937, 1939}, {1938, 1940}, {1939, 1941}, {1940, 1942}, {1941, 1943}, {1942, 1944}, {1943, 1945}, {1944, 1946}, {1945, 1947}, {1946, 1948}, {1947, 1949}, {1948, 1950}, {1949, 1951}, {1950, 1952}, {1951, 1953}, {1952, 1954}, {1953, 1955}, {1954, 1956}, {1955, 1957}, {1956, 1958}, {1957, 1959}, {1958, 1960}, {1959, 1961}, {1960, 1962}, {1961, 1963}, {1962, 1874}, {1963, 1875}, {1876, 1877}, {1934, 1935}, {1936, 1937},
{1874, 1875}, {1964, 1966}, {1965, 1967}, {1966, 1968}, {1967, 1969}, {1968, 1970}, {1969, 1971}, {1970, 1972}, {1971, 1973}, {1972, 1974}, {1973, 1975}, {1974, 1976}, {1975, 1977}, {1976, 1978}, {1977, 1979}, {1978, 1980}, {1979, 1981}, {1980, 1982}, {1981, 1983}, {1982, 1984}, {1983, 1985}, {1984, 1986}, {1985, 1987}, {1986, 1988}, {1987, 1989}, {1988, 1990}, {1989, 1991}, {1990, 1992}, {1991, 1993}, {1992, 1994}, {1993, 1995}, {1994, 1996},
{1995, 1997}, {1996, 1998}, {1997, 1999}, {1998, 2000}, {1999, 2001}, {2000, 2002}, {2001, 2003}, {2002, 2004}, {2003, 2005}, {2004, 2006}, {2005, 2007}, {2006, 2008}, {2007, 2009}, {2008, 2010}, {2009, 2011}, {2010, 2012}, {2011, 2013}, {2012, 2014}, {2013, 2015}, {2014, 2016}, {2015, 2017}, {2016, 2018}, {2017, 2019}, {2018, 2020}, {2019, 2021}, {2020, 2022}, {2021, 2023}, {2022, 2024}, {2023, 2025}, {2024, 2026}, {2025, 2027}, {2028, 2030},
{2029, 2031}, {2030, 2032}, {2031, 2033}, {2032, 2034}, {2033, 2035}, {2034, 2036}, {2035, 2037}, {2036, 2038}, {2037, 2039}, {2038, 2040}, {2039, 2041}, {2040, 2042}, {2041, 2043}, {2042, 2044}, {2043, 2045}, {2044, 2046}, {2045, 2047}, {2046, 2048}, {2047, 2049}, {2048, 2050}, {2049, 2051}, {2050, 2052}, {2051, 2053}, {2052, 2054}, {2053, 2055}, {2054, 2056}, {2055, 2057}, {2056, 2058}, {2057, 2059}, {2060, 1964}, {2061, 1965}
}
);
| 404.194118 | 449 | 0.706344 | [
"geometry"
] |
dec49aaae9c699a41de87b26497cb3b4a77c0d8f | 966 | hpp | C++ | src/org/apache/poi/sl/draw/binding/CTGeomGuide.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/sl/draw/binding/CTGeomGuide.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/sl/draw/binding/CTGeomGuide.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/sl/draw/binding/CTGeomGuide.java
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/sl/draw/binding/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct default_init_tag;
class poi::sl::draw::binding::CTGeomGuide
: public virtual ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
public: /* protected */
::java::lang::String* name { };
::java::lang::String* fmla { };
public:
virtual ::java::lang::String* getName();
virtual void setName(::java::lang::String* value);
virtual bool isSetName();
virtual ::java::lang::String* getFmla();
virtual void setFmla(::java::lang::String* value);
virtual bool isSetFmla();
// Generated
CTGeomGuide();
protected:
CTGeomGuide(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
};
| 22.465116 | 75 | 0.665631 | [
"object"
] |
dec85920a171c58d624b9a02375b979354b58e29 | 5,259 | cpp | C++ | src/shader.cpp | xslattery/OpenGL-Voxel-Terrain | c3fc0f7931c52054f9f2c71e5c06193c486d08b0 | [
"MIT"
] | null | null | null | src/shader.cpp | xslattery/OpenGL-Voxel-Terrain | c3fc0f7931c52054f9f2c71e5c06193c486d08b0 | [
"MIT"
] | 1 | 2020-02-01T07:05:48.000Z | 2020-04-14T05:35:49.000Z | src/shader.cpp | xslattery/OpenGL-Voxel-Terrain | c3fc0f7931c52054f9f2c71e5c06193c486d08b0 | [
"MIT"
] | null | null | null | //
// shader.cpp
// RTSProject
//
// Created by Xavier Slattery.
// Copyright © 2015 Xavier Slattery. All rights reserved.
//
#include <OpenGL/gl3.h>
#include <glm/glm.hpp>
#include <fstream>
#include <string>
#include <vector>
#include "typedefs.hpp"
#include "shader.hpp"
unsigned int LoadShaders( const char * vertex_file_path, const char * fragment_file_path ) {
int Result = 0;
int InfoLogLength;
// Create the shaders:
unsigned int VertexShaderID = glCreateShader( GL_VERTEX_SHADER );
// Read the Vertex Shader code from the file:
std::string VertexShaderCode;
std::ifstream VertexShaderStream( vertex_file_path, std::ios::in );
if( VertexShaderStream.is_open() ) {
std::string Line = "";
while( getline( VertexShaderStream, Line ) )
VertexShaderCode += "\n" + Line;
VertexShaderStream.close();
} else {
ERROR( "Impossible to open. Are you in the right directory ? : " << vertex_file_path << "\n" );
return 0;
}
// Compile Vertex Shader
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource( VertexShaderID, 1, &VertexSourcePointer , NULL );
glCompileShader( VertexShaderID );
// Check Vertex Shader
glGetShaderiv( VertexShaderID, GL_COMPILE_STATUS, &Result );
glGetShaderiv( VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength );
if ( InfoLogLength > 0 ) {
std::vector<char> VertexShaderErrorMessage( InfoLogLength+1 );
glGetShaderInfoLog( VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0] );
ERROR( &VertexShaderErrorMessage[0] << "\n" );
}
unsigned int FragmentShaderID = glCreateShader( GL_FRAGMENT_SHADER );
// Read the Fragment Shader code from the file:
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream( fragment_file_path, std::ios::in );
if( FragmentShaderStream.is_open() ){
std::string Line = "";
while( getline(FragmentShaderStream, Line) )
FragmentShaderCode += "\n" + Line;
FragmentShaderStream.close();
} else {
ERROR( "Impossible to open. Are you in the right directory ? : " << fragment_file_path << "\n" );
return 0;
}
// Compile Fragment Shader:
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource( FragmentShaderID, 1, &FragmentSourcePointer , NULL );
glCompileShader( FragmentShaderID );
// Check Fragment Shader:
glGetShaderiv( FragmentShaderID, GL_COMPILE_STATUS, &Result );
glGetShaderiv( FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength );
if ( InfoLogLength > 0 ){
std::vector<char> FragmentShaderErrorMessage( InfoLogLength+1 );
glGetShaderInfoLog( FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0] );
ERROR( &FragmentShaderErrorMessage[0] << "\n" );
}
// Link the program:
unsigned int ProgramID = glCreateProgram();
glAttachShader( ProgramID, VertexShaderID );
glAttachShader( ProgramID, FragmentShaderID );
glLinkProgram( ProgramID );
// Check the program:
glGetProgramiv( ProgramID, GL_LINK_STATUS, &Result );
glGetProgramiv( ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength );
if ( InfoLogLength > 0 ) {
std::vector<char> ProgramErrorMessage( InfoLogLength+1 );
glGetProgramInfoLog( ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0] );
std::cout << &ProgramErrorMessage[0] << "\n";
std::cout << "Shader failed to be created.\n";
}
glDetachShader( ProgramID, VertexShaderID );
glDetachShader( ProgramID, FragmentShaderID );
glDeleteShader( VertexShaderID );
glDeleteShader( FragmentShaderID );
return ProgramID;
}
// Getting Uniforms:
GLint getUniformLocation(const GLint programID, const GLchar* name) {
return glGetUniformLocation(programID, name);
}
// Setting Uniforms:
void setUniform1f(const GLint programID, const GLchar* name, float value) {
glUniform1f(getUniformLocation(programID, name), value);
}
void setUniform1fv(const GLint programID, const GLchar* name, float* value, int count) {
glUniform1fv(getUniformLocation(programID, name), count, value);
}
void setUniform1i(const GLint programID, const GLchar* name, int value) {
glUniform1i(getUniformLocation(programID, name), value);
}
void setUniform1iv(const GLint programID, const GLchar* name, int* value, int count) {
glUniform1iv(getUniformLocation(programID, name), count, value);
}
void setUniform2f(const GLint programID, const GLchar* name, const glm::vec2& vector) {
glUniform2f(getUniformLocation(programID, name), vector.x, vector.y);
}
void setUniform3f(const GLint programID, const GLchar* name, const glm::vec3& vector) {
glUniform3f(getUniformLocation(programID, name), vector.x, vector.y, vector.z);
}
void setUniform4f(const GLint programID, const GLchar* name, const glm::vec4& vector) {
glUniform4f(getUniformLocation(programID, name), vector.x, vector.y, vector.z, vector.w);
}
void setUniformMat4(const GLint programID, const GLchar* name, const glm::mat4& matrix) {
glUniformMatrix4fv(getUniformLocation(programID, name), 1, GL_FALSE, &(matrix[0][0]) );
}
| 38.669118 | 105 | 0.697851 | [
"vector"
] |
dec85bd2d317de9c9941212ffa365be842f77618 | 1,059 | hh | C++ | Alignment/Geners/interface/PackerIOCycle.hh | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | Alignment/Geners/interface/PackerIOCycle.hh | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | Alignment/Geners/interface/PackerIOCycle.hh | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #ifndef GENERS_PACKERIOCYCLE_HH_
#define GENERS_PACKERIOCYCLE_HH_
#include "Alignment/Geners/interface/GenericIO.hh"
namespace gs {
namespace Private {
// Before calling this, make sure that iostack is properly filled
template<typename Pack, unsigned long N>
struct PackerIOCycle
{
template <typename Stream>
inline static bool read(
Pack* s, Stream& is,
std::vector<std::vector<ClassId> >& iostack)
{
return PackerIOCycle<Pack, N-1>::read(s, is, iostack) &&
process_item<GenericReader>(
std::get<N-1>(*s), is, &iostack[N-1], false);
}
};
template<typename Pack>
struct PackerIOCycle<Pack, 0UL>
{
template <typename Stream>
inline static bool read(Pack*, Stream&,
std::vector<std::vector<ClassId> >&)
{return true;}
};
}
}
#endif // GENERS_PACKERIOCYCLE_HH_
| 29.416667 | 73 | 0.539188 | [
"vector"
] |
ded126df06be33aad48e5cbee3a3baa128a80301 | 2,996 | cpp | C++ | aws-cpp-sdk-mediastore-data/source/model/GetObjectResult.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-mediastore-data/source/model/GetObjectResult.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-mediastore-data/source/model/GetObjectResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/mediastore-data/model/GetObjectResult.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::MediaStoreData::Model;
using namespace Aws::Utils::Stream;
using namespace Aws::Utils;
using namespace Aws;
GetObjectResult::GetObjectResult() :
m_contentLength(0),
m_statusCode(0)
{
}
GetObjectResult::GetObjectResult(GetObjectResult&& toMove) :
m_body(std::move(toMove.m_body)),
m_cacheControl(std::move(toMove.m_cacheControl)),
m_contentRange(std::move(toMove.m_contentRange)),
m_contentLength(toMove.m_contentLength),
m_contentType(std::move(toMove.m_contentType)),
m_eTag(std::move(toMove.m_eTag)),
m_lastModified(std::move(toMove.m_lastModified)),
m_statusCode(toMove.m_statusCode)
{
}
GetObjectResult& GetObjectResult::operator=(GetObjectResult&& toMove)
{
if(this == &toMove)
{
return *this;
}
m_body = std::move(toMove.m_body);
m_cacheControl = std::move(toMove.m_cacheControl);
m_contentRange = std::move(toMove.m_contentRange);
m_contentLength = toMove.m_contentLength;
m_contentType = std::move(toMove.m_contentType);
m_eTag = std::move(toMove.m_eTag);
m_lastModified = std::move(toMove.m_lastModified);
m_statusCode = toMove.m_statusCode;
return *this;
}
GetObjectResult::GetObjectResult(Aws::AmazonWebServiceResult<ResponseStream>&& result) :
m_contentLength(0),
m_statusCode(0)
{
*this = std::move(result);
}
GetObjectResult& GetObjectResult::operator =(Aws::AmazonWebServiceResult<ResponseStream>&& result)
{
m_body = result.TakeOwnershipOfPayload();
const auto& headers = result.GetHeaderValueCollection();
const auto& cacheControlIter = headers.find("cache-control");
if(cacheControlIter != headers.end())
{
m_cacheControl = cacheControlIter->second;
}
const auto& contentRangeIter = headers.find("content-range");
if(contentRangeIter != headers.end())
{
m_contentRange = contentRangeIter->second;
}
const auto& contentLengthIter = headers.find("content-length");
if(contentLengthIter != headers.end())
{
m_contentLength = StringUtils::ConvertToInt64(contentLengthIter->second.c_str());
}
const auto& contentTypeIter = headers.find("content-type");
if(contentTypeIter != headers.end())
{
m_contentType = contentTypeIter->second;
}
const auto& eTagIter = headers.find("etag");
if(eTagIter != headers.end())
{
m_eTag = eTagIter->second;
}
const auto& lastModifiedIter = headers.find("last-modified");
if(lastModifiedIter != headers.end())
{
m_lastModified = DateTime(lastModifiedIter->second, DateFormat::RFC822);
}
m_statusCode = static_cast<int>(result.GetResponseCode());
return *this;
}
| 27.740741 | 98 | 0.724967 | [
"model"
] |
ded2c632317bc94f574df09fee423fe9b623e7c9 | 1,363 | hpp | C++ | include/KdTree.hpp | Ip-umd/EucledianClustering | 42120be32297a1cc42113aad5fba46326defcbc3 | [
"BSD-3-Clause"
] | null | null | null | include/KdTree.hpp | Ip-umd/EucledianClustering | 42120be32297a1cc42113aad5fba46326defcbc3 | [
"BSD-3-Clause"
] | null | null | null | include/KdTree.hpp | Ip-umd/EucledianClustering | 42120be32297a1cc42113aad5fba46326defcbc3 | [
"BSD-3-Clause"
] | 1 | 2021-06-03T07:04:18.000Z | 2021-06-03T07:04:18.000Z | /**
* @file KdTree.hpp
* @author Ishan Patel
* @brief Header file for KdTree.cpp
* Declaration of the member variables and functions in the KdTree class.
*/
#ifndef INCLUDE_KDTREE_HPP_
#define INCLUDE_KDTREE_HPP_
#include <vector>
#include "Node.hpp"
class KdTree
{
private:
// Object of Node class
Node* root;
// Helper function for insert function
void insertHelper( Node*& node, uint depth, std::vector<float> point, int id);
// Helper function for search function
void searchHelper(std::vector<float> target, Node* node, uint depth, float distanceTol, std::vector<int> &ids);
// Helper function for eucledianCluster function
void clusterHelper(int indices, std::vector<bool>& processed, const std::vector<std::vector<float>>& points, std::vector<int>& cluster, float distanceTol);
public:
KdTree();
~KdTree();
//Function to insert new point into the tree
void insert(std::vector<float> point, int id);
// Function to obtain a list of point ids in the tree that are within distance of target
std::vector<int> search(std::vector<float> target, float distanceTol);
// Function to obtain list of indices for each cluster based on their proximity
std::vector<std::vector<int>> euclideanCluster(const std::vector<std::vector<float>>& points, float distanceTol);
};
#endif // INCLUDE_KDTREE_HPP_ | 29.630435 | 157 | 0.72047 | [
"object",
"vector"
] |
ded920cb892fc107fe327925fd1422704fb62249 | 1,877 | cpp | C++ | android-28/android/graphics/ColorSpace_Rgb_TransferParameters.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-28/android/graphics/ColorSpace_Rgb_TransferParameters.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/graphics/ColorSpace_Rgb_TransferParameters.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../JObject.hpp"
#include "./ColorSpace_Rgb_TransferParameters.hpp"
namespace android::graphics
{
// Fields
jdouble ColorSpace_Rgb_TransferParameters::a()
{
return getField<jdouble>(
"a"
);
}
jdouble ColorSpace_Rgb_TransferParameters::b()
{
return getField<jdouble>(
"b"
);
}
jdouble ColorSpace_Rgb_TransferParameters::c()
{
return getField<jdouble>(
"c"
);
}
jdouble ColorSpace_Rgb_TransferParameters::d()
{
return getField<jdouble>(
"d"
);
}
jdouble ColorSpace_Rgb_TransferParameters::e()
{
return getField<jdouble>(
"e"
);
}
jdouble ColorSpace_Rgb_TransferParameters::f()
{
return getField<jdouble>(
"f"
);
}
jdouble ColorSpace_Rgb_TransferParameters::g()
{
return getField<jdouble>(
"g"
);
}
// QJniObject forward
ColorSpace_Rgb_TransferParameters::ColorSpace_Rgb_TransferParameters(QJniObject obj) : JObject(obj) {}
// Constructors
ColorSpace_Rgb_TransferParameters::ColorSpace_Rgb_TransferParameters(jdouble arg0, jdouble arg1, jdouble arg2, jdouble arg3, jdouble arg4)
: JObject(
"android.graphics.ColorSpace$Rgb$TransferParameters",
"(DDDDD)V",
arg0,
arg1,
arg2,
arg3,
arg4
) {}
ColorSpace_Rgb_TransferParameters::ColorSpace_Rgb_TransferParameters(jdouble arg0, jdouble arg1, jdouble arg2, jdouble arg3, jdouble arg4, jdouble arg5, jdouble arg6)
: JObject(
"android.graphics.ColorSpace$Rgb$TransferParameters",
"(DDDDDDD)V",
arg0,
arg1,
arg2,
arg3,
arg4,
arg5,
arg6
) {}
// Methods
jboolean ColorSpace_Rgb_TransferParameters::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jint ColorSpace_Rgb_TransferParameters::hashCode() const
{
return callMethod<jint>(
"hashCode",
"()I"
);
}
} // namespace android::graphics
| 19.757895 | 167 | 0.701652 | [
"object"
] |
dee661a052802f9e89d08ed7956dcc5c3a86ec80 | 2,181 | cpp | C++ | src/voronoi/src/voronoi_cell.cpp | frmr/gs | b9721ad27f59ca2e19f637bccd9eba32b663b6a3 | [
"MIT"
] | 2 | 2016-12-06T17:51:30.000Z | 2018-06-21T08:52:58.000Z | src/voronoi/src/voronoi_cell.cpp | frmr/gs | b9721ad27f59ca2e19f637bccd9eba32b663b6a3 | [
"MIT"
] | null | null | null | src/voronoi/src/voronoi_cell.cpp | frmr/gs | b9721ad27f59ca2e19f637bccd9eba32b663b6a3 | [
"MIT"
] | null | null | null | #include "voronoi_cell.h"
#include "../glm/gtc/matrix_transform.hpp"
VoronoiCell::VoronoiCell(mpvec3 p)
{
position = p;
}
void VoronoiCell::addCorner(glm::dvec3 c)
{
corners.push_back(glm::normalize(c));
}
void VoronoiCell::sortCorners()
{
corners = quicksort(corners);
}
std::vector<glm::dvec3> VoronoiCell::quicksort(std::vector<glm::dvec3> points)
{
if (points.size() <= 1)
return points;
glm::dvec3 pivot = points[0];
std::vector<glm::dvec3> prev;
std::vector<glm::dvec3> next;
glm::dvec3 pos = position.to_dvec3();
glm::dvec3 pivnorm = glm::normalize(pivot - pos);
for (unsigned int i = 1; i < points.size(); i++)
{
glm::dvec3 pnorm = glm::normalize(points[i] - pos);
float side = glm::dot(glm::cross(pivnorm,pnorm), pos);
if (side < 0)
prev.push_back(points[i]);
else
next.push_back(points[i]);
}
prev = quicksort(prev);
next = quicksort(next);
prev.push_back(pivot);
prev.insert(prev.end(),next.begin(),next.end());
return prev;
}
void VoronoiCell::computeCentroid()
{
// construct transformation and inverse
glm::dmat4x4 transform = glm::lookAt(glm::dvec3(0.0),
position.to_dvec3(),
glm::dvec3(0.0,1.0,0.0));
glm::dmat4x4 inverse = glm::inverse(transform);
long double cx, cy, cz, area;
cx = cy = area = 0.0;
glm::dvec4 pc4 = glm::dvec4(corners[corners.size()-1], 1.0);
glm::dvec4 prev_t_corner = transform * pc4;
cz = prev_t_corner.z;
for (auto it = corners.begin(); it != corners.end(); it++)
{
glm::dvec3 corner = *it;
glm::dvec4 c4 = glm::dvec4(corner, 1.0);
glm::dvec4 t_corner = transform * c4;
long double a = (prev_t_corner.x * t_corner.y)
- (t_corner.x * prev_t_corner.y);
cx += (prev_t_corner.x + t_corner.x) * a;
cy += (prev_t_corner.y + t_corner.y) * a;
area += a;
prev_t_corner = t_corner;
}
long double f = 1.0/(3.0 * area);
centroid = glm::vec3(inverse * glm::dvec4(f*cx, f*cy, cz, 1.0));
} | 25.658824 | 78 | 0.569005 | [
"vector",
"transform"
] |
def5057d4e86e75e51cb2fa2531558533a42ea5b | 280 | cpp | C++ | EulerRender/src/graphics/MeshMaterial.cpp | jjovanovski/eulerrender | 9ef87b4c0c3667414edc8104c84d3ac08aa2303d | [
"MIT"
] | null | null | null | EulerRender/src/graphics/MeshMaterial.cpp | jjovanovski/eulerrender | 9ef87b4c0c3667414edc8104c84d3ac08aa2303d | [
"MIT"
] | null | null | null | EulerRender/src/graphics/MeshMaterial.cpp | jjovanovski/eulerrender | 9ef87b4c0c3667414edc8104c84d3ac08aa2303d | [
"MIT"
] | null | null | null | #include "MeshMaterial.h"
using namespace Euler;
MeshMaterial::MeshMaterial() {
}
MeshMaterial::MeshMaterial(Mesh * mesh, Material * material) {
this->mesh = mesh;
this->material = material;
}
MeshMaterial::~MeshMaterial() {
Dispose();
}
void MeshMaterial::Dispose() {
} | 14 | 62 | 0.703571 | [
"mesh"
] |
deff149ab6fea61cd1faba5e7ed8c18559ebdaad | 6,399 | hpp | C++ | avl/AVL-extra.hpp | udupa-varun/coursera-cs400 | cf073e6fe816c0d1f8fe95cae10448e979fec2ce | [
"MIT"
] | 2 | 2021-05-19T02:49:55.000Z | 2021-05-20T03:14:24.000Z | avl/AVL-extra.hpp | udupa-varun/coursera-cs400 | cf073e6fe816c0d1f8fe95cae10448e979fec2ce | [
"MIT"
] | null | null | null | avl/AVL-extra.hpp | udupa-varun/coursera-cs400 | cf073e6fe816c0d1f8fe95cae10448e979fec2ce | [
"MIT"
] | null | null | null | /**
* AVL tree - Additional definitions for debugging, etc.
*
* @author Eric Huber
*/
#pragma once
#include <stack>
#include "AVL.hpp"
// printInOrder: Print the tree contents to std::cout using an in-order
// traversal. The "_printInOrder" version is for internal use by the
// public wrapper function "printInOrder".
template <typename K, typename D>
void AVL<K, D>::_printInOrder(TreeNode* node) const {
// Base case: if node is nullptr, then print a space and return.
if (!node) {
std::cout << " ";
return;
}
else {
// Recurse left:
_printInOrder(node->left);
// Print this node:
std::cout << "[" << node->key << " : " << node->data << "]";
// Recurse right:
_printInOrder(node->right);
}
}
// public interface for _printInOrder
template <typename K, typename D>
void AVL<K, D>::printInOrder() const {
_printInOrder(head_);
}
// Print a simple vertical tree diagram. Indentation shows level,
// and children are listed under parents:
// parent
// left child
// right child
// This repeats iteratively with nested indentation. (This could be done
// recursively as well.)
template <typename K, typename D>
void AVL<K, D>::printVertical() const {
// Stacks maintain the next node contents to display as well as the
// corresponding amount of indentation to show in the margin.
std::stack<TreeNode*> node_stack;
std::stack<int> margin_stack;
node_stack.push(head_);
margin_stack.push(0);
while (!node_stack.empty()) {
TreeNode* n = node_stack.top();
node_stack.pop();
int margin_level = margin_stack.top();
margin_stack.pop();
for (int i=0; i < margin_level; i++) {
std::cout << " ";
}
if (margin_level > 0) {
std::cout << "|- ";
}
else {
std::cout << ". ";
}
if (n) {
// Only push child markers if at least one child exists.
// This makes the leaf output clearer: if both children are nullptr,
// they are simply not printed.
if (n->left || n->right) {
node_stack.push(n->right);
margin_stack.push(margin_level+1);
node_stack.push(n->left);
margin_stack.push(margin_level+1);
}
// show key, data pair
std::cout << "[" << n->key << ": \"" << n->data << "\"] ";
// balance factor
std::cout << "Bal: " << _get_balance_factor(n) << " ";
// height
std::cout << "Ht: " << _get_height(n) << std::endl;
}
else {
// no child (nullptr)
std::cout << "[]" << std::endl;
}
}
}
// These debugging checks do redundant checking just to make sure the
// program doesn't have a mistake that would be hard to catch otherwise.
// In practice this kind of check could be disabled after the library
// was fully tested.
// For practice, think about why the recursive checks in these functions are
// logically valid.
template <typename K, typename D>
bool AVL<K, D>::runDebuggingChecks() {
if (ENABLE_DEBUGGING_CHECKS) {
if (!_debugHeightCheck(head_)) throw std::runtime_error("ERROR: _debugHeightCheck failed");
if (!_debugBalanceCheck(head_)) throw std::runtime_error("ERROR: _debugBalanceCheck failed");
if (!_debugOrderCheck(head_)) throw std::runtime_error("ERROR: _debugOrderCheck failed");
}
return true;
}
template <typename K, typename D>
bool AVL<K, D>::_debugHeightCheck(TreeNode* cur) {
// a non-existent node implicitly has the correct height
if (!cur) return true;
// everything OK left?
if (!_debugHeightCheck(cur->left)) return false;
// everything OK right?
if (!_debugHeightCheck(cur->right)) return false;
// everything OK here?
int height_here = _get_height(cur);
int height_left = _get_height(cur->left);
int height_right = _get_height(cur->right);
int max_child_height = std::max(height_left, height_right);
bool test_result = (1 == height_here - max_child_height);
if (!test_result) {
std::cerr << "_debugHeightCheck internals:" << std::endl;
std::cerr << "here: " << height_here << std::endl;
std::cerr << "left: " << height_left << std::endl;
std::cerr << "right: " << height_right << std::endl;
}
return test_result;
}
template <typename K, typename D>
bool AVL<K, D>::_debugBalanceCheck(TreeNode* cur) {
// balanced non-existence
if (!cur) return true;
// everything OK left?
if (!_debugBalanceCheck(cur->left)) return false;
// everything OK right?
if (!_debugBalanceCheck(cur->right)) return false;
// everything OK here?
int bal = _get_height(cur->right) - _get_height(cur->left);
return (bal >= -1 && bal <= 1);
}
template <typename K, typename D>
bool AVL<K, D>::_debugOrderCheck(TreeNode* cur) {
// An empty tree is well-ordered.
if (!cur) return true;
// An enumeration is a special type that can only have one of the
// labeled states. Useful for a mode toggle variable.
enum action_enum {
VISIT, EXPLORE
};
// There are more efficient ways to write this iterative traversal.
// Here we "explore", "visit", and finally order-check every node.
// You can do this at least 3x faster.
// Try it with one stack instead of using two stacks and a vector.
std::stack<TreeNode*> node_stack;
std::stack<action_enum> action_stack;
std::vector<const K*> key_ptrs;
node_stack.push(head_);
action_stack.push(EXPLORE);
while (!node_stack.empty()) {
TreeNode* cur = node_stack.top();
node_stack.pop();
const auto action = action_stack.top();
action_stack.pop();
if (action == VISIT) {
key_ptrs.push_back(&(cur->key));
}
else {
if (cur->right) {
node_stack.push(cur->right);
action_stack.push(EXPLORE);
}
node_stack.push(cur);
action_stack.push(VISIT);
if (cur->left) {
node_stack.push(cur->left);
action_stack.push(EXPLORE);
}
}
}
// There are more efficient ways to write this loop too.
for (int i=0; (i+1) < (int)(key_ptrs.size()); i++) {
const K* first_key_ptr = key_ptrs[i];
const K* second_key_ptr = key_ptrs[i+1];
// Keys should have increasing order, with no duplicates.
if (*first_key_ptr >= *second_key_ptr) {
std::cerr << "ERROR: These keys should be in strictly increasing order:" << std::endl;
std::cerr << *first_key_ptr << " followed by " << *second_key_ptr << std::endl;
return false;
}
}
return true;
}
| 27.346154 | 97 | 0.641663 | [
"vector"
] |
7206a8ab58e1199a8d0e4af4271501fb7887de34 | 16,475 | cpp | C++ | sources/Framework/Tools/LightmapGenerator/spLightmapShaderDispatcher.cpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 14 | 2015-08-16T21:05:20.000Z | 2019-08-21T17:22:01.000Z | sources/Framework/Tools/LightmapGenerator/spLightmapShaderDispatcher.cpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | null | null | null | sources/Framework/Tools/LightmapGenerator/spLightmapShaderDispatcher.cpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 3 | 2016-10-31T06:08:44.000Z | 2019-08-02T16:12:33.000Z | /*
* Lightmap shader dispatcher file
*
* This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
* See "SoftPixelEngine.hpp" for license information.
*/
#include "Framework/Tools/LightmapGenerator/spLightmapShaderDispatcher.hpp"
#ifdef SP_COMPILE_WITH_LIGHTMAPGENERATOR
#include "Framework/Tools/LightmapGenerator/spKDTreeBufferMapper.hpp"
#include "SceneGraph/Collision/spCollisionMesh.hpp"
#include "RenderSystem/spRenderSystem.hpp"
#include "RenderSystem/spShaderResource.hpp"
#include "RenderSystem/spShaderClass.hpp"
#include "Base/spInputOutputString.hpp"
#include "Base/spMath.hpp"
#include "Base/spMathRandomizer.hpp"
#include "Base/spDimensionVector2D.hpp"
#include "Base/spDimensionVector4D.hpp"
#include "Base/spDimensionMatrix4.hpp"
#include "Base/spBaseExceptions.hpp"
#include "Base/spTimer.hpp"
#if ( defined(SP_DEBUGMODE) || 1 ) && 0
# define _DEB_LOAD_SHADERS_FROM_FILES_//!!!
#endif
namespace sp
{
extern video::RenderSystem* GlbRenderSys;
namespace tool
{
namespace LightmapGen
{
/*
* Constant buffer structures
*/
using dim::uint2;
using dim::float2;
using dim::float3;
using dim::float4;
using dim::float4x4;
#if defined(_MSC_VER)
# pragma pack(push, packing)
# pragma pack(1)
# define SP_PACK_STRUCT
#elif defined(__GNUC__)
# define SP_PACK_STRUCT __attribute__((packed))
#else
# define SP_PACK_STRUCT
#endif
struct SLightmapMainCB
{
float4x4 InvWorldMatrix;
float4 AmbientColor;
u32 NumLights;
u32 LightmapSize;
u32 NumTriangles;
}
SP_PACK_STRUCT;
struct SRadiositySetupCB
{
u32 NumRadiosityRays;
f32 RadiosityFactor; // (1.0 / NumRadiosityRays) * Factor
}
SP_PACK_STRUCT;
struct SRadiosityRaysCB
{
float4 RadiosityDirections[ShaderDispatcher::MAX_NUM_RADIOSITY_RAYS];
}
SP_PACK_STRUCT;
struct SLightSourceSR
{
s32 Type;
float4 Sphere; // Position (XYZ) and inverse radius (W).
float3 Color;
float3 Direction;
f32 SpotTheta;
f32 SpotPhiMinusTheta;
}
SP_PACK_STRUCT;
#ifdef _MSC_VER
# pragma pack(pop, packing)
#endif
#undef SP_PACK_STRUCT
/*
* LightmapGenerator class
*/
ShaderDispatcher::ShaderDispatcher() :
DirectIlluminationSC_ (0 ),
IndirectIlluminationSC_ (0 ),
LightListSR_ (0 ),
LightmapGridSR_ (0 ),
TriangleListSR_ (0 ),
TriangleIdListSR_ (0 ),
NodeListSR_ (0 ),
InputLightmap_ (0 ),
OutputLightmap_ (0 ),
ActiveLightmap_ (0 ),
RadiosityEnabled_ (false ),
UseTreeHierarchy_ (false ),
NumLights_ (0 ),
LMGridSize_ (0 )
{
}
ShaderDispatcher::~ShaderDispatcher()
{
deleteResources();
}
bool ShaderDispatcher::createResources(
const scene::CollisionMesh* SceneCollMdl, bool EnableRadiosity,
bool UseTreeHierarchy, u32 LMGridSize, u32 NumRadiosityRays)
{
/* Initialization */
io::Log::message("Create resources for lightmap generation shader dispatcher");
io::Log::ScopedTab Unused;
try
{
if (!SceneCollMdl)
throw io::DefaultException("Invalid collision model for shader dispatcher");
if (!GlbRenderSys->queryVideoSupport(video::VIDEOSUPPORT_COMPUTE_SHADER))
throw io::DefaultException("Compute shaders are not available");
RadiosityEnabled_ = EnableRadiosity;
UseTreeHierarchy_ = UseTreeHierarchy;
/* Create all shader resources */
if (!createAllShaderResources())
throw io::DefaultException("Creating shader resources failed");
/* Initialize lightmap grid */
LMGridSize_ = LMGridSize;
LightmapGridSR_->setupBuffer<SLightmapTexelLoc>(math::pow2(LMGridSize_));
/* Create shader classes, lightmap textures and setup collision model */
if ( !createAllComputeShaders() ||
!createTextures() ||
!setupCollisionModel(SceneCollMdl) )
{
throw io::DefaultException("");
}
}
catch (const std::exception &e)
{
if (*e.what())
io::Log::error(e.what());
deleteResources();
return false;
}
/* Setup constant buffers */
generateRadiosityRays(NumRadiosityRays);
return true;
}
void ShaderDispatcher::deleteResources()
{
/* Delete all shader resources and textures */
GlbRenderSys->deleteShaderClass(DirectIlluminationSC_ );
GlbRenderSys->deleteShaderClass(IndirectIlluminationSC_ );
GlbRenderSys->deleteShaderResource(LightListSR_ );
GlbRenderSys->deleteShaderResource(LightmapGridSR_ );
GlbRenderSys->deleteShaderResource(TriangleListSR_ );
GlbRenderSys->deleteShaderResource(TriangleIdListSR_);
GlbRenderSys->deleteShaderResource(NodeListSR_ );
GlbRenderSys->deleteTexture(InputLightmap_ );
GlbRenderSys->deleteTexture(OutputLightmap_ );
DirectIlluminationSC_ = 0;
IndirectIlluminationSC_ = 0;
}
bool ShaderDispatcher::setupLightSources(const std::vector<SLightmapLight> &LightList)
{
if (!LightListSR_)
return false;
/* Initialize buffer light list and get iterators for easy access */
std::vector<SLightSourceSR> BufferLightList(LightList.size());
std::vector<SLightSourceSR>::iterator it = BufferLightList.begin();
std::vector<SLightmapLight>::const_iterator itRef = LightList.begin();
NumLights_ = LightList.size();
/* Fill each light source entry */
for (; it != BufferLightList.end(); ++it, ++itRef)
{
it->Type = static_cast<s32>(itRef->Type);
it->Sphere = dim::vector4df(itRef->Matrix.getPosition(), itRef->Attn1);
it->Color = itRef->Color.getVector(true);
it->Direction = (itRef->Matrix * dim::vector3df(0, 0, 1));
it->SpotTheta = itRef->InnerConeAngle;
it->SpotPhiMinusTheta = itRef->OuterConeAngle - itRef->InnerConeAngle;
}
/* Copy to shader resource */
return LightListSR_->setupBuffer<SLightSourceSR>(NumLights_, &BufferLightList[0]);
}
bool ShaderDispatcher::setupLightmapGrid(SLightmap* Lightmap)
{
/* Copy texel location buffer to shader resource */
if (Lightmap && LightmapGridSR_ && Lightmap->TexelLocBuffer && Lightmap->TexelBuffer)
{
ActiveLightmap_ = Lightmap;
LightmapGridSR_->writeBuffer(Lightmap->TexelLocBuffer);
return true;
}
return false;
}
void ShaderDispatcher::dispatchDirectIllumination(const dim::matrix4f &InvWorldMatrix, const video::color &AmbientColor)
{
if (!DirectIlluminationSC_ || !ActiveLightmap_ || NumLights_ == 0)
return;
/* Setup constant buffers */
setupMainConstBuffer(DirectIlluminationSC_, InvWorldMatrix, AmbientColor);
/* Run compute shader to generate lightmap texels */
if (GlbRenderSys->dispatch(DirectIlluminationSC_, getNumWorkGroup()))
extractLightmapTexels();
}
void ShaderDispatcher::dispatchIndirectIllumination(const dim::matrix4f &InvWorldMatrix)
{
if (!IndirectIlluminationSC_ || !InputLightmap_ || !OutputLightmap_)
return;
/* Setup constant buffers */
setupMainConstBuffer(IndirectIlluminationSC_, InvWorldMatrix, 0);
/* Copy input texture from previous output texture and bind it */
//InputLightmap_->copyTexture(OutputLightmap_);
InputLightmap_->bind(5);
/* Run compute shader to generate lightmap texels */
GlbRenderSys->dispatch(IndirectIlluminationSC_, getNumWorkGroup());
}
/*
* ======= Private: =======
*/
bool ShaderDispatcher::createShaderResource(video::ShaderResource* &ShdResource)
{
return ( ShdResource = GlbRenderSys->createShaderResource() ) != 0;
}
bool ShaderDispatcher::createAllShaderResources()
{
return
createShaderResource(LightListSR_ ) &&
createShaderResource(LightmapGridSR_ ) &&
createShaderResource(TriangleListSR_ ) &&
createShaderResource(TriangleIdListSR_ ) &&
createShaderResource(NodeListSR_ );
}
void ShaderDispatcher::appendShaderResources(video::ShaderClass* ShdClass)
{
if (ShdClass)
{
ShdClass->addShaderResource(LightListSR_ );
ShdClass->addShaderResource(LightmapGridSR_ );
ShdClass->addShaderResource(TriangleListSR_ );
ShdClass->addShaderResource(TriangleIdListSR_ );
ShdClass->addShaderResource(NodeListSR_ );
}
}
bool ShaderDispatcher::createComputeShader(video::ShaderClass* &ShdClass)
{
return ( ShdClass = GlbRenderSys->createShaderClass() ) != 0;
}
bool ShaderDispatcher::createAllComputeShaders()
{
/* Load shader source code */
std::list<io::stringc> ShdBuf;
video::Shader::addOption(ShdBuf, "MAX_NUM_RADIOSITY_RAYS " + io::stringc(ShaderDispatcher::MAX_NUM_RADIOSITY_RAYS));
if (UseTreeHierarchy_)
video::Shader::addOption(ShdBuf, "USE_TREE_HIERARCHY");
switch (GlbRenderSys->getRendererType())
{
case video::RENDERER_DIRECT3D11:
{
#ifndef _DEB_LOAD_SHADERS_FROM_FILES_//!!!
ShdBuf.push_back(
#include "Resources/spLightmapGenerationShaderStr.hlsl"
);
#else
io::FileSystem fsys;
video::ShaderClass::loadShaderResourceFile(fsys, "../../sources/Framework/Tools/LightmapGenerator/spLightmapGenerationShader.hlsl", ShdBuf);
#endif
}
break;
default:
io::Log::error("No direct illumination compute shader support for this render system");
return false;
}
/* Build direct illumination compute shader */
if (!createComputeShader(DirectIlluminationSC_))
return false;
const u64 StartTime = io::Timer::millisecs();
video::Shader* CompShd = GlbRenderSys->createShader(
DirectIlluminationSC_, video::SHADER_COMPUTE, video::HLSL_COMPUTE_5_0,
ShdBuf, "ComputeDirectIllumination", video::SHADERFLAG_NO_OPTIMIZATION//!!!
);
if (!DirectIlluminationSC_->compile())
{
io::Log::error("Compiling direct illumination compute shader failed");
return false;
}
/* Print information about shader compilation time */
io::Log::message(
"Shader compilation time: " + io::stringc(io::Timer::millisecs() - StartTime) + " ms."
);
/* Build direct illumination compute shader */
if (RadiosityEnabled_)
{
if (!createComputeShader(IndirectIlluminationSC_))
return false;
CompShd = GlbRenderSys->createShader(
IndirectIlluminationSC_, video::SHADER_COMPUTE, video::HLSL_COMPUTE_5_0, ShdBuf, "ComputeIndirectIllumination"
);
if (!IndirectIlluminationSC_->compile())
{
io::Log::error("Compiling indirect illumination compute shader failed");
return false;
}
}
/* Append resources to shaders */
appendShaderResources(DirectIlluminationSC_);
appendShaderResources(IndirectIlluminationSC_);
return true;
}
bool ShaderDispatcher::createTextures()
{
/* Create input and output lightmap textures */
video::STextureCreationFlags CreationFlags;
{
CreationFlags.Filename = "Input Lightmap";
CreationFlags.Type = video::TEXTURE_2D;
CreationFlags.Size = LMGridSize_;
CreationFlags.Format = video::PIXELFORMAT_RGBA;
CreationFlags.HWFormat = video::HWTEXFORMAT_FLOAT32;
CreationFlags.BufferType = video::IMAGEBUFFER_FLOAT;
CreationFlags.Filter.HasMIPMaps = false;
}
InputLightmap_ = GlbRenderSys->createTexture(CreationFlags);
{
CreationFlags.Filename = "Output Lightmap";
CreationFlags.Type = video::TEXTURE_2D_RW;
}
OutputLightmap_ = GlbRenderSys->createTexture(CreationFlags);
/* Append textures to */
if (DirectIlluminationSC_)
DirectIlluminationSC_->addRWTexture(OutputLightmap_);
if (IndirectIlluminationSC_)
IndirectIlluminationSC_->addRWTexture(OutputLightmap_);
return true;
}
bool ShaderDispatcher::setupCollisionModel(const scene::CollisionMesh* SceneCollMdl)
{
const u64 StartTime = io::Timer::millisecs();
/* Setup collision model shader resources with the kd-tree buffer mapper */
bool Result = KDTreeBufferMapper::copyTreeHierarchy(
SceneCollMdl,
(UseTreeHierarchy_ ? NodeListSR_ : 0),
(UseTreeHierarchy_ ? TriangleIdListSR_ : 0),
TriangleListSR_
);
if (Result)
{
/* Print information about collision model creation time */
io::Log::message(
"Collision model creation time: " + io::stringc(io::Timer::millisecs() - StartTime) + " ms."
);
}
return Result;
}
void ShaderDispatcher::setupMainConstBuffer(
video::ShaderClass* ShdClass, const dim::matrix4f &InvWorldMatrix, const video::color &AmbientColor)
{
/* Setup main constant buffer */
video::Shader* CompShd = ShdClass->getComputeShader();
SLightmapMainCB BufferMain;
{
BufferMain.InvWorldMatrix = InvWorldMatrix;
BufferMain.AmbientColor = AmbientColor.getVector4(true);
BufferMain.NumLights = NumLights_;
BufferMain.LightmapSize = LMGridSize_;
BufferMain.NumTriangles = TriangleListSR_->getCount();
}
CompShd->setConstantBuffer(0, &BufferMain);
}
dim::vector3df ShaderDispatcher::getRandomRadiosityRay() const
{
/*
Get transformed random angle.
We need more rays in the surface's normal direction.
*/
const f32 Theta = 90.0f * std::pow(math::Randomizer::randFloat(-1.0f, 1.0f), 5);
const f32 Phi = math::Randomizer::randFloat(360.0f);
/* Convert spherical coordinate into cartesian coordinate */
dim::vector3df Vec;
math::convertToCartesianCoordiantes(Vec, Theta, Phi, 1.0f);
return Vec;
}
void ShaderDispatcher::generateRadiosityRays(u32 NumRays)
{
if (!IndirectIlluminationSC_)
return;
video::Shader* CompShd = IndirectIlluminationSC_->getComputeShader();
/* Clamp number of rays */
if (NumRays > ShaderDispatcher::MAX_NUM_RADIOSITY_RAYS)
{
NumRays = ShaderDispatcher::MAX_NUM_RADIOSITY_RAYS;
io::Log::warning("Maximal number of radiosity rays is " + io::stringc(ShaderDispatcher::MAX_NUM_RADIOSITY_RAYS));
}
/* Setup radiosity configuration */
SRadiositySetupCB RadiositySetup;
{
RadiositySetup.NumRadiosityRays = NumRays;
}
CompShd->setConstantBuffer(1, &RadiositySetup);
/* Setup radiosity ray directions */
SRadiosityRaysCB RadiosityRays;
{
for (u32 i = 0; i < ShaderDispatcher::MAX_NUM_RADIOSITY_RAYS; ++i)
RadiosityRays.RadiosityDirections[i] = getRandomRadiosityRay();
}
CompShd->setConstantBuffer(2, &RadiosityRays);
}
bool ShaderDispatcher::extractLightmapTexels()
{
/* Load texel buffer from GPU */
if (!ActiveLightmap_ || !OutputLightmap_->shareImageBuffer())
return false;
/* Copy texel data into active lightmap texel buffer */
video::ImageBuffer* ImgBuffer = OutputLightmap_->getImageBuffer();
dim::point2di Pos;
const dim::size2di Size = ImgBuffer->getSize();
for (Pos.Y = 0; Pos.Y < Size.Height; ++Pos.Y)
{
for (Pos.X = 0; Pos.X < Size.Width; ++Pos.X)
{
/* Get current texel color and clamp to range [0, 255] */
dim::vector4df TexelColor = ImgBuffer->getPixelVector(Pos);
for (u32 i = 0; i < 4; ++i)
math::clamp(TexelColor[i], 0.0f, 1.0f);
ActiveLightmap_->getTexel(Pos.X, Pos.Y).Color = video::color(TexelColor);
}
}
return true;
}
dim::vector3d<u32> ShaderDispatcher::getNumWorkGroup() const
{
return UseTreeHierarchy_ ?
dim::vector3d<u32>(LMGridSize_, LMGridSize_, 1) :
dim::vector3d<u32>(LMGridSize_ / 8, LMGridSize_ / 8, 1);
}
} // /namespace LightmapGen
} // /namespace tool
} // /namespace sp
#endif
// ================================================================================
| 30.173993 | 152 | 0.656146 | [
"render",
"vector",
"model"
] |
720d4036a35be53f39565e3f7da27be757b1cc94 | 3,036 | cpp | C++ | game/src/zombie.cpp | speedy0/SoldierNo1296 | bd379e9e21d6bab585c2b68c43016a1e5b6ffc59 | [
"MIT"
] | null | null | null | game/src/zombie.cpp | speedy0/SoldierNo1296 | bd379e9e21d6bab585c2b68c43016a1e5b6ffc59 | [
"MIT"
] | null | null | null | game/src/zombie.cpp | speedy0/SoldierNo1296 | bd379e9e21d6bab585c2b68c43016a1e5b6ffc59 | [
"MIT"
] | null | null | null | #pragma once
#include "pch.h"
#include "zombie.h"
zombie::zombie() {};
zombie::~zombie() {};
void zombie::initialise(engine::ref<engine::game_object> object, glm::vec3 position, glm::vec3 forward) {
m_zom = object;
m_zom->set_forward(forward);
m_zom->set_position(position);
m_zom->animated_mesh()->set_default_animation(2);
isWalking = false;
Set_Health(35);
}
void zombie::on_update(const engine::timestep& time_step, const glm::vec3& player_position) {
//Measures the distance between a zombie and a player.
float dist_to_player = glm::distance(m_zom->position(), player_position);
if (isWalking == true && m_speed == 0.f) {
isWalking = false;
m_zom->animated_mesh()->switch_animation(m_zom->animated_mesh()->default_animation());
}
else if (isWalking != true && m_speed > 0.f) {
isWalking = true;
m_zom->animated_mesh()->switch_animation(1);
}
//Checks which behaviour is zombie currently in.
if (m_state == state::idle) {
//If player is not in the near the zombie's detection radius, zombie will just wonder around.
wonder(time_step);
//If player is in zombie's detection radius, zombie will face the player and prepare to attack.
if (dist_to_player < m_detection_radius)
m_state = state::prepare;
}
else if (m_state == state::prepare) {
confirm_player(time_step, player_position);
//This is a slow zombie, if player leaves the area when zombie is preparing, the zombie will leave the player alone.
if (dist_to_player > m_detection_radius)
m_state = state::idle;
//however if player will not back away and move towards the zombie, zombie will start chasing and attack.
else if (dist_to_player < m_trigger_radius)
m_state = state::attack;
}
else {
attack_player(time_step, player_position);
}
}
void zombie::wonder(const engine::timestep& time_step) {
//When zombie wonders around, how long does it take him to turn around and change direction.
m_speed = 0.8f;
m_switch_directions -= (float)time_step;
if (m_switch_directions < 0.f) {
m_zom->set_forward(m_zom->forward() * -1.f);
m_switch_directions = m_default_time;
}
m_zom->set_position(m_zom->position() + m_zom->forward() * m_speed * (float)time_step);
m_zom->set_rotation_amount(atan2(m_zom->forward().x, m_zom->forward().z));
}
void zombie::confirm_player(const engine::timestep& time_step, const glm::vec3& player_position) {
m_zom->set_forward(player_position - m_zom->position());
m_zom->set_rotation_amount(atan2(m_zom->forward().x, m_zom->forward().z));
}
void zombie::attack_player(const engine::timestep& time_step, const glm::vec3& player_position) {
m_speed = 1.f;
m_zom->set_forward(player_position - m_zom->position());
m_zom->set_position(m_zom->position() + m_zom->forward() * m_speed * (float)time_step);
m_zom->set_rotation_amount(atan2(m_zom->forward().x, m_zom->forward().z));
}
void zombie::Set_Health(int a_health) {
health = a_health;
}
int zombie::Get_Health() {
return health;
}
int zombie::Damage_Taken(int a_health) {
health -= a_health;
return health;
}
| 32.297872 | 118 | 0.725955 | [
"object"
] |
72129fa5167ad0d4dce43caffd49fde6bb1804e8 | 1,581 | hpp | C++ | include/cinatra/io_service_pool.hpp | wofeicaoge/cinatra | 249fbbb7d271ec4483bed35b63e26c40343a3ff6 | [
"MIT"
] | null | null | null | include/cinatra/io_service_pool.hpp | wofeicaoge/cinatra | 249fbbb7d271ec4483bed35b63e26c40343a3ff6 | [
"MIT"
] | null | null | null | include/cinatra/io_service_pool.hpp | wofeicaoge/cinatra | 249fbbb7d271ec4483bed35b63e26c40343a3ff6 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <memory>
#include <thread>
#include "use_asio.hpp"
#include "utils.hpp"
namespace cinatra
{
class io_service_pool : private noncopyable{
public:
explicit io_service_pool(const std::size_t pool_size = 1) : next_io_service_(0) {
for (std::size_t i = 0; i < pool_size; ++i)
{
io_service_ptr io_service(new boost::asio::io_service);
work_ptr work(new boost::asio::io_service::work(*io_service));
io_services_.push_back(io_service);
work_.push_back(work);
}
}
void run() {
std::vector<std::shared_ptr<std::thread>> threads;
for (auto& io_service : io_services_){
threads.emplace_back(std::make_shared<std::thread>(
[](io_service_ptr svr) {
svr->run();
}, io_service));
}
for (auto& thread : threads)
thread->join();
}
intptr_t run_one() {
return -1;
}
intptr_t poll() {
return -1;
}
intptr_t poll_one() {
return -1;
}
void stop() {
work_.clear();
for (std::size_t i = 0; i < io_services_.size(); ++i)
io_services_[i]->stop();
}
boost::asio::io_service& get_io_service() {
boost::asio::io_service& io_service = *io_services_[next_io_service_];
++next_io_service_;
if (next_io_service_ == io_services_.size())
next_io_service_ = 0;
return io_service;
}
private:
using io_service_ptr = std::shared_ptr<boost::asio::io_service>;
using work_ptr = std::shared_ptr<boost::asio::io_service::work>;
std::vector<io_service_ptr> io_services_;
std::vector<work_ptr> work_;
std::size_t next_io_service_;
};
}
| 21.958333 | 83 | 0.661607 | [
"vector"
] |
72167af10009d5af4c8c944fbc6179c3896e527e | 16,647 | cpp | C++ | toolbox/unused/garment_shape.cpp | katjawolff/custom_fit_garments | 1d6f9dcba612010bb5552201f39595f7b288b8d5 | [
"MIT"
] | 4 | 2021-08-15T09:28:51.000Z | 2022-03-14T10:19:09.000Z | toolbox/unused/garment_shape.cpp | katjawolff/custom_fit_garments | 1d6f9dcba612010bb5552201f39595f7b288b8d5 | [
"MIT"
] | 1 | 2021-12-24T07:16:34.000Z | 2021-12-24T07:16:34.000Z | toolbox/unused/garment_shape.cpp | katjawolff/custom_fit_garments | 1d6f9dcba612010bb5552201f39595f7b288b8d5 | [
"MIT"
] | null | null | null | #include "garment_shape.h"
#include <vector>
#include <iostream>
#include <iomanip>
#include <igl/edges.h>
#include "../adjacency.h"
using namespace std;
using namespace Eigen;
typedef Triplet<double> Tri;
RestShape::RestShape(){}
void RestShape::init(const MatrixXi& F) {
// create adjacency information - E4: list of 4 vertices for each face pair (each internal edge)
this->F = F;
igl::edges(F, E);
vector< vector<int> > VF_adj;
createVertexFaceAdjacencyList(F, VF_adj);
createFaceEdgeAdjecencyList(F, E, VF_adj, FE_adj);
createFacePairEdgeListWith4VerticeIDs(F, E, VF_adj, E4, EF6, EF_adj);
faces = F.rows();
edges = E.rows();
interior_edges = 0;
for (int i = 0; i < EF_adj.rows(); i++)
if (EF_adj(i, 1) != -1)
interior_edges++;
}
void RestShape::setFixedVertices(const vector<bool>& fixed_boundary_vert) {
this->fixed_boundary_vert = fixed_boundary_vert;
fixed_boundary_edge.clear();
fixed_boundary_edge.resize(E.rows(), false);
for (int e = 0; e < E.rows(); e++)
if (fixed_boundary_vert[E(e, 0)] && fixed_boundary_vert[E(e, 1)])
fixed_boundary_edge[e] = true;
}
void RestShape::shape_energy(
const MatrixXd& X_current,
const MatrixXd& X_restshape,
const vector< double >& length_target,
const vector< double >& angle_target,
int edge_constraints_count,
const vector< int >& edge_constraints,
VectorXd& f,
SparseMatrix<double>& J,
bool with_jacobian
) {
// edge lenght weight is always 1.
double alpha = 1.e-4; // how to weight angle constraints
//double beta = 1.e-6; // how to weight shear constraints
double lambda = 1.e-4; // how to weight positional constraints
//double lambda_fixed = 1.;
double gamma = 1e3; // weighing fixed edge lengths of fixed boundaries
// calculate energy and Jacobian
// -----------------------------
int total_constraints = edges + interior_edges /*+ faces*/ + verts * 3 + 1; // edge constr. + angle constr. + shear constr. + position constr. + sum edges
// TODO abobve line
f = VectorXd::Zero(total_constraints);
int c = 0; //index of next constraint
vector<Tri> triJ;
triJ.reserve(edges * 6 + interior_edges * 12 + verts * 3 + faces * 3);
// TODO abobve line
// edge lengths
// ------------
vector<bool> vertex_constrained_by_edge(X_current.rows(), false);
VectorXd edge_length(edges);
for (int e = 0; e < edges; e++) {
int x1 = E(e, 0);
int x2 = E(e, 1);
if (edge_constraints[e] != 0) { // mark vertices that are affected by edge length changes
vertex_constrained_by_edge[x1] = true;
vertex_constrained_by_edge[x2] = true;
}
Vector3d dx = X_current.row(x1) - X_current.row(x2);
edge_length(e) = dx.norm();
if (!fixed_boundary_edge[e]) { // TODO try including the boundary edges too
f(c) = dx.dot(dx) - length_target[e] * length_target[e];
if (with_jacobian) {
Vector3d df_dx = 2. * dx; // df_dx2 = -df_dx1
for (int j = 0; j < 3; j++) {
triJ.push_back(Tri(c, j * verts + x1, df_dx(j)));
triJ.push_back(Tri(c, j * verts + x2, -df_dx(j)));
}
}
c++;
}
}
// fixed boundary edges
// =====================
// TODO !!! need to do this for each boundary individually!!
/* double sum_old = 0.;
double sum_new = 0.;
for (int e = 0; e < edges; e++) {
if (fixed_boundary_edge[e]) {
int x1 = E(e, 0);
int x2 = E(e, 1);
sum_new += edge_length(e);
sum_old += (X_restshape.row(x1) - X_restshape.row(x2)).norm();
}
}
double d_sum = sum_new - sum_old;
f(c) = gamma * d_sum * d_sum;
for (int e = 0; e < edges; e++) {
if (fixed_boundary_edge[e]) {
int x1 = E(e, 0);
int x2 = E(e, 1);
Vector3d dx = X_current.row(x1) - X_current.row(x2);
if (with_jacobian) {
Vector3d df_dx = gamma * 2. * d_sum * dx / edge_length(e);
for (int j = 0; j < 3; j++) {
triJ.push_back(Tri(c, j * verts + x1, df_dx(j)));
triJ.push_back(Tri(c, j * verts + x2, -df_dx(j)));
}
}
}
}
c++;
*/
// shear
// -----
/* for (int i = 0; i < faces; i++) {
for (int k = 0; k < 3; k++) { // each angle in a triangle
Vector3d v1 = X_current.row(F(i, (k+1)%3)) - X_current.row(F(i, k));
Vector3d v2 = X_current.row(F(i, (k+2)%3)) - X_current.row(F(i, k));
double v1norm = v1.norm();
double v2norm = v2.norm();
double shear = v1.dot(v2) / (v1norm * v2norm);
if (shear > 0.9) {
f(c) = shear - 0.9;
c++;
// first order derivatives
// some mysterious needed precomp (for dJ/dv_x), left col for J_x, right col for J_y
if (with_jacobian) {
Vector3d df_dv1 = v2 / (v1norm * v2norm) * (v1.sum() / (v1norm * v1norm) - 1);
Vector3d df_dv2 = v1 / (v1norm * v2norm) * (v2.sum() / (v2norm * v2norm) - 1);
Vector3d df_dv0 = v2 / (v1norm * v2norm) * (-v1.sum() / (v1norm * v1norm) + 1) + v1 / (v1norm * v2norm) * (-v2.sum() / (v2norm * v2norm) + 1);
for (int j = 0; j < 3; j++) { // x,y,z
triJ.push_back(Tri(c, j * verts + F(i, 0), df_dv0(j)));
triJ.push_back(Tri(c, j * verts + F(i, 1), df_dv1(j)));
triJ.push_back(Tri(c, j * verts + F(i, 2), df_dv2(j)));
}
}
}
}
}
*/
// angles
// ------
// to avoid wobbling and overlapping triangles
MatrixXd normal(faces, 3), cos_alpha(faces, 3), h_inverse(faces, 3);
for (int f = 0; f < faces; f++) {
vector<Vector3d> e(3);
e[0] = X_current.row(F(f, 2)) - X_current.row(F(f, 1)); // edge opposite of v_0
e[1] = X_current.row(F(f, 0)) - X_current.row(F(f, 2)); // opposite of v_1
e[2] = X_current.row(F(f, 1)) - X_current.row(F(f, 0)); // opposite of v_2
normal.row(f) = e[2].cross(-e[1]).normalized();
if (with_jacobian) {
double area = 0.5 * e[0].cross(-e[2]).norm();
vector<Vector3d> en(3);
for (int i = 0; i < 3; i++)
en[i] = e[i].normalized(); // direction is important, therefore we do not precompute them per edge earlier
vector<Vector3d> edge_normal(3);
for (int i = 0; i < 3; i++) {
cos_alpha(f, i) = -en[(i + 1) % 3].dot(en[(i + 2) % 3]); // angle at v_i
h_inverse(f, i) = 0.5 * edge_length(FE_adj[f][i]) / area; // height ending in v_i
}
}
}
for (int e = 0; e < edges; e++) {
if (EF_adj(e, 1) != -1) { // no border edge
// indexing
int face = EF_adj(e, 0); // adjacent face 1
int face_dot = EF_adj(e, 1); // adjacent face 2
// angle
double sin_theta_half = (normal.row(face) - normal.row(face_dot)).norm() * 0.5;
double cos_theta_half = (normal.row(face) + normal.row(face_dot)).norm() * 0.5;
double theta = atan2(sin_theta_half, cos_theta_half) * 2.;
f(c) = alpha * (theta - angle_target[e]);
// first derivative
if (with_jacobian) {
// indexing
vector<int> f_v(3), f_dot_v(3); // f_v 0,1,2 corresponds to v0,v1,v2 --- f_dot_v 0,1,2 corresponds to v1,v2,v3
for (int i = 0; i < 3; i++) {
f_v[i] = EF6(e, i);
f_dot_v[i] = EF6(e, 3 + i);
}
// jacobian
vector< Vector3d > delta_theta(4);
delta_theta[0] = -h_inverse(face, f_v[0]) * normal.row(face);
delta_theta[1] = cos_alpha(face, f_v[2]) * h_inverse(face, f_v[1]) * normal.row(face) + cos_alpha(face_dot, f_dot_v[1]) * h_inverse(face_dot, f_dot_v[0]) * normal.row(face_dot);
delta_theta[2] = cos_alpha(face, f_v[1]) * h_inverse(face, f_v[2]) * normal.row(face) + cos_alpha(face_dot, f_dot_v[0]) * h_inverse(face_dot, f_dot_v[1]) * normal.row(face_dot);
delta_theta[3] = -h_inverse(face_dot, f_dot_v[2]) * normal.row(face_dot);
for (int i = 0; i < 4; i++) // x0,x1,x2,x3
for (int j = 0; j < 3; j++) // x,y,z
triJ.push_back(Tri(c, j * verts + E4(e, i), alpha * delta_theta[i](j)));
}
c++;
}
}
// positions
// ---------
// constrain each vertex that hasn't been affected
// and those that are on fixed boundaries
for (int v = 0; v < verts; v++) {
for (int i = 0; i < 3; i++) {
if (!vertex_constrained_by_edge[v] /*&& !fixed_boundary_vert[v]*/) {
f(c) = lambda * (X_current(v, i) - X_restshape(v, i));
if (with_jacobian)
triJ.push_back(Tri(c, i * verts + v, lambda));
c++;
}
}
}
if (with_jacobian) {
J.resize(total_constraints, verts * 3);
J.setFromTriplets(triJ.begin(), triJ.end());
}
}
void RestShape::adjust_restshape(
const MatrixXd& X_simulation,
const MatrixXd& Vm,
const double t_stretch,
const double t_compress,
MatrixXd& X_restshape
) {
vector<double> edge_adjustment(edges, 0.);
adjust_restshape(X_simulation, Vm, t_stretch, t_compress, edge_adjustment, X_restshape);
}
void RestShape::adjust_restshape(
const MatrixXd& X_simulation,
const MatrixXd& Vm,
const double t_stretch,
const double t_compress,
const vector<double>& edge_adjustment,
MatrixXd & X_restshape
) {
verts = X_restshape.rows();
// calculate the new length of each edge
// -------------------------------------
vector< double > l_target(edges);
double original_diff = 0;
vector<int> edge_constraints(edges, 0);
int edge_constraints_count = 0;
for (int e = 0; e < edges; e++) {
double l_rest = (X_restshape.row(E(e, 0)) - X_restshape.row(E(e, 1))).norm() + edge_adjustment[e];
double l_sim = (X_simulation.row(E(e, 0)) - X_simulation.row(E(e, 1))).norm();
double ratio = l_sim / l_rest;
if (ratio > t_stretch) {
l_target[e] = l_sim / t_stretch; // es soll: l_rest_neu * t_rtretch = l_sim
edge_constraints[e] = edge_constraints_count;
edge_constraints_count++;
//cout << "-- edge " << e << " too short " << l_rest << " need " << l_target[e] << endl;
}
else if (ratio < t_compress) {
l_target[e] = l_sim / t_compress;
edge_constraints[e] = true;
edge_constraints_count++;
//cout << "-- edge " << e << " too long " << l_rest << " need " << l_target[e] << endl;
}
else {
l_target[e] = l_rest;
}
original_diff += (l_target[e]* l_target[e] - l_rest* l_rest)* (l_target[e] * l_target[e] - l_rest * l_rest);
}
if (edge_constraints_count== 0) return;
// calculate old angles of the rest shape
// --------------------------------------
vector< double > old_theta(edges, 0);
MatrixXd old_normal(faces, 3);
for (int f = 0; f < faces; f++) {
Vector3d e1 = X_restshape.row(F(f, 2)) - X_restshape.row(F(f, 0)); // opposite of v_1
Vector3d e2 = X_restshape.row(F(f, 1)) - X_restshape.row(F(f, 0)); // opposite of v_2
old_normal.row(f) = e2.cross(e1).normalized();
}
for (int e = 0; e < edges; e++) {
if (EF_adj(e, 1) != -1) { // no border edge
// indexing
int face = EF_adj(e, 0); // adjacent face 1
int face_dot = EF_adj(e, 1); // adjacent face 2
// angle
double sin_theta_half = (old_normal.row(face) - old_normal.row(face_dot)).norm() * 0.5;
double cos_theta_half = (old_normal.row(face) + old_normal.row(face_dot)).norm() * 0.5;
old_theta[e] = atan2(sin_theta_half, cos_theta_half) * 2.;
//old_theta[e] = 0.;
}
}
// use Gauss-Newton to calculate the new rest shape with new edge lengths
// ----------------------------------------------------------------------
double residual = 1.;
MatrixXd X_current = X_restshape;
bool change = false;
double eps = 0.;// 1.e-8;
while (residual > eps) { // repeat Gauss-Newton steps
VectorXd f;
SparseMatrix<double> J;
shape_energy(X_current, X_restshape, l_target, old_theta, edge_constraints_count, edge_constraints, f, J, true);
double energy_start_of_step = f.dot(f);
if (energy_start_of_step < 1e-8) {
cout << "-- energy almost 0 already" << endl;
break; // nothing to do here
}
// find the step direction / solve system
// -----------------------
SparseMatrix<double> D = J.transpose() * J;
VectorXd dir_vec;
LDLTSolver solver;
solver.setSystem(D);
solver.solve(J.transpose() * f, dir_vec);
MatrixXd dir(verts, 3); // transform from vector to Matrix with x,y,z columns
dir.col(0) = dir_vec.head(verts);
dir.col(1) = dir_vec.segment(verts, verts);
dir.col(2) = dir_vec.tail(verts);
// find best step size
// -------------------
MatrixXd X_updated;
MatrixXd X_current_stepsize = X_current;
double stepsize = 0.0001;
//double stepsize = 1.;
// We start with a small step size, since most of the time we are already ultra close to the best solution. We double the stepsize when possible.
// If the energy only gets larger, even for this tiny step size, we can break instantly and just use the old solution.
double energy_updated;
double energy_current_stepsize = energy_start_of_step;
do {
energy_updated = energy_current_stepsize;
X_updated = X_current_stepsize;
stepsize *= 2.;
X_current_stepsize = X_current - stepsize * dir; // new solution
VectorXd f_step;
shape_energy(X_current_stepsize, X_restshape, l_target, old_theta, edge_constraints_count, edge_constraints, f_step, J, false); // new energy, no jacobian needed
energy_current_stepsize = f_step.dot(f_step);
} while (energy_current_stepsize < (energy_updated - eps) && stepsize < 100.);
// check, if the energy went down
residual = energy_start_of_step - energy_updated;
if (residual <= eps) { // no improvement, stop Gauss-Newton
//X_updated = X_current;
cout << "-- Gauss-Newton only made it worse." << endl;
cout << "-- final stepsize " << stepsize << endl;
cout << "-- energy old " << fixed << setprecision(16) << energy_start_of_step << endl;
cout << "-- energy new " << energy_current_stepsize << endl;
}
else { // good improvement
change = true;
X_current = X_updated;
cout << "-- final stepsize " << stepsize << endl;
cout << "-- Gauss-Newton old energy " << energy_start_of_step << endl;
cout << "-- Gauss-Newton final energy " << energy_updated << endl;
}
}
// double check if new edge lenghts are ok
// -------------------------------------
// TODO outcomment everything below
if (change) {
X_restshape = X_current;
double diff = 0;
double diff_constraint = 0;
for (int e = 0; e < edges; e++) {
Vector3d dx = (X_restshape.row(E(e, 0)) - X_restshape.row(E(e, 1)));
double l_now = dx.dot(dx);
double single_diff = (l_target[e] * l_target[e] - l_now) * (l_target[e] * l_target[e] - l_now);
diff += single_diff;
//if (edge_constraints[e] > 0)
// diff_constraint += single_diff;
}
cout << "-- Final difference to wanted lenghts: " << diff << " difference before: " << original_diff << endl;
//cout << "-- Final difference to wanted constrs: " << diff_constraint << " difference before: " << original_diff << endl;
}
}
| 39.261792 | 193 | 0.532348 | [
"shape",
"vector",
"transform"
] |
7228240259c1c47bd2a2343e4b21d7fb4dc5d7d7 | 1,310 | cc | C++ | src/contests/2010-regional/H/H.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | 2 | 2019-09-07T17:00:26.000Z | 2020-08-05T02:08:35.000Z | src/contests/2010-regional/H/H.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | null | null | null | src/contests/2010-regional/H/H.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define FR(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef vector<int> vi;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<double> vd;
vd minL = { 125, 90, 0.25 };
vd maxL = { 290, 155, 7 };
vd maxPk = { 380, 300, 50 };
double l, h, t;
double s = 0;
bool islet() {
vd A = { l, h, t };
FR(i, 3) {
if (minL[i] > A[i])
return false;
}
FR(i, 3) {
if (maxL[i] < A[i])
return false;
}
return true;
}
bool ismail() {
vd A = { l, h, t };
FR(i, 3) {
if (minL[i] > A[i]) {
return false;
}
}
if ((2*h + 2*t + l) > 2100) return false;
return true;
}
bool isparc() {
vd A = { l, h, t };
FR(i, 3) {
if (A[i] > maxPk[i])
return true;
}
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
while (cin >> l >> h >> t) {
if (l == 0 && h == 0 && t == 0) break;
s = l + h + t;
vd A = { l, h, t };
sort(begin(A), end(A));
l = A[2], h = A[1], t = A[0];
// is let
if (!ismail()) {
cout << "not mailable" << endl;
} else if (islet()) {
cout << "letter" << endl;
} else if (isparc()) {
cout << "parcel" << endl;
} else {
cout << "packet" << endl;
}
}
}
| 16.582278 | 46 | 0.448092 | [
"vector"
] |
72285e86e18343b62d42dcac434409f405ebe634 | 1,498 | hpp | C++ | include/mcnla/core/la/dense/routine/dot.hpp | emfomy/mcnla | 9f9717f4d6449bbd467c186651856d6212035667 | [
"MIT"
] | null | null | null | include/mcnla/core/la/dense/routine/dot.hpp | emfomy/mcnla | 9f9717f4d6449bbd467c186651856d6212035667 | [
"MIT"
] | null | null | null | include/mcnla/core/la/dense/routine/dot.hpp | emfomy/mcnla | 9f9717f4d6449bbd467c186651856d6212035667 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @file include/mcnla/core/la/dense/routine/dot.hpp
/// @brief The BLAS DOT routine.
///
/// @author Mu Yang <<emfomy@gmail.com>>
///
#ifndef MCNLA_CORE_LA_DENSE_ROUTINE_DOT_HPP_
#define MCNLA_CORE_LA_DENSE_ROUTINE_DOT_HPP_
#include <mcnla/core/la/def.hpp>
#include <mcnla/core/matrix.hpp>
#include <mcnla/core/la/raw/blas/dot.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The MCNLA namespace
//
namespace mcnla {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The linear algebra namespace
//
namespace la {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @ingroup la_dense_blas1_module
/// @brief Computes a vector-vector dot product.
///
//@{
template <typename _Val>
inline _Val dot(
const DenseVector<_Val> &x,
const DenseVector<_Val> &y
) noexcept {
mcnla_assert_eq(x.sizes(), y.sizes());
return detail::dot(x.len(), x.valPtr(), x.stride(), y.valPtr(), y.stride());
}
template <typename _Val>
inline _Val dot(
const DenseVector<_Val> &x
) noexcept {
return dot(x, x);
}
//@}
} // namespace la
} // namespace mcnla
#endif // MCNLA_CORE_LA_DENSE_ROUTINE_DOT_HPP_
| 28.807692 | 128 | 0.453271 | [
"vector"
] |
5cfcea12affd54e50353adfc122b3c3c6b0b7501 | 2,224 | cpp | C++ | USACOcontests/platinum/2016.01/fortmoo.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | 14 | 2019-08-14T00:43:10.000Z | 2021-12-16T05:43:31.000Z | USACOcontests/platinum/2016.01/fortmoo.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | null | null | null | USACOcontests/platinum/2016.01/fortmoo.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | 6 | 2020-12-30T03:30:17.000Z | 2022-03-11T03:40:02.000Z | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pii;
template <typename T1, typename T2>
ostream &operator <<(ostream &os, pair<T1, T2> p){os << p.first << " " << p.second; return os;}
template <typename T>
ostream &operator <<(ostream &os, vector<T> &v){for(T i : v)os << i << ", "; return os;}
template <typename T>
ostream &operator <<(ostream &os, set<T> s){for(T i : s) os << i << ", "; return os;}
template <typename T1, typename T2>
ostream &operator <<(ostream &os, map<T1, T2> m){for(pair<T1, T2> i : m) os << i << endl; return os;}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
freopen("fortmoo.in", "r", stdin);
freopen("fortmoo.out", "w", stdout);
int N, M; cin >> N >> M;
string grid[N];
for(int i = 0; i < N; i++){
cin >> grid[i];
}
bool swmp[N][M];
fill(swmp[0], swmp[N-1]+M, false);
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
if(grid[i][j] == 'X'){
swmp[i][j] = true;
}
}
}
int pfx[N][M];
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
pfx[i][j] = swmp[i][j];
}
}
for(int i = 1; i < N; i++){
for(int j = 0; j < M; j++){
pfx[i][j] += pfx[i-1][j];
}
}
int O_o_o_O = 0;
for(int i = 0; i < N; i++){
for(int j = i+1; j < N; j++){
int startloc = -1;
for(int k = 0; k < M; k++){
if(swmp[i][k] || swmp[j][k]){
startloc = -1;
continue;
}
if(pfx[i][k] == pfx[j][k]){
if(startloc == -1){
startloc = k;
}
pii ul = pii(i, startloc), lr = pii(j, k);
if(O_o_o_O < (lr.first - ul.first + 1) * (lr.second - ul.second + 1)){
O_o_o_O = (lr.first - ul.first + 1) * (lr.second - ul.second + 1);
//cout << ul << " " << lr << endl;
}
}
}
}
}
cout << O_o_o_O << endl;
return 0;
}
| 30.054054 | 101 | 0.415468 | [
"vector"
] |
cf0224c4e36035f7c5568be02a0ff738aec588e6 | 5,254 | cpp | C++ | MCGIDI/Test/samplePhotoAtomic/samplePhotoAtomic.cpp | Mathnerd314/gidiplus | ed4c48ab399a964fe782f73d0a065849b00090bb | [
"MIT-0",
"MIT"
] | null | null | null | MCGIDI/Test/samplePhotoAtomic/samplePhotoAtomic.cpp | Mathnerd314/gidiplus | ed4c48ab399a964fe782f73d0a065849b00090bb | [
"MIT-0",
"MIT"
] | null | null | null | MCGIDI/Test/samplePhotoAtomic/samplePhotoAtomic.cpp | Mathnerd314/gidiplus | ed4c48ab399a964fe782f73d0a065849b00090bb | [
"MIT-0",
"MIT"
] | null | null | null | /*
# <<BEGIN-copyright>>
# Copyright 2019, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: MIT
# <<END-copyright>>
*/
static char const *description = "Reads a photo-atomic protare and loops over each reaction. For each reaction, one product sample is done at a list of projectile energies.";
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <set>
#include "MCGIDI.hpp"
#include "MCGIDI_testUtilities.hpp"
int main2( int argc, char **argv );
/*
=========================================================
*/
int main( int argc, char **argv ) {
try {
main2( argc, argv ); }
catch (char const *str) {
std::cout << str << std::endl;
return( EXIT_FAILURE );
}
exit( EXIT_SUCCESS );
}
/*
=========================================================
*/
int main2( int argc, char **argv ) {
PoPI::Database pops( "../../../GIDI/Test/pops.xml" );
std::string projectileID( PoPI::IDs::photon );
GIDI::Protare *protare;
GIDI::Transporting::Particles particles;
void *rngState = nullptr;
unsigned long long seed = 1;
std::set<int> reactionsToExclude;
std::cerr << " " << __FILE__;
for( int i1 = 1; i1 < argc; i1++ ) std::cerr << " " << argv[i1];
std::cerr << std::endl;
MCGIDI_test_rngSetup( seed );
argvOptions2 argv_options( "sampleProducts", description );
argv_options.add( argvOption2( "--map", true, "The map file to use." ) );
argv_options.add( argvOption2( "--tid", true, "The PoPs id of the target." ) );
argv_options.add( argvOption2( "--all", false, "If present, all particles are sampled; otherwise only transporting particles are sampled." ) );
argv_options.parseArgv( argc, argv );
std::string mapFilename = argv_options.find( "--map" )->zeroOrOneOption( argv, "../../../GIDI/Test/all.map" );
std::string targetID = argv_options.find( "--tid" )->zeroOrOneOption( argv, "O16" );
GIDI::Map::Map map( mapFilename, pops );
GIDI::Construction::Settings construction( GIDI::Construction::ParseMode::all, GIDI::Construction::PhotoMode::atomicOnly );
protare = map.protare( construction, pops, projectileID, targetID );
GIDI::Styles::TemperatureInfos temperatures = protare->temperatures( );
for( GIDI::Styles::TemperatureInfos::const_iterator iter = temperatures.begin( ); iter != temperatures.end( ); ++iter ) {
std::cout << "label = " << iter->heatedCrossSection( ) << " temperature = " << iter->temperature( ).value( ) << std::endl;
}
std::string label( temperatures[0].griddedCrossSection( ) );
MCGIDI::Transporting::MC MC( pops, projectileID, &protare->styles( ), label, GIDI::Transporting::DelayedNeutrons::on, 20.0 );
MC.sampleNonTransportingParticles( argv_options.find( "--all" )->present( ) );
GIDI::Transporting::Groups_from_bdfls groups_from_bdfls( "../../../GIDI/Test/bdfls" );
GIDI::Transporting::Fluxes_from_bdfls fluxes_from_bdfls( "../../../GIDI/Test/bdfls", 0 );
GIDI::Transporting::Particle photon( PoPI::IDs::photon, groups_from_bdfls.getViaGID( 70 ) );
photon.appendFlux( fluxes_from_bdfls.getViaFID( 1 ) );
particles.add( photon );
MCGIDI::DomainHash domainHash( 4000, 1e-8, 10 );
MCGIDI::Protare *MCProtare;
MCProtare = MCGIDI::protareFromGIDIProtare( *protare, pops, MC, particles, domainHash, temperatures, reactionsToExclude );
MCGIDI::Sampling::Input input( true, MCGIDI::Sampling::Upscatter::Model::none );
std::size_t numberOfReactions = MCProtare->numberOfReactions( );
MCGIDI::Sampling::StdVectorProductHandler products;
for( std::size_t i1 = 0; i1 < numberOfReactions; ++i1 ) {
MCGIDI::Reaction const *reaction = MCProtare->reaction( i1 );
double threshold = MCProtare->threshold( i1 );
std::cout << "reaction (" << std::setw( 3 ) << i1 << ") = " << reaction->label( ).c_str( ) << " threshold = " << threshold << std::endl;
if( threshold < 1e-13 ) threshold = 1e-13;
for( double energy = threshold; energy < 100; energy *= 2 ) {
products.clear( );
std::cout << " energy = " << energy << std::endl;
reaction->sampleProducts( MCProtare, energy, input, float64RNG64, rngState, products );
for( std::size_t i2 = 0; i2 < products.size( ); ++i2 ) {
MCGIDI::Sampling::Product const &product = products[i2];
std::cout << " productIndex " << std::setw( 4 ) << product.m_productIndex;
if( product.m_sampledType == MCGIDI::Sampling::SampledType::unspecified ) {
std::cout << " unspecified distribution" << std::endl; }
else {
double p = sqrt( product.m_px_vx * product.m_px_vx + product.m_py_vy * product.m_py_vy + product.m_pz_vz * product.m_pz_vz );
std::cout << " KE = " << product.m_kineticEnergy << " p = " << p << " m_px_vx = " << product.m_px_vx <<
" m_py_vy = " << product.m_py_vy << " m_pz_vz = " << product.m_pz_vz << std::endl;
}
}
}
}
delete protare;
delete MCProtare;
return( EXIT_SUCCESS );
}
| 41.698413 | 174 | 0.60925 | [
"model"
] |
cf0c8d6f75d3ec10013ccf3b14fda1bd95d85bcd | 4,127 | cc | C++ | pyaims/src/libpyaims/vector/numpytypes.cc | brainvisa/aims-free | 5852c1164292cadefc97cecace022d14ab362dc4 | [
"CECILL-B"
] | 4 | 2019-07-09T05:34:10.000Z | 2020-10-16T00:03:15.000Z | pyaims/src/libpyaims/vector/numpytypes.cc | brainvisa/aims-free | 5852c1164292cadefc97cecace022d14ab362dc4 | [
"CECILL-B"
] | 72 | 2018-10-31T14:52:50.000Z | 2022-03-04T11:22:51.000Z | pyaims/src/libpyaims/vector/numpytypes.cc | brainvisa/aims-free | 5852c1164292cadefc97cecace022d14ab362dc4 | [
"CECILL-B"
] | null | null | null |
#include <pyaims/vector/numpytypes_d.h>
#include <iostream>
#include <cstdio>
PyArray_Descr* NPY_AimsRGB_Descr()
{
static PyArray_Descr* descr = 0;
if( !descr )
{
PyObject *op;
op = Py_BuildValue( "[(s, s)]", "v", "3u1" );
PyArray_DescrConverter( op, &descr );
Py_DECREF( op );
}
return descr;
}
using namespace std;
PyArray_Descr* NPY_AimsRGBA_Descr()
{
static PyArray_Descr* descr = 0;
if( !descr )
{
PyObject *op;
op = Py_BuildValue( "[(s, s)]", "v", "4u1" );
PyArray_DescrConverter( op, &descr );
Py_DECREF( op );
}
return descr;
}
PyArray_Descr* NPY_AimsHSV_Descr()
{
static PyArray_Descr* descr = 0;
if( !descr )
{
PyObject *op;
op = Py_BuildValue( "[(s, s)]", "v", "3u1" );
PyArray_DescrConverter( op, &descr );
Py_DECREF( op );
}
return descr;
}
int NPY_AimsRGB()
{
return NPY_AimsRGB_Descr()->type_num;
}
int NPY_AimsRGBA()
{
return NPY_AimsRGBA_Descr()->type_num;
}
int NPY_AimsHSV()
{
return NPY_AimsHSV_Descr()->type_num;
}
template PyArray_Descr* NPY_AimsVector_Descr<uint8_t, 2>();
template PyArray_Descr* NPY_AimsVector_Descr<uint8_t, 3>();
template PyArray_Descr* NPY_AimsVector_Descr<uint8_t, 4>();
template PyArray_Descr* NPY_AimsVector_Descr<int8_t, 2>();
template PyArray_Descr* NPY_AimsVector_Descr<int8_t, 3>();
template PyArray_Descr* NPY_AimsVector_Descr<int8_t, 4>();
template PyArray_Descr* NPY_AimsVector_Descr<uint16_t, 2>();
template PyArray_Descr* NPY_AimsVector_Descr<uint16_t, 3>();
template PyArray_Descr* NPY_AimsVector_Descr<uint16_t, 4>();
template PyArray_Descr* NPY_AimsVector_Descr<int16_t, 2>();
template PyArray_Descr* NPY_AimsVector_Descr<int16_t, 3>();
template PyArray_Descr* NPY_AimsVector_Descr<int16_t, 4>();
template PyArray_Descr* NPY_AimsVector_Descr<uint32_t, 2>();
template PyArray_Descr* NPY_AimsVector_Descr<uint32_t, 3>();
template PyArray_Descr* NPY_AimsVector_Descr<uint32_t, 4>();
template PyArray_Descr* NPY_AimsVector_Descr<int32_t, 2>();
template PyArray_Descr* NPY_AimsVector_Descr<int32_t, 3>();
template PyArray_Descr* NPY_AimsVector_Descr<int32_t, 4>();
template PyArray_Descr* NPY_AimsVector_Descr<uint64_t, 2>();
template PyArray_Descr* NPY_AimsVector_Descr<uint64_t, 3>();
template PyArray_Descr* NPY_AimsVector_Descr<uint64_t, 4>();
template PyArray_Descr* NPY_AimsVector_Descr<int64_t, 2>();
template PyArray_Descr* NPY_AimsVector_Descr<int64_t, 3>();
template PyArray_Descr* NPY_AimsVector_Descr<int64_t, 4>();
template PyArray_Descr* NPY_AimsVector_Descr<float, 2>();
template PyArray_Descr* NPY_AimsVector_Descr<float, 3>();
template PyArray_Descr* NPY_AimsVector_Descr<float, 4>();
template PyArray_Descr* NPY_AimsVector_Descr<double, 2>();
template PyArray_Descr* NPY_AimsVector_Descr<double, 3>();
template PyArray_Descr* NPY_AimsVector_Descr<double, 4>();
template int NPY_AimsVector<uint8_t, 2>();
template int NPY_AimsVector<uint8_t, 3>();
template int NPY_AimsVector<uint8_t, 4>();
template int NPY_AimsVector<int8_t, 2>();
template int NPY_AimsVector<int8_t, 3>();
template int NPY_AimsVector<int8_t, 4>();
template int NPY_AimsVector<uint16_t, 2>();
template int NPY_AimsVector<uint16_t, 3>();
template int NPY_AimsVector<uint16_t, 4>();
template int NPY_AimsVector<int16_t, 2>();
template int NPY_AimsVector<int16_t, 3>();
template int NPY_AimsVector<int16_t, 4>();
template int NPY_AimsVector<uint32_t, 2>();
template int NPY_AimsVector<uint32_t, 3>();
template int NPY_AimsVector<uint32_t, 4>();
template int NPY_AimsVector<int32_t, 2>();
template int NPY_AimsVector<int32_t, 3>();
template int NPY_AimsVector<int32_t, 4>();
template int NPY_AimsVector<uint64_t, 2>();
template int NPY_AimsVector<uint64_t, 3>();
template int NPY_AimsVector<uint64_t, 4>();
template int NPY_AimsVector<int64_t, 2>();
template int NPY_AimsVector<int64_t, 3>();
template int NPY_AimsVector<int64_t, 4>();
template int NPY_AimsVector<float, 2>();
template int NPY_AimsVector<float, 3>();
template int NPY_AimsVector<float, 4>();
template int NPY_AimsVector<double, 2>();
template int NPY_AimsVector<double, 3>();
template int NPY_AimsVector<double, 4>();
| 30.345588 | 60 | 0.751393 | [
"vector"
] |
cf1205f573e97c8a060e7ed9ca011af1317d63d0 | 826 | hpp | C++ | mge_v18_student_version/src/mge/core/Subject.hpp | TristanSmeets/Agent-OwO | 9ee94c8fd605cdf2b2274624ef55f83e527ee472 | [
"MIT"
] | null | null | null | mge_v18_student_version/src/mge/core/Subject.hpp | TristanSmeets/Agent-OwO | 9ee94c8fd605cdf2b2274624ef55f83e527ee472 | [
"MIT"
] | null | null | null | mge_v18_student_version/src/mge/core/Subject.hpp | TristanSmeets/Agent-OwO | 9ee94c8fd605cdf2b2274624ef55f83e527ee472 | [
"MIT"
] | null | null | null | #pragma once
#include "mge/core/Observer.hpp"
#include <vector>
#include <algorithm>
#include "mge/util/EventQueue/EventStructs.hpp"
template <typename T> class Subject
{
public:
Subject(){};
virtual ~Subject()
{
std::cout << "GC running on:Subject\n";
for (int index = 0; index < observers.size(); ++index)
{
observers[index] = nullptr;
}
observers.clear();
}
void AddObserver(Observer<T>* observer)
{
observers.push_back(observer);
}
void RemoveObserver(Observer<T>* observer)
{
observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
}
protected:
void notify(const T& eventInfo)
{
for (unsigned int index = 0; index < observers.size(); ++index)
{
observers[index]->OnNotify(eventInfo);
}
}
private:
std::vector<Observer<T>*> observers;
};
| 18.772727 | 94 | 0.676755 | [
"vector"
] |
cf14ec91517f69dc2644e84d998396a82515e784 | 5,863 | cpp | C++ | ConsoleRpg/ConsoleRpg/Event.cpp | LucasRKrueger/RPG_game | bc27de5b1d0e5ca34fc1141b2832c291f667cf5f | [
"MIT"
] | 2 | 2020-05-27T19:58:48.000Z | 2020-05-27T19:58:50.000Z | ConsoleRpg/ConsoleRpg/Event.cpp | LucasRKrueger/RPG_game | bc27de5b1d0e5ca34fc1141b2832c291f667cf5f | [
"MIT"
] | null | null | null | ConsoleRpg/ConsoleRpg/Event.cpp | LucasRKrueger/RPG_game | bc27de5b1d0e5ca34fc1141b2832c291f667cf5f | [
"MIT"
] | null | null | null | #include "Event.h"
Event::Event()
{
this->numberOfEvents = 2;
}
Event::~Event()
{
}
void Event::generateEvent(Character& character)
{
int i = rand() % this->numberOfEvents;
i = 0;
switch (i)
{
case 0:
enemyEncouter(character);
break;
case 1:
puzzleEncouter(character);
break;
case 2:
break;
default:
break;
}
}
void Event::enemyEncouter(Character& character)
{
vector<Enemy> enemies;
int characterLevel = character.getLevel();
GetEnemies(characterLevel, enemies);
StartBattle(enemies, character);
}
void Event::StartBattle(vector<Enemy>& enemies, Character& character)
{
bool isFighting = true;
cout << "THE BATTLE IS ABOUT TO BEGIN\n";
while (isFighting)
{
ShowAttributes(enemies, character);
system("pause");
EnemyTurn(enemies, character);
if (character.characterDoesntHasHp())
{
system("CLS");
cout << "YOU ARE DEAD!\n" << endl;
isFighting = false;
continue;
}
system("CLS");
ShowAttributes(enemies, character);
CharacterTurn(enemies, character);
isFighting = AllEnemiesWithoutHp(enemies);
if (!isFighting)
{
if (enemies.size() > 1)
{
cout << "YOU DEFEATED ALL THE ENEMIES!";
}
character.receiveExperience(enemies.size());
cout << "You're now with " << character.getExp() << "XP!" << endl;
system("pause");
}
system("CLS");
}
}
void Event::puzzleEncouter(Character& character)
{
bool completed = false;
int userAnswer = 0;
int chances = 1;
int randN = 0;
for (size_t i = 1; i < 10; i++)
{
//IMPLEMENT MORE PUZZLES
randN = rand() % 10;
Puzzle puzzle("Puzzles/" + to_string(randN) + ".txt");
while (!completed && chances > 0)
{
chances--;
cin >> userAnswer;
cout << puzzle.getAsString() + "\n";
cout << "Your Answer: ";
cout << "\n";
completed = puzzle.getCorrectAnswer() == userAnswer;
}
if (completed)
{
character.receiveExperience();
cout << "CONGRATS YOU SUCCEDED! You're now with " << character.getExp() << "XP!\n \n";
}
else
{
//IMPLEMENT WHEN XP BECOMES LESS THAN 0 AND LEVEL BIGGER THAN 1
character.stealExperience();
cout << "YOU FAILED! XP STEALED!\n \n";
}
}
}
bool Event::AllEnemiesWithoutHp(vector<Enemy>& enemies)
{
int enemiesWithoutHp = 0;
for (size_t i = 0; i < enemies.size(); i++)
{
if (enemies[i].getHp() <= 0)
{
enemiesWithoutHp += 1;
cout << "YOU DEFEATED THE ENEMY " << i + 1 << "\n\n" << endl;
}
}
return enemiesWithoutHp == 0;
}
vector<int> Event::EnemyAction(vector<Enemy>& enemies)
{
vector<int> actions;
for (size_t i = 0; i < enemies.size(); i++)
{
actions.push_back(i);
actions[i] = rand() % 2;
}
return actions;
}
void Event::GetEnemies(int characterLevel, std::vector<Enemy>& enemies)
{
int position = 0;
if (characterLevel == 1) {
Enemy enemy(rand() % characterLevel + 1);
enemies.push_back(position);
enemies[position] = enemy;
position++;
}
else
{
for (size_t i = characterLevel; i > 2; i -= 2)
{
Enemy enemy(rand() % characterLevel + 5);
enemies.push_back(position);
enemies[position] = enemy;
position++;
}
}
}
void Event::CharacterTurn(std::vector<Enemy>& enemies, Character& character)
{
int enemy;
int action;
cout << "Select 1 to punch and 2 to defend" << endl;
cin >> action;
if (action == 1 && enemies.size() > 1)
{
cout << "Which enemy do you want to punch: " << endl;
cin >> enemy;
}
else if (action != 1)
{
character.setIsDefending(true);
for (size_t i = 1; i < enemies.size(); i++)
{
enemies[i].setIsDefending(false);
}
}
else
{
enemy = 1;
}
int characterDamage = character.getDamage();
system("CLS");
if (action == 1)
{
if (enemies[enemy-1].getIsDefending())
{
cout << "ENEMY IS DEFENDING\n" << endl;
CharacterDamage(characterDamage, enemies, enemy);
enemies[enemy - 1].takeDamage(characterDamage);
cout << "Enemy " << enemy << " taked " << characterDamage << " damage!\n" << endl;
enemies[enemy - 1].setIsDefending(false);
}
else
{
enemies[enemy - 1].takeDamage(characterDamage);
cout << "Enemy " << enemy << " taked " << characterDamage << " damage!\n" << endl;
}
}
system("pause");
}
void Event::CharacterDamage(int& characterDamage, std::vector<Enemy>& enemies, int enemy)
{
bool damageIsGreaterThanZero = characterDamage - (enemies[enemy - 1].getDefence() / 2) > 0;
characterDamage -= enemies[enemy - 1].getDefence() / 2;
characterDamage = damageIsGreaterThanZero ? characterDamage : 0;
}
void Event::EnemyTurn(std::vector<Enemy>& enemies, Character& character)
{
vector<int> actions = EnemyAction(enemies);
int enemyDamage;
for (size_t i = 0; i < actions.size(); i++)
{
if (actions[i] == 1)
{
enemyDamage = enemies[i].getDamage();
system("CLS");
if (character.getIsDefending())
{
cout << "YOU ARE DEFENDING\n" << endl;
EnemyDamage(enemyDamage, character);
character.takeDamage(enemyDamage);
cout << "You taked " << enemyDamage << " Damage!\n" << endl;
character.setIsDefending(false);
}
else
{
character.takeDamage(enemyDamage);
cout << "You taked " << enemyDamage << " Damage!\n" << endl;
}
system("pause");
}
else
{
enemies[i].setIsDefending(true);
character.setIsDefending(false);
}
}
}
void Event::EnemyDamage(int& enemyDamage, Character& character)
{
bool damageIsGreaterThanZero = enemyDamage - (character.getDefence() / 2) > 0;
enemyDamage -= character.getDefence() / 2;
enemyDamage = damageIsGreaterThanZero ? enemyDamage : 0;
}
void Event::ShowAttributes(vector<Enemy>& enemies, Character& character)
{
system("CLS");
cout << "ENEMIES \n " << endl;
for (size_t i = 0; i < enemies.size(); i++)
{
cout << "Enemy " << i + 1 << endl;
cout << enemies[i].getBattleAtributes() << "\n";
}
cout << "\n\n";
cout << "YOU \n\n" << character.getBattleAtributes() << "\n";
} | 19.543333 | 92 | 0.6321 | [
"vector"
] |
cf171f708b7b3f642569f387ef604f0666845097 | 11,734 | cpp | C++ | TabulaRasa/Source/Game/World.cpp | Halliom/Tabula-Rasa | 2c1f1e0373851786cdbdb02c6792f71392ce98f9 | [
"MIT"
] | null | null | null | TabulaRasa/Source/Game/World.cpp | Halliom/Tabula-Rasa | 2c1f1e0373851786cdbdb02c6792f71392ce98f9 | [
"MIT"
] | null | null | null | TabulaRasa/Source/Game/World.cpp | Halliom/Tabula-Rasa | 2c1f1e0373851786cdbdb02c6792f71392ce98f9 | [
"MIT"
] | null | null | null | #include "World.h"
#include "glm/common.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "../Platform/Platform.h"
#include "../Engine/Block.h"
#include "../Engine/Chunk.h"
#include "../Engine/ScriptEngine.h"
#include "../Engine/ChunkManager.h"
#include "../Engine/Core/Memory.h"
#include "../Engine/Camera.h"
#include "../Engine/Console.h"
#include "../Game/WorldGenerator.h"
#include "../Game/Player.h"
#define TOCHUNK_COORD(X, Y, Z) X >= 0 ? X / Chunk::SIZE : (X / Chunk::SIZE) - 1, Y >= 0 ? Y / Chunk::SIZE : (Y / Chunk::SIZE) - 1, Z >= 0 ? Z / Chunk::SIZE : (Z / Chunk::SIZE) - 1
World::World()
{
m_pCurrentPlayer = NULL;
m_pWorldGenerator = NULL;
CachedChunk = NULL;
}
World::~World()
{
if (m_pCurrentPlayer)
{
delete m_pCurrentPlayer;
}
delete m_pWorldGenerator;
delete m_pChunkManager;
}
void World::Initialize()
{
BlockManager::SetupBlocks();
m_pCurrentPlayer = new Player();
m_pCurrentPlayer->BeginPlay();
m_pCurrentPlayer->m_pWorldObject = this;
m_pWorldGenerator = new WorldGenerator(123123, this);
m_pWorldGenerator->LoadFeatures();
// m_pWorldGenerator->AddBiome(new BiomeGrasslands(0, 50, -1, 10));
m_pChunkManager = new ChunkManager(this, m_pWorldGenerator, 1);
m_pChunkManager->LoadNewChunks(glm::ivec3(0, 0, 0));
}
void World::Update(float DeltaTime)
{
glm::ivec3 PlayerChunkPosition = m_pCurrentPlayer->m_Position / (float)Chunk::SIZE;
glm::ivec3 OldPlayerChunkPosition = m_pCurrentPlayer->m_OldPosition / (float)Chunk::SIZE;
// If the player moved to a new chunk
if (PlayerChunkPosition != OldPlayerChunkPosition)
{
// Unload/load chunks (unload first to make room for new ones)
m_pChunkManager->UnloadChunks(PlayerChunkPosition);
m_pChunkManager->LoadNewChunks(PlayerChunkPosition);
}
// Tick the chunks
m_pChunkManager->Tick(DeltaTime);
// Update the player last as chunk updates should take precedence
m_pCurrentPlayer->Update(DeltaTime);
}
Chunk* World::GetLoadedChunk(const int& ChunkX, const int& ChunkY, const int& ChunkZ)
{
if (CachedChunk &&
CachedChunk->m_ChunkX == ChunkX &&
CachedChunk->m_ChunkY == ChunkY &&
CachedChunk->m_ChunkZ == ChunkZ)
{
return CachedChunk;
}
else
{
CachedChunk = m_pChunkManager->GetChunkAt(ChunkX, ChunkY, ChunkZ);
return CachedChunk;
}
}
FORCEINLINE unsigned int ChunkMod(const int& Value)
{
static constexpr int ModuloMinusOne = Chunk::SIZE - 1;
return Value >= 0 ? Value % Chunk::SIZE : ((Value + 1) % Chunk::SIZE) + ModuloMinusOne;
}
Voxel* World::GetBlock(const int& X, const int& Y, const int& Z)
{
Chunk* QueriedChunk = GetLoadedChunk(TOCHUNK_COORD(X, Y, Z));
return QueriedChunk != NULL ? QueriedChunk->GetVoxel(ChunkMod(X), ChunkMod(Y), ChunkMod(Z)) : NULL;;
}
Voxel* World::GetMultiblock(const int &X, const int &Y, const int &Z)
{
int ChunkX = X >= 0 ? X / Chunk::SIZE : (X / Chunk::SIZE) - 1;
int ChunkY = Y >= 0 ? Y / Chunk::SIZE : (Y / Chunk::SIZE) - 1;
int ChunkZ = Z >= 0 ? Z / Chunk::SIZE : (Z / Chunk::SIZE) - 1;
Chunk* QueriedChunk = GetLoadedChunk(ChunkX, ChunkY, ChunkZ);
if (QueriedChunk)
{
// This gets the local coordinate in the chunks local coordinate
// system, which ranges from 0 to 31
int LocalX = ChunkMod(X);
int LocalY = ChunkMod(Y);
int LocalZ = ChunkMod(Z);
Voxel* QueriedVoxel = QueriedChunk->GetVoxel(LocalX, LocalY, LocalZ);
// If we got the child node, set the block operated upon to be the parent (master)
if (QueriedVoxel->Parent != NULL)
{
QueriedVoxel = QueriedVoxel->Parent;
}
// TODO: Shuold we check whether this actually is a multiblock or not
// and if it's not return NULL?
return QueriedVoxel;
}
return NULL;
}
void World::AddBlock(const int& X, const int& Y, const int& Z, const unsigned int& BlockID)
{
AddBlockWithRotation(X, Y, Z, 0, BlockID);
}
void World::AddBlockWithRotation(const int& X, const int& Y, const int& Z, unsigned char Rotation, const unsigned int& BlockID)
{
assert(BlockID != 0);
Chunk* ChunkToAddTo = GetLoadedChunk(TOCHUNK_COORD(X, Y, Z));
if (ChunkToAddTo)
{
// This gets the local coordinate in the chunks local coordinate
// system, which ranges from 0 to 31
int LocalX = ChunkMod(X);
int LocalY = ChunkMod(Y);
int LocalZ = ChunkMod(Z);
ChunkToAddTo->SetVoxel(this, LocalX, LocalY, LocalZ, BlockID, Rotation);
}
}
void World::AddMultiblock(const int &X, const int &Y, const int &Z, const unsigned int &BlockID)
{
BlockInfo BlockIDInfo = BlockManager::LoadedBlocks[BlockID];
unsigned int MultiblockWidth = BlockIDInfo.RenderData.MultiblockRenderData.Width;
unsigned int MultiblockHeight = BlockIDInfo.RenderData.MultiblockRenderData.Height;
unsigned int MultiblockDepth = BlockIDInfo.RenderData.MultiblockRenderData.Depth;
for (unsigned int XCoord = 0; XCoord < MultiblockWidth; ++XCoord)
{
for (unsigned int YCoord = 0; YCoord < MultiblockHeight; ++YCoord)
{
for (unsigned int ZCoord = 0; ZCoord < MultiblockDepth; ++ZCoord)
{
Voxel *CurrentBlock = GetBlock(X + XCoord, Y + YCoord, Z + ZCoord);
if (CurrentBlock)
{
// We can't place a multiblock here since the space is
// already occupied
return;
}
}
}
}
int ChunkX = X >= 0 ? X / Chunk::SIZE : (X / Chunk::SIZE) - 1;
int ChunkY = Y >= 0 ? Y / Chunk::SIZE : (Y / Chunk::SIZE) - 1;
int ChunkZ = Z >= 0 ? Z / Chunk::SIZE : (Z / Chunk::SIZE) - 1;
Chunk *QueriedChunk = GetLoadedChunk(ChunkX, ChunkY, ChunkZ);
if (QueriedChunk)
{
// This gets the local coordinate in the chunks local coordinate
// system, which ranges from 0 to 31
int LocalX = ChunkMod(X);
int LocalY = ChunkMod(Y);
int LocalZ = ChunkMod(Z);
Voxel *Parent = NULL;
for (unsigned int XCoord = 0; XCoord < MultiblockWidth; ++XCoord)
{
for (unsigned int YCoord = 0; YCoord < MultiblockHeight; ++YCoord)
{
for (unsigned int ZCoord = 0; ZCoord < MultiblockDepth; ++ZCoord)
{
if (LocalX >= 16)
{
++ChunkX;
QueriedChunk = GetLoadedChunk(ChunkX, ChunkY, ChunkZ);
LocalX = ChunkMod(LocalX);
}
if (LocalY >= 16)
{
++ChunkY;
QueriedChunk = GetLoadedChunk(ChunkX, ChunkY, ChunkZ);
LocalY = ChunkMod(LocalY);
}
if (LocalZ >= 16)
{
++ChunkZ;
QueriedChunk = GetLoadedChunk(ChunkX, ChunkY, ChunkZ);
LocalZ = ChunkMod(LocalZ);
}
if (XCoord == 0 && YCoord == 0 && ZCoord == 0)
{
Parent = QueriedChunk->GetVoxel(LocalX, LocalY, LocalZ);
}
QueriedChunk->SetVoxel(this, LocalX, LocalY, LocalZ, BlockID, 0, Parent);
++LocalZ;
}
++LocalY;
}
++LocalZ;
}
}
}
void World::RemoveBlock(const int& X, const int& Y, const int& Z)
{
Chunk* QueriedChunk = GetLoadedChunk(TOCHUNK_COORD(X, Y, Z));
if (QueriedChunk)
{
// This gets the local coordinate in the chunks local coordinate
// system, which ranges from 0 to 31
int LocalX = ChunkMod(X);
int LocalY = ChunkMod(Y);
int LocalZ = ChunkMod(Z);
QueriedChunk->RemoveVoxel(this, LocalX, LocalY, LocalZ);
}
}
void World::RemoveMultiblock(const int& X, const int& Y, const int& Z)
{
Voxel *Parent = GetMultiblock(X, Y, Z);
if (Parent)
{
int ChunkX = X >= 0 ? X / Chunk::SIZE : (X / Chunk::SIZE) - 1;
int ChunkY = Y >= 0 ? Y / Chunk::SIZE : (Y / Chunk::SIZE) - 1;
int ChunkZ = Z >= 0 ? Z / Chunk::SIZE : (Z / Chunk::SIZE) - 1;
Chunk *QueriedChunk = GetLoadedChunk(ChunkX, ChunkY, ChunkZ);
if (QueriedChunk)
{
int LocalX = ChunkMod(X);
int LocalY = ChunkMod(Y);
int LocalZ = ChunkMod(Z);
BlockInfo BlockIDInfo = BlockManager::LoadedBlocks[Parent->BlockID];
unsigned int MultiblockWidth = BlockIDInfo.RenderData.MultiblockRenderData.Width;
unsigned int MultiblockHeight = BlockIDInfo.RenderData.MultiblockRenderData.Height;
unsigned int MultiblockDepth = BlockIDInfo.RenderData.MultiblockRenderData.Depth;
for (unsigned int XCoord = 0; XCoord < MultiblockWidth; ++XCoord)
{
for (unsigned int YCoord = 0; YCoord < MultiblockHeight; ++YCoord)
{
for (unsigned int ZCoord = 0; ZCoord < MultiblockDepth; ++ZCoord)
{
++LocalZ;
if (LocalX >= 16)
{
++ChunkX;
QueriedChunk = GetLoadedChunk(ChunkX, ChunkY, ChunkZ);
LocalX = ChunkMod(LocalX);
}
if (LocalY >= 16)
{
++ChunkY;
QueriedChunk = GetLoadedChunk(ChunkX, ChunkY, ChunkZ);
LocalY = ChunkMod(LocalY);
}
if (LocalZ >= 16)
{
++ChunkZ;
QueriedChunk = GetLoadedChunk(ChunkX, ChunkY, ChunkZ);
LocalZ = ChunkMod(LocalZ);
}
QueriedChunk->RemoveVoxel(this, LocalX, LocalY, LocalZ);
}
++LocalY;
}
++LocalZ;
}
}
}
}
FORCEINLINE float Mod(float Value, float Mod)
{
return glm::mod((glm::mod(Value, Mod) + Mod), Mod);
}
// Find t where Direction * t + Origin = integer
float GetStep(float Origin, float Direction)
{
if (Direction < 0)
return GetStep(-Origin, -Direction);
else
{
float Rem = Mod(Origin, 1.0f);
return (1.0f - Rem) / Direction;
}
}
FORCEINLINE float intbound(float s, float ds)
{
if (ds < 0) {
return intbound(-s, -ds);
}
else {
s = Mod(s, 1);
// problem is now s+t*ds = 1
return (1 - s) / ds;
}
}
FORCEINLINE float Floor(float Value)
{
return Value >= 0 ? glm::floor(Value) : -1 * glm::floor(glm::abs(Value));
}
RayHitResult World::RayTraceVoxels(const Ray& Ray)
{
RayHitResult Result = { };
if (Ray.Direction.x == 0 && Ray.Direction.y == 0 && Ray.Direction.z == 0)
{
return Result;
}
glm::vec3 CameraPosition = Ray.Origin;
// The voxel we're starting in
float PositionX = CameraPosition.x >= 0 ? Floor(CameraPosition.x) : Floor(CameraPosition.x - 1.0f);
float PositionY = CameraPosition.y >= 0 ? Floor(CameraPosition.y) : Floor(CameraPosition.y - 1.0f);
float PositionZ = CameraPosition.z >= 0 ? Floor(CameraPosition.z) : Floor(CameraPosition.z - 1.0f);
// The direction in which to take a step
int stepX = Ray.Direction.x > 0 ? 1 : Ray.Direction.x < 0 ? -1 : 0;
int stepY = Ray.Direction.y > 0 ? 1 : Ray.Direction.y < 0 ? -1 : 0;
int stepZ = Ray.Direction.z > 0 ? 1 : Ray.Direction.z < 0 ? -1 : 0;
// How much we need to multiply the Direction vector with to get to an int
glm::vec3 tMax(
intbound(CameraPosition.x, Ray.Direction.x),
intbound(CameraPosition.y, Ray.Direction.y),
intbound(CameraPosition.z, Ray.Direction.z));
// How much we need to multiply the direction vector with to get to the next int
glm::vec3 tDelta(
(float)stepX / Ray.Direction.x,
(float)stepY / Ray.Direction.y,
(float)stepZ / Ray.Direction.z);
// What face we entered through
int FaceX = 0;
int FaceY = 0;
int FaceZ = 0;
do
{
Voxel* Hit = GetBlock(PositionX, PositionY, PositionZ);
if (Hit && Hit->BlockID != 0)
{
Result.Position = glm::ivec3(PositionX, PositionY, PositionZ);
Result.BlockID = Hit->BlockID;
Result.Side = SideHelper::SideFromDirection(FaceX, FaceY, FaceZ);
break;
}
if (tMax.x < tMax.y)
{
if (tMax.x < tMax.z)
{
if (tMax.x > Ray.Distance)
break;
PositionX += stepX;
tMax[0] += tDelta[0];
FaceX = -stepX;
FaceY = 0;
FaceZ = 0;
}
else
{
if (tMax.z > Ray.Distance)
break;
PositionZ += stepZ;
tMax.z += tDelta.z;
FaceX = 0;
FaceY = 0;
FaceZ = -stepZ;
}
}
else
{
if (tMax.y < tMax.z)
{
if (tMax.y > Ray.Distance)
break;
PositionY += stepY;
tMax.y += tDelta.y;
FaceX = 0;
FaceY = -stepY;
FaceZ = 0;
}
else
{
if (tMax.z > Ray.Distance)
break;
PositionZ += stepZ;
tMax.z += tDelta.z;
FaceX = 0;
FaceY = 0;
FaceZ = -stepZ;
}
}
} while (true);
LogF("(%d, %d, %d)", stepX, stepY, stepZ);
return Result;
} | 26.368539 | 179 | 0.64948 | [
"vector"
] |
cf1d78e1832e348cfd67577bf8a58a1bdd3f1432 | 1,943 | cpp | C++ | qt/render_bmp_as_movie/myutilities.cpp | kurekagura/samples | f8aacc470883cf2eb92ae36064cb6d24ffae967f | [
"MIT"
] | null | null | null | qt/render_bmp_as_movie/myutilities.cpp | kurekagura/samples | f8aacc470883cf2eb92ae36064cb6d24ffae967f | [
"MIT"
] | null | null | null | qt/render_bmp_as_movie/myutilities.cpp | kurekagura/samples | f8aacc470883cf2eb92ae36064cb6d24ffae967f | [
"MIT"
] | null | null | null | #include "myutilities.h"
#include <vector>
#include <opencv2/opencv.hpp>
#include <filesystem>
#include <Windows.h>
std::vector<cv::Mat> my_load_images(bool toRGB){
std::vector<cv::Mat> pseudo_device;
//映像入力デバイスを想定,ダミーでオンメモリ(pseudo_device_)に取り込んでおく.
//連番画像ファイルの一覧取得・ソート
const char* input_file_dir = "C:\\dev\\samplevideo\\out-avframe2mat-fhd";
std::vector<std::string> filePathVec;
for (const auto& entry : std::filesystem::directory_iterator(input_file_dir))
filePathVec.push_back(entry.path().string());
sort(filePathVec.begin(), filePathVec.end(), [](std::string& s1, std::string& s2) { return s1 < s2; });
//連番画像ファイルをMatに読み込む
for (const auto& afile : filePathVec) {
cv::Mat mat_bgr = cv::imread(afile);
if(toRGB){
cv::Mat mat_rgb;
cv::cvtColor(mat_bgr, mat_rgb, cv::COLOR_BGR2RGB);
pseudo_device.push_back(mat_rgb);
}else{
pseudo_device.push_back(mat_bgr);
}
}
return pseudo_device;
}
extern uchar* my_load_images_as_uchar2x2(uint* count, uint* width, uint* height, uint* channels, bool toRGB)
{
std::vector<cv::Mat> matVec = my_load_images(toRGB);
cv::Mat& firstMat = matVec[0];
*width = firstMat.cols;
*height = firstMat.rows;
*channels = firstMat.channels();
int step_ = static_cast<int>(firstMat.step);
*count = matVec.size();
size_t size_bitmap = (*width) * (*height) * (*channels);
uchar* images = (uchar*)malloc(sizeof(uchar) * size_bitmap * (*count));
uchar* image_head = images;
for (int i=0; i < *count; i++) {
cv::Mat& mat = matVec[i];
if(mat.isContinuous()){
memcpy(image_head, mat.data, size_bitmap);
image_head += size_bitmap;
}else{
throw "Exception: The Mat must be isContinuous.";
}
}
return images;
}
| 32.383333 | 109 | 0.607308 | [
"vector"
] |
cf1f42d8de692742a1c41aad5a327e91609da61d | 7,632 | cxx | C++ | VTK/Graphics/vtkExtractSelection.cxx | certik/paraview | 973d37b466552ce770ac0674f30040bb7e31d7fe | [
"BSD-3-Clause"
] | 1 | 2016-05-09T00:36:44.000Z | 2016-05-09T00:36:44.000Z | VTK/Graphics/vtkExtractSelection.cxx | certik/paraview | 973d37b466552ce770ac0674f30040bb7e31d7fe | [
"BSD-3-Clause"
] | null | null | null | VTK/Graphics/vtkExtractSelection.cxx | certik/paraview | 973d37b466552ce770ac0674f30040bb7e31d7fe | [
"BSD-3-Clause"
] | 3 | 2015-05-14T21:18:53.000Z | 2022-03-07T02:53:45.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkExtractSelection.cxx,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkExtractSelection.h"
#include "vtkDataSet.h"
#include "vtkIdList.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSelection.h"
#include "vtkDataSet.h"
#include "vtkUnstructuredGrid.h"
#include "vtkExtractSelectedIds.h"
#include "vtkExtractSelectedFrustum.h"
#include "vtkExtractSelectedLocations.h"
#include "vtkExtractSelectedThresholds.h"
#include "vtkStreamingDemandDrivenPipeline.h"
vtkCxxRevisionMacro(vtkExtractSelection, "$Revision: 1.18 $");
vtkStandardNewMacro(vtkExtractSelection);
//----------------------------------------------------------------------------
vtkExtractSelection::vtkExtractSelection()
{
this->SetNumberOfInputPorts(2);
this->IdsFilter = vtkExtractSelectedIds::New();
this->FrustumFilter = vtkExtractSelectedFrustum::New();
this->LocationsFilter = vtkExtractSelectedLocations::New();
this->ThresholdsFilter = vtkExtractSelectedThresholds::New();
}
//----------------------------------------------------------------------------
vtkExtractSelection::~vtkExtractSelection()
{
this->IdsFilter->Delete();
this->FrustumFilter->Delete();
this->LocationsFilter->Delete();
this->ThresholdsFilter->Delete();
}
//----------------------------------------------------------------------------
//needed because parent class sets output type to input type
//and we sometimes want to change it to make an UnstructuredGrid regardless of
//input type
int vtkExtractSelection::RequestDataObject(
vtkInformation*,
vtkInformationVector** inputVector ,
vtkInformationVector* outputVector)
{
vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
if (!inInfo)
{
return 0;
}
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
if (input)
{
int passThrough = 0;
vtkInformation* selInfo = inputVector[1]->GetInformationObject(0);
if (selInfo)
{
vtkSelection *sel = vtkSelection::SafeDownCast(
selInfo->Get(vtkDataObject::DATA_OBJECT()));
if (sel->GetProperties()->Has(vtkSelection::PRESERVE_TOPOLOGY()) &&
sel->GetProperties()->Get(vtkSelection::PRESERVE_TOPOLOGY()) != 0)
{
passThrough = 1;
}
}
vtkInformation* info = outputVector->GetInformationObject(0);
vtkDataSet *output = vtkDataSet::SafeDownCast(
info->Get(vtkDataObject::DATA_OBJECT()));
if (!output
||
(passThrough && !output->IsA(input->GetClassName()))
||
(!passThrough && !output->IsA("vtkUnstructuredGrid"))
)
{
vtkDataSet* newOutput = NULL;
if (!passThrough)
{
// The mesh will be modified.
newOutput = vtkUnstructuredGrid::New();
}
else
{
// The mesh will not be modified.
newOutput = input->NewInstance();
}
newOutput->SetPipelineInformation(info);
newOutput->Delete();
this->GetOutputPortInformation(0)->Set(
vtkDataObject::DATA_EXTENT_TYPE(), newOutput->GetExtentType());
}
return 1;
}
return 0;
}
//----------------------------------------------------------------------------
int vtkExtractSelection::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *selInfo = inputVector[1]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// verify the input, selection and output
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
if ( ! input )
{
vtkErrorMacro(<<"No input specified");
return 0;
}
if ( ! selInfo )
{
//When not given a selection, quietly select nothing.
return 1;
}
vtkSelection *sel = vtkSelection::SafeDownCast(
selInfo->Get(vtkDataObject::DATA_OBJECT()));
if (!sel->GetProperties()->Has(vtkSelection::CONTENT_TYPE()))
{
vtkErrorMacro("Selection missing CONTENT_TYPE.");
return 0;
}
vtkDataSetAlgorithm *subFilter = NULL;
int seltype = sel->GetProperties()->Get(vtkSelection::CONTENT_TYPE());
switch (seltype)
{
case vtkSelection::GLOBALIDS:
case vtkSelection::PEDIGREEIDS:
case vtkSelection::VALUES:
case vtkSelection::INDICES:
{
subFilter = this->IdsFilter;
break;
}
case vtkSelection::FRUSTUM:
{
subFilter = this->FrustumFilter;
break;
}
case vtkSelection::LOCATIONS:
{
subFilter = this->LocationsFilter;
break;
}
case vtkSelection::THRESHOLDS:
{
subFilter = this->ThresholdsFilter;
break;
}
default:
vtkErrorMacro("Unrecognized CONTENT_TYPE.");
return 0;
}
subFilter->SetInput(1, sel);
vtkDataSet *output = vtkDataSet::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkStreamingDemandDrivenPipeline* sddp =
vtkStreamingDemandDrivenPipeline::SafeDownCast(
subFilter->GetExecutive());
vtkDebugMacro(<< "Preparing subfilter to extract from dataset");
//pass all required information to the helper filter
int piece = -1;
int npieces = -1;
int *uExtent;
if (outInfo->Has(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()))
{
piece = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
npieces = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES());
if (sddp)
{
sddp->SetUpdateExtent(0, piece, npieces, 0);
}
}
if (outInfo->Has(
vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()))
{
uExtent = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT());
if (sddp)
{
sddp->SetUpdateExtent(0, uExtent);
}
}
vtkDataSet* inputCopy = input->NewInstance();
inputCopy->ShallowCopy(input);
subFilter->SetInput(0, inputCopy);
subFilter->Update();
vtkDataSet* ecOutput = vtkDataSet::SafeDownCast(
subFilter->GetOutputDataObject(0));
output->ShallowCopy(ecOutput);
//make sure everything is deallocated
inputCopy->Delete();
ecOutput->Initialize();
subFilter->SetInput(0, (vtkDataSet*)NULL);
subFilter->SetInput(1, (vtkSelection*)NULL);
return 1;
}
//----------------------------------------------------------------------------
void vtkExtractSelection::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//----------------------------------------------------------------------------
int vtkExtractSelection::FillInputPortInformation(
int port, vtkInformation* info)
{
if (port==0)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
}
else
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);
}
return 1;
}
| 29.241379 | 78 | 0.631944 | [
"mesh"
] |
cf2284489214067efa02a990ffe1dd6a2e707b79 | 50,320 | cpp | C++ | src/njli/World.cpp | njligames/Engine | 899c7b79cea33a72fc34f159134f721b56715d3d | [
"MIT"
] | 1 | 2019-02-13T05:41:54.000Z | 2019-02-13T05:41:54.000Z | src/njli/World.cpp | njligames/Engine | 899c7b79cea33a72fc34f159134f721b56715d3d | [
"MIT"
] | null | null | null | src/njli/World.cpp | njligames/Engine | 899c7b79cea33a72fc34f159134f721b56715d3d | [
"MIT"
] | null | null | null | //
// World.cpp
// JLIGameEngineTest
//
// Created by James Folk on 11/21/14.
// Copyright (c) 2014 James Folk. All rights reserved.
//
#include "World.h"
#include "SceneState.h"
#include "SceneStateMachine.h"
#include "btVector2.h"
#include "GLPlatform.h"
#include "tinyxml.h"
#include "Log.h"
#define TAG "World.cpp"
#include "PhysicsWorld.h"
#include "AbstractRender.h"
#include "MaterialProperty.h"
#include "ShaderProgram.h"
#include "Material.h"
#include "Image.h"
#define FORMATSTRING "{\"njli::World\":[]}"
#include "btPrint.h"
#include "JsonJLI.h"
#include "btQuickprof.h"
#include "unistd.h"
#include <signal.h>
namespace njli
{
World *World::s_Instance = NULL;
void World::createInstance()
{
if(NULL == s_Instance)
{
s_Instance = new World();
}
MaterialProperty::initReferences();
}
void World::destroyInstance()
{
delete s_Instance;
s_Instance = NULL;
}
World * World::getInstance()
{
DEBUG_ASSERT(s_Instance);
// if(NULL == s_Instance)
// {
// s_Instance = new World();
// }
return s_Instance;
}
bool World::hasInstance()
{
return (NULL != s_Instance);
}
World::World() :
m_WorldFactory(new WorldFactory()),
m_WorldResourceLoader(new WorldResourceLoader()),
m_WorldClock(new WorldClock()),
m_WorldLuaVirtualMachine(new WorldLuaVirtualMachine()),
// m_WorldPythonVirtualMachine(new WorldPythonVirtualMachine()),
m_stateMachine(new WorldStateMachine()),
// m_Name("MyWorld"),
m_ViewPortDimensions(new btVector2()),
m_Scene(NULL),
m_WorldSocket(new WorldSocket),
m_WorldHUD(new WorldHUD),
m_WorldInput(new WorldInput),
m_WorldSound(new WorldSound),
m_WorldDebugDrawer(new WorldDebugDrawer),
//m_WorldSQLite(new WorldSQLite),
//m_WorldFacebook(new WorldFacebook),
m_enableDebugDraw(false),
m_DebugDrawCamera(NULL),
m_DebugDrawMaterial(NULL),
// m_TouchCamera(NULL),
m_SocketEnabled(false),
m_SocketAddress("192.168.1.10"),
m_SocketPort(2223),
m_BackgroundColor(new btVector4(.5, .5, .5, .5)),
m_DeviceName("NOT - SET"),
m_AnimationPaused(false),
m_GamePaused(false)
{
addChild(m_WorldSound);
addChild(m_WorldInput);
addChild(m_WorldHUD);
addChild(m_WorldSocket);
addChild(m_stateMachine);
addChild(m_WorldLuaVirtualMachine);
addChild(m_WorldClock);
addChild(m_WorldResourceLoader);
addChild(m_WorldFactory);
//addChild(m_WorldFacebook);
// getWorldSQLite()->createBuffer();
}
World::~World()
{
// getWorldSQLite()->deleteBuffer();
delete m_BackgroundColor;m_BackgroundColor=NULL;
//delete m_WorldFacebook;m_WorldFacebook=NULL;
//delete m_WorldSQLite;m_WorldSQLite=NULL;
delete m_WorldDebugDrawer;m_WorldDebugDrawer=NULL;
delete m_WorldSound;m_WorldSound=NULL;
delete m_WorldInput;m_WorldInput=NULL;
delete m_WorldHUD;m_WorldHUD=NULL;
delete m_WorldSocket;m_WorldSocket=NULL;
delete m_ViewPortDimensions;m_ViewPortDimensions=NULL;
delete m_stateMachine;m_stateMachine=NULL;
delete m_WorldLuaVirtualMachine;m_WorldLuaVirtualMachine=NULL;
delete m_WorldClock;m_WorldClock=NULL;
delete m_WorldResourceLoader;m_WorldResourceLoader=NULL;
delete m_WorldFactory;m_WorldFactory=NULL;
if(m_DebugDrawMaterial)
{
Material::destroy(m_DebugDrawMaterial);
m_DebugDrawMaterial = NULL;
}
}
WorldFactory *World::getWorldFactory()
{
s32 idx = getChildIndex(m_WorldFactory);
if(idx != -1)
return dynamic_cast<WorldFactory*>(getChild(idx));
return NULL;
}
const WorldFactory *World::getWorldFactory() const
{
s32 idx = getChildIndex(m_WorldFactory);
if(idx != -1)
return dynamic_cast<const WorldFactory*>(getChild(idx));
return NULL;
}
WorldResourceLoader *World::getWorldResourceLoader()
{
s32 idx = getChildIndex(m_WorldResourceLoader);
if(idx != -1)
return dynamic_cast<WorldResourceLoader*>(getChild(idx));
return NULL;
}
const WorldResourceLoader *World::getWorldResourceLoader() const
{
s32 idx = getChildIndex(m_WorldResourceLoader);
if(idx != -1)
return dynamic_cast<const WorldResourceLoader*>(getChild(idx));
return NULL;
}
WorldClock *World::getWorldClock()
{
s32 idx = getChildIndex(m_WorldClock);
if(idx != -1)
return dynamic_cast<WorldClock*>(getChild(idx));
return NULL;
}
const WorldClock *World::getWorldClock() const
{
s32 idx = getChildIndex(m_WorldClock);
if(idx != -1)
return dynamic_cast<const WorldClock*>(getChild(idx));
return NULL;
}
WorldLuaVirtualMachine *World::getWorldLuaVirtualMachine()
{
s32 idx = getChildIndex(m_WorldLuaVirtualMachine);
if(idx != -1)
//#if defined(DEBUG) || defined(_DEBUG)
// {
// return dynamic_cast<WorldLuaVirtualMachine*>(getChild(idx));
// }
//#else
{
// DEBUG_ASSERT(dynamic_cast<WorldLuaVirtualMachine*>(getChild(idx)));
return dynamic_cast<WorldLuaVirtualMachine*>(getChild(idx));
}
//#endif
return NULL;
}
const WorldLuaVirtualMachine *World::getWorldLuaVirtualMachine() const
{
s32 idx = getChildIndex(m_WorldLuaVirtualMachine);
if(idx != -1)
//#if defined(DEBUG) || defined(_DEBUG)
// {
// return dynamic_cast<const WorldLuaVirtualMachine*>(getChild(idx));
// }
//#else
{
// DEBUG_ASSERT(dynamic_cast<const WorldLuaVirtualMachine*>(getChild(idx)));
return dynamic_cast<const WorldLuaVirtualMachine*>(getChild(idx));
}
//#endif
return NULL;
}
// WorldPythonVirtualMachine *World::getWorldPythonVirtualMachine()
// {
// s32 idx = getChildIndex(m_WorldPythonVirtualMachine);
// if(idx != -1)
// return dynamic_cast<WorldPythonVirtualMachine*>(getChild(idx));
// return NULL;
// }
//
// const WorldPythonVirtualMachine *World::getWorldPythonVirtualMachine() const
// {
// s32 idx = getChildIndex(m_WorldPythonVirtualMachine);
// if(idx != -1)
// return dynamic_cast<const WorldPythonVirtualMachine*>(getChild(idx));
// return NULL;
// }
WorldSocket *World::getWorldSocket()
{
s32 idx = getChildIndex(m_WorldSocket);
if(idx != -1)
return dynamic_cast<WorldSocket*>(getChild(idx));
return NULL;
}
const WorldSocket *World::getWorldSocket() const
{
s32 idx = getChildIndex(m_WorldSocket);
if(idx != -1)
return dynamic_cast<const WorldSocket*>(getChild(idx));
return NULL;
}
/*WorldFacebook *World::getWorldFacebook()
{
s32 idx = getChildIndex(m_WorldFacebook);
if(idx != -1)
return dynamic_cast<WorldFacebook*>(getChild(idx));
return NULL;
}*/
/*const WorldFacebook *World::getWorldFacebook() const
{
s32 idx = getChildIndex(m_WorldFacebook);
if(idx != -1)
return dynamic_cast<const WorldFacebook*>(getChild(idx));
return NULL;
}*/
WorldHUD *World::getWorldHUD()
{
s32 idx = getChildIndex(m_WorldHUD);
if(idx != -1)
return dynamic_cast<WorldHUD*>(getChild(idx));
return NULL;
}
const WorldHUD *World::getWorldHUD() const
{
s32 idx = getChildIndex(m_WorldHUD);
if(idx != -1)
return dynamic_cast<const WorldHUD*>(getChild(idx));
return NULL;
}
WorldInput *World::getWorldInput()
{
s32 idx = getChildIndex(m_WorldInput);
if(idx != -1)
return dynamic_cast<WorldInput*>(getChild(idx));
return NULL;
}
const WorldInput *World::getWorldInput() const
{
s32 idx = getChildIndex(m_WorldInput);
if(idx != -1)
return dynamic_cast<const WorldInput*>(getChild(idx));
return NULL;
}
WorldSound *World::getWorldSound()
{
s32 idx = getChildIndex(m_WorldSound);
if(idx != -1)
return dynamic_cast<WorldSound*>(getChild(idx));
return NULL;
}
const WorldSound *World::getWorldSound() const
{
s32 idx = getChildIndex(m_WorldSound);
if(idx != -1)
return dynamic_cast<const WorldSound*>(getChild(idx));
return NULL;
}
WorldStateMachine *World::getStateMachine()
{
s32 idx = getChildIndex(m_stateMachine);
if(idx != -1)
return dynamic_cast<WorldStateMachine*>(getChild(idx));
return NULL;
}
const WorldStateMachine *World::getStateMachine()const
{
s32 idx = getChildIndex(m_stateMachine);
if(idx != -1)
return dynamic_cast<const WorldStateMachine*>(getChild(idx));
return NULL;
}
WorldDebugDrawer *World::getDebugDrawer()
{
return m_WorldDebugDrawer;
}
const WorldDebugDrawer *World::getDebugDrawer()const
{
return m_WorldDebugDrawer;
}
//WorldSQLite *World::getWorldSQLite()
//{
// return m_WorldSQLite;
//}
// const WorldSQLite *World::getWorldSQLite()const
// {
// return m_WorldSQLite;
// }
void World::touchDown(DeviceTouch **m_CurrentTouches)
{
// DEBUG_LOG_WRITE_D(TAG, "World::touchDown\n");
WorldState *currentState = dynamic_cast<WorldState*>(m_stateMachine->getState());
if(currentState)
{
currentState->touchDown(m_CurrentTouches);
}
else
{
DEBUG_LOG_WRITE_D(TAG, "There is no WorldState\n");
}
if(getScene())
getScene()->touchDown(m_CurrentTouches);
char buffer[256];
sprintf(buffer, "%s", "__NJLITouchDown");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer, m_CurrentTouches);
}
void World::touchUp(DeviceTouch **m_CurrentTouches)
{
WorldState *currentState = dynamic_cast<WorldState*>(m_stateMachine->getState());
if(currentState)
{
currentState->touchUp(m_CurrentTouches);
}
else
{
DEBUG_LOG_WRITE_D(TAG, "There is no WorldState\n");
}
if(getScene())
getScene()->touchUp(m_CurrentTouches);
char buffer[256];
sprintf(buffer, "%s", "__NJLITouchUp");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer, m_CurrentTouches);
}
void World::touchMove(DeviceTouch **m_CurrentTouches)
{
WorldState *currentState = dynamic_cast<WorldState*>(m_stateMachine->getState());
if(currentState)
{
currentState->touchMove(m_CurrentTouches);
}
else
{
DEBUG_LOG_WRITE_D(TAG, "There is no WorldState\n");
}
if(getScene())
getScene()->touchMove(m_CurrentTouches);
char buffer[256];
sprintf(buffer, "%s", "__NJLITouchMove");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer, m_CurrentTouches);
}
void World::touchCancelled(DeviceTouch **m_CurrentTouches)
{
WorldState *currentState = dynamic_cast<WorldState*>(m_stateMachine->getState());
if(currentState)
{
currentState->touchCancelled(m_CurrentTouches);
}
else
{
DEBUG_LOG_WRITE_D(TAG, "There is no WorldState\n");
}
if(getScene())
getScene()->touchCancelled(m_CurrentTouches);
char buffer[256];
sprintf(buffer, "%s", "__NJLITouchCancelled");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer, m_CurrentTouches);
}
void World::keyboardShow()
{
char buffer[256];
sprintf(buffer, "%s", "__NJLIWorldKeyboardShow");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer);
if(getScene())
getScene()->keyboardShow();
}
void World::keyboardCancel()
{
char buffer[256];
sprintf(buffer, "%s", "__NJLIWorldKeyboardCancel");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer);
if(getScene())
getScene()->keyboardCancel();
}
void World::keyboardReturn(const char* text)
{
char buffer[256];
sprintf(buffer, "%s", "__NJLIWorldKeyboardReturn");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer, text);
if(getScene())
getScene()->keyboardReturn(text);
}
// void World::setTouchCamera(Camera *camera)
// {
// m_TouchCamera = camera;
// }
// Camera *World::getTouchCamera()
// {
// return m_TouchCamera;
// }
// const Camera *World::getTouchCamera()const
// {
// return m_TouchCamera;
// }
void World::getViewPort(s32 *viewPort)const
{
viewPort[0] = 0;
viewPort[1] = 0;
// if (njli::World::getInstance()->getWorldInput()->isPortraitOrientation())
{
viewPort[2] = static_cast<s32>(njli::World::getInstance()->getViewportDimensions().x());
viewPort[3] = static_cast<s32>(njli::World::getInstance()->getViewportDimensions().y());
}
// else if (njli::World::getInstance()->getWorldInput()->isLandscapeOrientation())
// {
// viewPort[2] = static_cast<s32>(njli::World::getInstance()->getViewportDimensions().y());
// viewPort[3] = static_cast<s32>(njli::World::getInstance()->getViewportDimensions().x());
// }
}
void World::update(f32 timeStep, const u32 numSubSteps)
{
BT_PROFILE("World::update");
m_WorldClock->update(timeStep);
if(getScene())
getScene()->update(timeStep, numSubSteps);
m_stateMachine->update(timeStep);
char buffer[256];
sprintf(buffer, "%s", "__NJLIUpdate");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer, timeStep);
// for (s32 cameraIndex = 0; cameraIndex < m_cameraArray.size(); ++cameraIndex)
// {
// m_cameraArray[cameraIndex]->updateProjection();
// }
// for (s32 nodeIndex = 0; nodeIndex < m_nodeArray.size(); ++nodeIndex)
// {
// m_nodeArray[nodeIndex]->update(timeStep);
// }
if(m_SocketEnabled)
handleSocketMessage();
m_WorldSound->update();
// u64 before = m_WorldFactory->collectGarbageSize();
m_WorldFactory->collectGarbage();
// u64 after = m_WorldFactory->collectGarbageSize();
// DEBUG_LOG_V(TAG, "There were (%lld) objects before and (%lld) objects after", before, after);
}
void World::render()
{
getWorldHUD()->renderFBOs();
renderGL();
if(getScene())
getScene()->render();
getWorldHUD()->render();
char buffer[256];
sprintf(buffer, "%s", "__NJLIRender");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer);
#if defined(DEBUG) || defined (_DEBUG)
Scene *scene = getScene();
ShaderProgram *shaderProgram = getDebugDrawer()->getShaderProgram();
if(m_enableDebugDraw)
{
if(scene && m_DebugDrawCamera && shaderProgram)
{
PhysicsWorld *physicsWorld = scene->getPhysicsWorld();
if(physicsWorld)
{
getDebugDrawer()->render(m_DebugDrawCamera);
physicsWorld->debugDrawWorld();
}
else
{
DEBUG_LOG_WRITE_W(TAG, "Debug draw is enabled without a physics World.");
}
}
else
{
if(!shaderProgram)
DEBUG_LOG_WRITE_W(TAG, "Debug draw is enabled without a shader.");
if(!m_DebugDrawCamera)
DEBUG_LOG_WRITE_W(TAG, "Debug draw is enabled without a camera.");
if(!scene)
DEBUG_LOG_WRITE_W(TAG, "Debug draw is enabled without a scene.");
}
}
#endif
m_WorldFactory->collectGarbage_GPU();
}
void World::resize(s32 width, s32 height, s32 orientation)
{
setGLViewSize(0, 0, width, height);
m_ViewPortDimensions->setX(width);
m_ViewPortDimensions->setY(height);
getWorldInput()->setOrientation(orientation);
if(getScene())
getScene()->updateViewSize();
char buffer[256];
sprintf(buffer, "%s", "__NJLIResize");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer, width, height, orientation);
// DEBUG_LOG_V(TAG, "Screen Dimensions: `%dx%d`", width, height);
}
const btVector2 &World::getViewportDimensions()const
{
return *m_ViewPortDimensions;
}
f32 World::getAspectRatio()const
{
return fabsf(m_ViewPortDimensions->x() / m_ViewPortDimensions->y());
}
const char *World::getClassName()const
{
return "World";
}
s32 World::getType()const
{
return JLI_OBJECT_TYPE_World;
}
World::operator std::string() const
{
return njli::JsonJLI::parse(string_format("%s", FORMATSTRING));
}
// Scene *World::getScene()const
// {
// return m_Scene;
// }
void World::setScene(Scene *scene)
{
DEBUG_ASSERT(scene != NULL);
Scene *currentScene = getScene();
if(scene != currentScene)
{
if(currentScene)
{
removeChild(currentScene);
SceneStateMachine *sm = currentScene->getStateMachine();
sm->clear();
}
m_Scene = scene;
m_Scene->updateViewSize();
addChild(m_Scene);
}
}
void World::removeScene()
{
if(getScene())
removeChild(getScene());
m_Scene = NULL;
}
Scene *World::getScene()
{
s32 idx = getChildIndex(m_Scene);
if(idx != -1)
//#if defined(DEBUG) || defined(_DEBUG)
// {
// return dynamic_cast<Scene*>(getChild(idx));
// }
//#else
{
// DEBUG_ASSERT(dynamic_cast<Scene*>(getChild(idx)));
return dynamic_cast<Scene*>(getChild(idx));
}
//#endif
return NULL;
}
const Scene *World::getScene() const
{
s32 idx = getChildIndex(m_Scene);
if(idx != -1)
//#if defined(DEBUG) || defined(_DEBUG)
// {
// return dynamic_cast<const Scene*>(getChild(idx));
// }
//#else
{
// DEBUG_ASSERT(dynamic_cast<const Scene*>(getChild(idx)));
return dynamic_cast<const Scene*>(getChild(idx));
}
//#endif
return NULL;
}
void World::enableDebugDraw(Camera *camera, ShaderProgram *shader, Material *material)
{
if (camera && shader && material)
{
m_enableDebugDraw = true;
m_DebugDrawCamera = camera;
getDebugDrawer()->setShaderProgram(shader);
getDebugDrawer()->setMaterial(material);
}
else
{
if (camera == NULL)
DEBUG_LOG_WRITE_D(TAG, "Unable to enableDebugDraw, camera is NULL\n");
if (shader == NULL)
DEBUG_LOG_WRITE_D(TAG, "Unable to enableDebugDraw, shader is NULL\n");
if (material == NULL)
DEBUG_LOG_WRITE_D(TAG, "Unable to enableDebugDraw, material is NULL\n");
}
}
void World::enableDebugDraw(Camera *camera, ShaderProgram *shader)
{
if(!m_DebugDrawMaterial)
{
Image *img = Image::create();
img->generate(8, 8, 4);
m_DebugDrawMaterial = Material::create();
m_DebugDrawMaterial->getDiffuse()->loadGPU(*img);
Image::destroy(img);
}
if (NULL == shader)
{
enableDebugDraw(camera, getDebugDrawer()->getShaderProgram(), m_DebugDrawMaterial);
}
else
{
enableDebugDraw(camera, shader, m_DebugDrawMaterial);
}
}
void World::disableDebugDraw()
{
m_enableDebugDraw = false;
m_DebugDrawCamera = NULL;
getDebugDrawer()->removeShaderProgram();
getDebugDrawer()->removeMaterial();
}
// void World::enableDebugDraw(bool enable)
// {
// m_enableDebugDraw = enable;
// }
// void World::setDebugDrawCamera(Camera *camera)
// {
// njliAssert(camera);
// m_DebugDrawCamera = camera;
// }
//
// void World::setDebugShader(ShaderProgram *shaderProgram)
// {
// njliAssert(shaderProgram);
//
// getDebugDrawer()->addShaderProgram(shaderProgram);
// }
//
// void World::setDebugMaterial(Material *material)
// {
// njliAssert(material);
//
// getDebugDrawer()->addMaterial(material);
// }
void World::startSocket(u8 n0, u8 n1, u8 n2, u8 n3, u16 port)
{
stopSocket();
char buffer[1024];
sprintf(buffer, "%d.%d.%d.%d", n0, n1, n2, n3);
if((n0 >= 0 && n0 <= 255) &&
(n1 >= 0 && n1 <= 255) &&
(n2 >= 0 && n2 <= 255) &&
(n3 >= 0 && n3 <= 255))
{
m_SocketAddress = buffer;
m_SocketPort = port;
m_SocketEnabled = true;
}
else
{
DEBUG_LOG_PRINT_E(TAG, "Invalid ip %s", buffer);
}
}
void World::startSocket(u16 port)
{
stopSocket();
m_SocketAddress = std::string("localhost");
m_SocketPort = port;
m_SocketEnabled = true;
}
bool World::isSocketEnabled()const
{
return m_SocketEnabled;
}
void World::stopSocket()
{
m_SocketEnabled = false;
if (getWorldSocket()->isConnected())
getWorldSocket()->disconnectJLI();
}
const char *World::getSocketAddress()const
{
return m_SocketAddress.c_str();
}
u16 World::getSocketPort()const
{
return m_SocketPort;
}
void World::setBackgroundAlpha(const f32 alpha)
{
btVector4 _color(m_BackgroundColor->x(), m_BackgroundColor->y(), m_BackgroundColor->z(), clampColor(alpha));
setBackgroundColor(_color);
}
void World::setBackgroundColor(const btVector3 &color)
{
btVector4 _color(color.x(), color.y(), color.z(), m_BackgroundColor->w());
setBackgroundColor(_color);
}
void World::setBackgroundColor(const btVector4 &color)
{
*m_BackgroundColor = color;
setGLBackgroundColor(clampColor(m_BackgroundColor->x()),
clampColor(m_BackgroundColor->y()),
clampColor(m_BackgroundColor->z()),
clampColor(m_BackgroundColor->w()));
}
const btVector4 &World::getBackgroundColor()const
{
return *m_BackgroundColor;
}
const char*World::getDeviceName()const
{
return m_DeviceName.c_str();
}
void World::setDeviceName(const char *name)
{
m_DeviceName = name;
}
void World::enablePauseAnimation(bool enable)
{
m_AnimationPaused = enable;
}
bool World::isAnimationPaused()const
{
return m_AnimationPaused;
}
void World::enablePauseGame(bool enable)
{
if (enable && !isPausedGame())
{
s8 buffer[BUFFER_SIZE];
sprintf(buffer, "%s", "__NJLIWorldGamePause");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer);
if(getScene())
getScene()->pauseGame();
}
if (!enable && isPausedGame())
{
s8 buffer[BUFFER_SIZE];
sprintf(buffer, "%s", "__NJLIWorldGameUnPause");
njli::World::getInstance()->getWorldLuaVirtualMachine()->execute(buffer);
if(getScene())
getScene()->unPauseGame();
}
m_GamePaused = enable;
}
bool World::isPausedGame()const
{
return m_GamePaused;
}
bool World::isDebug()const
{
#if defined(DEBUG) || defined (_DEBUG)
return true;
#endif
return false;
}
// void World::addNode(Node *node)
// {
// if(!hasNode(node))
// m_nodeArray.push_back(node);
// }
//
// void World::removeNode(Node *node)
// {
// if(hasNode(node))
// m_nodeArray.push_back(node);
// }
//
// bool World::hasNode(Node *node)
// {
// return m_nodeArray.size() != m_nodeArray.findLinearSearch(node);
// }
//
// void World::removeAllNodes()
// {
// m_nodeArray.clear();
// }
// void World::parseSocketMessage(const char *msg)
// {
// if(NULL!=msg)// && strcmp(msg, "") != 0)
// {
// std::string socketMessage(msg);
// size_t found=socketMessage.find("<root>");
// if (found != -1)
// {
// found=socketMessage.find("</root>");
// if(found != -1)
// {
// TiXmlDocument document;
// document.Parse(socketMessage.c_str());
//
// TiXmlNode* ele = NULL;
// while ( (ele = document.FirstChildElement( "root" )->IterateChildren( ele ) ) != 0 )
// {
// TiXmlElement *e = ele->ToElement();
//
// std::string contentType(e->Value());
// std::transform(contentType.begin(), contentType.end(), contentType.begin(), ::tolower);
//
// if(contentType == std::string("lua"))
// {
// DEBUG_LOG_WRITE_W(TAG, e->GetText());
// World::getInstance()->getWorldLuaVirtualMachine()->loadString(e->GetText());
// }
// else if(contentType == std::string("vertex"))
// {
// std::string name(e->Attribute("name"));
//
// // Log("%s\n%s\b%s", e->Value(), name.c_str(), e->GetText());
// }
// else if(contentType == std::string("fragment"))
// {
// std::string name(e->Attribute("name"));
//
// // Log("%s\n%s\b%s", e->Value(), name.c_str(), e->GetText());
//
// }
// }
// }
// else
// {
// DEBUG_LOG_W(TAG, "Maybe need to resize the Socket buffer?\n%s", msg);
//
// }
// }
// }
// }
void World::processMessage(const std::string &socketMessage, const std::string delimeter)
{
TiXmlDocument document;
document.Parse(socketMessage.c_str());
TiXmlNode* ele = NULL;
while ( (ele = document.FirstChildElement( delimeter.c_str() )->IterateChildren( ele ) ) != 0 )
{
TiXmlElement *e = ele->ToElement();
std::string contentType(e->Value());
std::transform(contentType.begin(), contentType.end(), contentType.begin(), ::tolower);
if(contentType == std::string("lua"))
{
std::string type(e->Attribute("type"));
std::string name(e->Attribute("name"));
// std::string source;
// const TiXmlNode* child = e->FirstChild();
// if ( child ) {
// source = child->Value();
//// const TiXmlText* childText = child->ToText();
//// if ( childText ) {
//// TiXmlString s = childText->ValueTStr();
//// source = s.data();
////// return childText->Value();
//// }
// }
std::string source(e->GetText());
std::string filePath = DOCUMENT_PATH(name.c_str());
int numwrote = 0;
if (type == std::string("build") || type == std::string("run"))
{
if (type == std::string("build"))
{
bool wrote = false;
if( access( filePath.c_str(), F_OK ) != -1 )
{
FILE *f = fopen(filePath.c_str(), "wb");
if (f != NULL)
{
numwrote = fwrite(source.c_str(), sizeof(char), source.length(), f);
fclose(f);
if (0 == ferror(f))
wrote = true;
}
}
if (!wrote)
DEBUG_LOG_V(TAG, "Couldn't write file %s - (%d bytes of %lu)", filePath.c_str(), numwrote, source.length());
else
DEBUG_LOG_V(TAG, "Wrote file %s", filePath.c_str());
}
if (type == std::string("run"))
{
World::getInstance()->getWorldLuaVirtualMachine()->reset();
World::getInstance()->getWorldLuaVirtualMachine()->loadString(source.c_str());
World::getInstance()->getWorldLuaVirtualMachine()->loadFile(DOCUMENT_PATH("scripts/main.lua"));
World::getInstance()->getWorldLuaVirtualMachine()->compile();
}
else
{
World::getInstance()->getWorldLuaVirtualMachine()->loadString(source.c_str());
World::getInstance()->getWorldLuaVirtualMachine()->compile();
}
}
}
else if(contentType == std::string("vertex"))
{
std::string name(e->Attribute("name"));
// Log("%s\n%s\b%s", e->Value(), name.c_str(), e->GetText());
}
else if(contentType == std::string("fragment"))
{
std::string name(e->Attribute("name"));
// Log("%s\n%s\b%s", e->Value(), name.c_str(), e->GetText());
}
}
}
void World::handleSocketMessage()
{
if(getWorldSocket()->hasMessage())
{
processMessage(getWorldSocket()->popMessage());
}
if (getWorldSocket()->isConnected())
{
getWorldSocket()->parseMessage("root");
}
else
{
getWorldSocket()->connectJLI(m_SocketAddress.c_str(), m_SocketPort);
}
}
/*
new (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
exit (myTestNode->myTestNode)
delete (myTestNode)
exit (BasicTestSceneState)
delete (BasicTestSceneState)
exit (TestsWorldState)
enter (TestsWorldState)
new (BasicTestSceneState)
enter (BasicTestSceneState)
new (myTestNode)
enter (myTestNode->myTestNode)
*/
}
| 30.185963 | 136 | 0.579332 | [
"render",
"transform"
] |
cf2969e22f0443d1b1ca86bad46ba4b79738e2cc | 14,113 | cpp | C++ | sdl2-sonic-drivers/src/audio/scummvm/RateConverter.cpp | Raffaello/sdl2-sonic-drivers | 20584f100ddd7c61f584deaee0b46c5228d8509d | [
"Apache-2.0"
] | 3 | 2021-10-31T14:24:00.000Z | 2022-03-16T08:15:31.000Z | sdl2-sonic-drivers/src/audio/scummvm/RateConverter.cpp | Raffaello/sdl2-sonic-drivers | 20584f100ddd7c61f584deaee0b46c5228d8509d | [
"Apache-2.0"
] | 48 | 2020-06-05T11:11:29.000Z | 2022-02-27T23:58:44.000Z | sdl2-sonic-drivers/src/audio/scummvm/RateConverter.cpp | Raffaello/sdl2-sonic-drivers | 20584f100ddd7c61f584deaee0b46c5228d8509d | [
"Apache-2.0"
] | null | null | null | #include <audio/scummvm/RateConverter.hpp>
#include <audio/scummvm/AudioStream.hpp>
#include <audio/scummvm/Mixer.hpp>
#include <cassert>
#include <cstdlib>
#include <spdlog/spdlog.h>
namespace audio
{
namespace scummvm
{
// TODO split into multiple class and in its own namesapce
// TODO: move to utils and as a constexpr
#define ARRAYSIZE(x) ((int)(sizeof(x) / sizeof(x[0])))
// frac.h -----------------------------------------------------------------
/**
* @defgroup common_frac Fixed-point fractions
* @ingroup common
*
* @brief API for fixed-point fractions.
*
* @{
*/
/**
* The precision of the fractional (fixed-point) type that is defined below.
* Normally, you should never need to modify this value.
*/
enum {
FRAC_BITS = 16,
FRAC_LO_MASK = ((1L << FRAC_BITS) - 1),
FRAC_HI_MASK = ((1L << FRAC_BITS) - 1) << FRAC_BITS,
FRAC_ONE = (1L << FRAC_BITS), // 1.0
FRAC_HALF = (1L << (FRAC_BITS - 1)) // 0.5
};
/**
* Fixed-point fractions, used by the sound rate converter and other code.
*/
typedef int32_t frac_t;
inline frac_t doubleToFrac(double value) { return (frac_t)(value * FRAC_ONE); }
inline double fracToDouble(frac_t value) { return ((double)value) / FRAC_ONE; }
inline frac_t intToFrac(int16_t value) { return value * (1 << FRAC_BITS); }
inline int16_t fracToInt(frac_t value) { return value / (1 << FRAC_BITS); }
/** @} */
// ------------------------------------------------------------------------
/*
* The code in this file is based on code with Copyright 1998 Fabrice Bellard
* Fabrice original code is part of SoX (http://sox.sourceforge.net).
* Max Horn adapted that code to the needs of ScummVM and rewrote it partial,
* in the process removing any use of floating point arithmetic. Various other
* improvements over the original code were made.
*/
/**
* The size of the intermediate input cache. Bigger values may increase
* performance, but only until some point (depends largely on cache size,
* target processor and various other factors), at which it will decrease
* again.
*/
#define INTERMEDIATE_BUFFER_SIZE 512
/**
* The default fractional type in frac.h (with 16 fractional bits) limits
* the rate conversion code to 65536Hz audio: we need to able to handle
* 96kHz audio, so we use fewer fractional bits in this code.
*/
enum {
FRAC_BITS_LOW = 15,
FRAC_ONE_LOW = (1L << FRAC_BITS_LOW),
FRAC_HALF_LOW = (1L << (FRAC_BITS_LOW - 1))
};
/**
* Audio rate converter based on simple resampling. Used when no
* interpolation is required.
*
* Limited to sampling frequency <= 65535 Hz.
*/
template<bool stereo, bool reverseStereo>
class SimpleRateConverter : public RateConverter {
protected:
int16_t inBuf[INTERMEDIATE_BUFFER_SIZE];
const int16_t* inPtr;
int inLen;
/** position of how far output is ahead of input */
/** Holds what would have been opos-ipos */
long opos;
/** fractional position increment in the output stream */
long opos_inc;
public:
SimpleRateConverter(uint32_t inrate, uint32_t outrate);
int flow(AudioStream& input, int16_t* obuf, uint32_t osamp, uint16_t vol_l, uint16_t vol_r);
int drain(int16_t* obuf, uint32_t osamp, uint16_t vol) {
return ST_SUCCESS;
}
};
/*
* Prepare processing.
*/
template<bool stereo, bool reverseStereo>
SimpleRateConverter<stereo, reverseStereo>::SimpleRateConverter(uint32_t inrate, uint32_t outrate) {
if ((inrate % outrate) != 0) {
spdlog::error("Input rate must be a multiple of output rate to use rate effect");
}
if (inrate >= 65536 || outrate >= 65536) {
spdlog::error("rate effect can only handle rates < 65536");
}
opos = 1;
/* increment */
opos_inc = inrate / outrate;
inLen = 0;
}
/*
* Processed signed long samples from ibuf to obuf.
* Return number of sample pairs processed.
*/
template<bool stereo, bool reverseStereo>
int SimpleRateConverter<stereo, reverseStereo>::flow(AudioStream& input, int16_t* obuf, uint32_t osamp, uint16_t vol_l, uint16_t vol_r) {
int16_t* ostart, * oend;
ostart = obuf;
oend = obuf + osamp * 2;
while (obuf < oend) {
// read enough input samples so that opos >= 0
do {
// Check if we have to refill the buffer
if (inLen == 0) {
inPtr = inBuf;
inLen = input.readBuffer(inBuf, ARRAYSIZE(inBuf));
if (inLen <= 0)
return (obuf - ostart) / 2;
}
inLen -= (stereo ? 2 : 1);
opos--;
if (opos >= 0) {
inPtr += (stereo ? 2 : 1);
}
} while (opos >= 0);
int16_t out0, out1;
out0 = *inPtr++;
out1 = (stereo ? *inPtr++ : out0);
// Increment output position
opos += opos_inc;
// output left channel
clampedAdd(obuf[reverseStereo], (out0 * (int)vol_l) / Mixer::MaxVolume::MIXER);
// output right channel
clampedAdd(obuf[reverseStereo ^ 1], (out1 * (int)vol_r) / Mixer::MaxVolume::MIXER);
obuf += 2;
}
return (obuf - ostart) / 2;
}
/**
* Audio rate converter based on simple linear Interpolation.
*
* The use of fractional increment allows us to use no buffer. It
* avoid the problems at the end of the buffer we had with the old
* method which stored a possibly big buffer of size
* lcm(in_rate,out_rate).
*
* Limited to sampling frequency <= 65535 Hz.
*/
template<bool stereo, bool reverseStereo>
class LinearRateConverter : public RateConverter {
protected:
int16_t inBuf[INTERMEDIATE_BUFFER_SIZE];
const int16_t* inPtr;
int inLen;
/** fractional position of the output stream in input stream unit */
frac_t opos;
/** fractional position increment in the output stream */
frac_t opos_inc;
/** last sample(s) in the input stream (left/right channel) */
int16_t ilast0, ilast1;
/** current sample(s) in the input stream (left/right channel) */
int16_t icur0, icur1;
public:
LinearRateConverter(uint32_t inrate, uint32_t outrate);
int flow(AudioStream& input, int16_t* obuf, uint32_t osamp, uint16_t vol_l, uint16_t vol_r);
int drain(int16_t* obuf, uint32_t osamp, uint16_t vol) {
return ST_SUCCESS;
}
};
/*
* Prepare processing.
*/
template<bool stereo, bool reverseStereo>
LinearRateConverter<stereo, reverseStereo>::LinearRateConverter(uint32_t inrate, uint32_t outrate) {
if (inrate >= 131072 || outrate >= 131072) {
spdlog::error("rate effect can only handle rates < 131072");
}
opos = FRAC_ONE_LOW;
// Compute the linear interpolation increment.
// This will overflow if inrate >= 2^17, and underflow if outrate >= 2^17.
// Also, if the quotient of the two rate becomes too small / too big, that
// would cause problems, but since we rarely scale from 1 to 65536 Hz or vice
// versa, I think we can live with that limitation ;-).
opos_inc = (inrate << FRAC_BITS_LOW) / outrate;
ilast0 = ilast1 = 0;
icur0 = icur1 = 0;
inLen = 0;
}
/*
* Processed signed long samples from ibuf to obuf.
* Return number of sample pairs processed.
*/
template<bool stereo, bool reverseStereo>
int LinearRateConverter<stereo, reverseStereo>::flow(AudioStream& input, int16_t* obuf, uint32_t osamp, uint16_t vol_l, uint16_t vol_r) {
int16_t* ostart, * oend;
ostart = obuf;
oend = obuf + osamp * 2;
while (obuf < oend) {
// read enough input samples so that opos < 0
while ((frac_t)FRAC_ONE_LOW <= opos) {
// Check if we have to refill the buffer
if (inLen == 0) {
inPtr = inBuf;
inLen = input.readBuffer(inBuf, ARRAYSIZE(inBuf));
if (inLen <= 0)
return (obuf - ostart) / 2;
}
inLen -= (stereo ? 2 : 1);
ilast0 = icur0;
icur0 = *inPtr++;
if (stereo) {
ilast1 = icur1;
icur1 = *inPtr++;
}
opos -= FRAC_ONE_LOW;
}
// Loop as long as the outpos trails behind, and as long as there is
// still space in the output buffer.
while (opos < (frac_t)FRAC_ONE_LOW && obuf < oend) {
// interpolate
int16_t out0, out1;
out0 = (int16_t)(ilast0 + (((icur0 - ilast0) * opos + FRAC_HALF_LOW) >> FRAC_BITS_LOW));
out1 = (stereo ?
(int16_t)(ilast1 + (((icur1 - ilast1) * opos + FRAC_HALF_LOW) >> FRAC_BITS_LOW)) :
out0);
// output left channel
clampedAdd(obuf[reverseStereo], (out0 * (int)vol_l) / Mixer::MaxVolume::MIXER);
// output right channel
clampedAdd(obuf[reverseStereo ^ 1], (out1 * (int)vol_r) / Mixer::MaxVolume::MIXER);
obuf += 2;
// Increment output position
opos += opos_inc;
}
}
return (obuf - ostart) / 2;
}
/**
* Simple audio rate converter for the case that the inrate equals the outrate.
*/
template<bool stereo, bool reverseStereo>
class CopyRateConverter : public RateConverter {
int16_t* _buffer;
uint32_t _bufferSize;
public:
CopyRateConverter() : _buffer(0), _bufferSize(0) {}
~CopyRateConverter() {
free(_buffer);
}
virtual int flow(AudioStream& input, int16_t* obuf, uint32_t osamp, uint16_t vol_l, uint16_t vol_r) {
assert(input.isStereo() == stereo);
int16_t* ptr;
uint32_t len;
int16_t* ostart = obuf;
if (stereo)
osamp *= 2;
// Reallocate temp buffer, if necessary
if (osamp > _bufferSize) {
free(_buffer);
_buffer = (int16_t*)malloc(osamp * 2);
_bufferSize = osamp;
}
if (!_buffer)
spdlog::error("[CopyRateConverter::flow] Cannot allocate memory for temp buffer");
// Read up to 'osamp' samples into our temporary buffer
len = input.readBuffer(_buffer, osamp);
// Mix the data into the output buffer
ptr = _buffer;
for (; len > 0; len -= (stereo ? 2 : 1)) {
int16_t out0, out1;
out0 = *ptr++;
out1 = (stereo ? *ptr++ : out0);
// output left channel
clampedAdd(obuf[reverseStereo], (out0 * (int)vol_l) / Mixer::MaxVolume::MIXER);
// output right channel
clampedAdd(obuf[reverseStereo ^ 1], (out1 * (int)vol_r) / Mixer::MaxVolume::MIXER);
obuf += 2;
}
return (obuf - ostart) / 2;
}
virtual int drain(int16_t* obuf, uint32_t osamp, uint16_t vol) {
return ST_SUCCESS;
}
};
template<bool stereo, bool reverseStereo>
RateConverter* makeRateConverter(uint32_t inrate, uint32_t outrate) {
if (inrate != outrate) {
if ((inrate % outrate) == 0 && (inrate < 65536)) {
return new SimpleRateConverter<stereo, reverseStereo>(inrate, outrate);
}
else {
return new LinearRateConverter<stereo, reverseStereo>(inrate, outrate);
}
}
else {
return new CopyRateConverter<stereo, reverseStereo>();
}
}
/**
* Create and return a RateConverter object for the specified input and output rates.
*/
RateConverter* makeRateConverter(uint32_t inrate, uint32_t outrate, bool stereo, bool reverseStereo) {
if (stereo) {
if (reverseStereo)
return makeRateConverter<true, true>(inrate, outrate);
else
return makeRateConverter<true, false>(inrate, outrate);
}
else
return makeRateConverter<false, false>(inrate, outrate);
}
}
}
| 36.187179 | 145 | 0.50953 | [
"object"
] |
cf3ccdad7a9de6b51916a98e9db8fd85c1826a3c | 679 | hpp | C++ | include/ez/imgui/Context.hpp | errata-c/ez-imgui | 171fdf7b4564f10034367425eb0d61e50dc6b786 | [
"MIT"
] | null | null | null | include/ez/imgui/Context.hpp | errata-c/ez-imgui | 171fdf7b4564f10034367425eb0d61e50dc6b786 | [
"MIT"
] | null | null | null | include/ez/imgui/Context.hpp | errata-c/ez-imgui | 171fdf7b4564f10034367425eb0d61e50dc6b786 | [
"MIT"
] | null | null | null | #pragma once
#include <cinttypes>
#include <string>
#include <chrono>
#include <ez/input/InputEvent.hpp>
#include "Backend.hpp"
struct ImGuiContext;
namespace ez::window {
class Window;
}
namespace ez::imgui {
// Associate with a window.
// That way we can use clipboard and update mouse and other things.
class Context {
public:
Context();
~Context();
void makeActive();
bool isActive() const;
bool processEvent(const ez::InputEvent& ev);
void newFrame(window::Window & window);
void render();
private:
ImGuiContext* ctx;
std::chrono::steady_clock::time_point prevTime;
bool mousePress[3];
std::string clipboard;
Backend backend;
};
}; | 16.975 | 68 | 0.701031 | [
"render"
] |
cf45a76ab6616424432ef398f735f9ced2c0e852 | 10,162 | cpp | C++ | src/main.cpp | adct-the-experimenter/dance-fighters | 758ba76eeb50e1c815ae5b3ec5923d64f9214154 | [
"MIT"
] | null | null | null | src/main.cpp | adct-the-experimenter/dance-fighters | 758ba76eeb50e1c815ae5b3ec5923d64f9214154 | [
"MIT"
] | null | null | null | src/main.cpp | adct-the-experimenter/dance-fighters | 758ba76eeb50e1c815ae5b3ec5923d64f9214154 | [
"MIT"
] | null | null | null | #include "core/coordinator.h"
#include "raylib.h"
#include "systems/InputReactorSystem.h"
#include "systems/PhysicsSystem.h"
#include "systems/CameraSystem.h"
#include "systems/RenderSystem.h"
#include "systems/AnimationSystem.h"
#include "core/ControllerInputHandler.h"
#include "core/ControllerInput.h"
#include "core/KeyboardTypingInputHandler.h"
#include "core/KeyboardInput.h"
#include "misc/camera.h"
#include "misc/MediaLoader.h"
#include "misc/globalvariables.h"
#include "misc/StageManager.h"
#include "misc/char_selector.h" //for CharacterSelector class
#include "misc/stage_selector.h" //for StageSelector class
#include <string>
#include <chrono>
#include <memory>
#include <iostream>
#include <array>
//main
//initialize manager for levels
//initialize list of levels from XML
Coordinator gCoordinator;
ControllerInput gControllerInput;
ControllerInputHandler gControllerInputHandler;
KeyboardInput gKeyboardInput;
KeyboardTypingInputHandler gKeyboardTypingInputHandler;
std::vector <Entity> entities(MAX_ENTITIES);
//function to initialize main ECS
void InitMainECS();
std::shared_ptr <RenderSystem> renderSystem;
std::shared_ptr <AnimationSystem> animationSystem;
std::shared_ptr <InputReactorSystem> input_ReactSystem;
std::shared_ptr <PhysicsSystem> physicsSystem;
//function to init raylib system
void InitRaylibSystem();
//function to close raylib system
void CloseRaylibSystem();
//function to load media for game
bool loadMedia();
MediaLoader gMediaLoader;
//function to run the game loop of event handling, logic render, sound
void GameLoop();
//game loop functions
void handle_events(); //receive input
void logic(); //determine what happens in world based on input
void render(); //draw visual representation of what happens in world to screen
void sound(); //play sounds of audio representation of what happens in world
//game state
enum class GameState : std::uint8_t {TITLE_MENU=0, CHAR_SELECTOR, STAGE_SELECTOR, FIGHT_GAME};
GameState m_game_state = GameState::TITLE_MENU;
//camera to follow players.
std::shared_ptr <CameraSystem> cameraSystem;
CustomCamera main_camera;
bool video_game_playing = false;
CharacterSelector gCharSelector;
std::int8_t gNumPlayers = 2;
const std::int16_t screenWidth = 800;
const std::int16_t screenHeight = 600;
StageManager gStageManager;
StageSelector gStageSelector;
int main(int argc, char* args[])
{
InitRaylibSystem();
if(!loadMedia())
{
std::cout << "Not loading game. Failed to load media!\n";
}
else
{
//reset to new number of players for input handling
gControllerInput.Init(gNumPlayers);
gControllerInputHandler.Init(gNumPlayers);
InitMainECS();
//create entities for players
for(size_t i = 0; i < gNumPlayers; i++)
{
entities[i] = gCoordinator.CreateEntity();
}
bool quit = false;
while (!quit)
{
// Detect window close button or ESC key
if(WindowShouldClose())
{
quit = true;
}
// Main game loop
GameLoop();
}
}
gMediaLoader.freeMedia();
gStageManager.FreeCurrentLoadedLevel();
CloseRaylibSystem();
return 0;
}
void GameLoop()
{
//handle events through event manager
handle_events();
//run logic for all entities through systems
logic();
//run render for all entities in manager
render();
}
void handle_events()
{
gControllerInputHandler.Update(&gControllerInput);
gKeyboardTypingInputHandler.Update(&gKeyboardInput);
switch(m_game_state)
{
case GameState::TITLE_MENU:
{
break;
}
case GameState::CHAR_SELECTOR:
{
//run logic for character creator system here
gCharSelector.handle_input(gControllerInput,gKeyboardInput);
break;
}
case GameState::STAGE_SELECTOR:
{
gStageSelector.handle_input(gControllerInput,gKeyboardInput);
break;
}
case GameState::FIGHT_GAME:
{
input_ReactSystem->Update(gControllerInput);
break;
}
}
}
void logic()
{
float dt = GetFrameTime();
//game
switch(m_game_state)
{
case GameState::TITLE_MENU:
{
bool moveNextState = false;
if(gControllerInput.gamepads_vec[0].button == SDL_CONTROLLER_BUTTON_A)
{
moveNextState = true;
}
//if need to move to next state
if(moveNextState)
{
//initialze char selector
gCharSelector.Init(&entities,gNumPlayers);
//initialize camera system
cameraSystem->Init(&main_camera,screenWidth,screenHeight);
//initialize render system
renderSystem->Init(&main_camera);
//move to next state
m_game_state = GameState::CHAR_SELECTOR;
}
break;
}
case GameState::CHAR_SELECTOR:
{
//run logic for character selector
gCharSelector.logic();
if(gCharSelector.MoveToNextStateBool())
{
//initialize stage selector
gStageSelector.Init(gNumPlayers);
m_game_state = GameState::STAGE_SELECTOR;
}
break;
}
case GameState::STAGE_SELECTOR:
{
//run logic for stage selector
gStageSelector.logic();
if(gStageSelector.MoveToNextStateBool())
{
//initialize fight game state
if(gStageManager.LoadLevel( gStageSelector.StageSelected() ) )
{
m_game_state = GameState::FIGHT_GAME;
}
}
break;
}
case GameState::FIGHT_GAME:
{
physicsSystem->Update(dt);
//set up frame for render
animationSystem->Update(dt);
break;
}
}
}
Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position
void render()
{
BeginDrawing();
ClearBackground(RAYWHITE);
switch(m_game_state)
{
case GameState::TITLE_MENU:
{
DrawTexture(title_menu_texture, 0, 0, WHITE);
break;
}
case GameState::CHAR_SELECTOR:
{
DrawText("In character selector. Press A to select character.", 80, 20, 20, BLACK);
gCharSelector.render();
break;
}
case GameState::STAGE_SELECTOR:
{
DrawText("In stage selector. Press A to select stage.", 80, 20, 20, BLACK);
gStageSelector.render();
break;
}
case GameState::FIGHT_GAME:
{
DrawText("In game fight.", 80, 20, 20, BLACK);
BeginMode3D(main_camera.GetReferenceToCamera());
//draw the stage
if(main_stage.mapPixels)
{
DrawModel(main_stage.model, mapPosition, 1.0f, WHITE); // Draw maze map
}
cameraSystem->Update();
//render any entity that has render component
renderSystem->Update();
EndMode3D();
break;
}
}
EndDrawing();
}
void sound()
{
}
bool loadMedia()
{
bool success = true;
if( !gMediaLoader.loadMedia() )
{
success = false;
}
return success;
}
void InitMainECS()
{
//initialize coordinator which initializes entity manager, component manager
gCoordinator.Init();
//Initialize components for entities
gCoordinator.RegisterComponent<Transform3D>(); //id 1
gCoordinator.RegisterComponent<RigidBody3D>();
gCoordinator.RegisterComponent<RenderModelComponent>();
gCoordinator.RegisterComponent<InputReact>();
gCoordinator.RegisterComponent<PhysicsTypeComponent>();
gCoordinator.RegisterComponent<Animation>();
gCoordinator.RegisterComponent<CollisionBox>();
gCoordinator.RegisterComponent<Player>();
//make rendering system that only reacts to entities
//with render info component
renderSystem = gCoordinator.RegisterSystem<RenderSystem>();
Signature sig_render;
sig_render.set(gCoordinator.GetComponentType<RenderModelComponent>());
sig_render.set(gCoordinator.GetComponentType<Transform3D>());
gCoordinator.SetSystemSignature<RenderSystem>(sig_render);
//make input reactor system that only reacts to components input react and transform
input_ReactSystem = gCoordinator.RegisterSystem<InputReactorSystem>();
Signature sig_input_react;
sig_input_react.set(gCoordinator.GetComponentType<InputReact>());
sig_input_react.set(gCoordinator.GetComponentType<RigidBody3D>());
gCoordinator.SetSystemSignature<InputReactorSystem>(sig_input_react);
//make physics system that only reacts to entitities
//with signature that has these components
gCoordinator.RegisterComponent<Gravity3D>();
physicsSystem = gCoordinator.RegisterSystem<PhysicsSystem>();
Signature phys_sys_signature;
phys_sys_signature.set(gCoordinator.GetComponentType<Gravity3D>());
phys_sys_signature.set(gCoordinator.GetComponentType<RigidBody3D>());
phys_sys_signature.set(gCoordinator.GetComponentType<Transform3D>());
phys_sys_signature.set(gCoordinator.GetComponentType<PhysicsTypeComponent>());
//phys_sys_signature.set(gCoordinator.GetComponentType<CollisionBox>());
gCoordinator.SetSystemSignature<PhysicsSystem>(phys_sys_signature);
//make camera system that only reacts to entities
//with signature that has these components
cameraSystem = gCoordinator.RegisterSystem<CameraSystem>();
Signature camera_sig;
camera_sig.set(gCoordinator.GetComponentType<Transform3D>());
camera_sig.set(gCoordinator.GetComponentType<Player>());
gCoordinator.SetSystemSignature<CameraSystem>(camera_sig);
//make animation system that only reacts to entities
//with signature that has these components
animationSystem = gCoordinator.RegisterSystem<AnimationSystem>();
animationSystem->Init();
Signature animation_sig;
animation_sig.set(gCoordinator.GetComponentType<Transform3D>());
animation_sig.set(gCoordinator.GetComponentType<Animation>());
animation_sig.set(gCoordinator.GetComponentType<RenderModelComponent>());
gCoordinator.SetSystemSignature<AnimationSystem>(animation_sig);
}
void InitRaylibSystem()
{
SetConfigFlags(FLAG_MSAA_4X_HINT); // Set MSAA 4X hint before windows creation
InitWindow(screenWidth, screenHeight, "Dance Fighters");
// initialize SDL2 for gamepad handling
if( SDL_Init( SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0 )
{
printf( "SDL input could not initialize! SDL Error: %s\n", SDL_GetError() );
}
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//initialize game controller input
gControllerInputHandler.Init(1);
}
void CloseRaylibSystem()
{
CloseWindow(); // Close window and OpenGL context
//Quit SDL subsystems
SDL_Quit();
}
| 22.139434 | 94 | 0.731254 | [
"render",
"vector",
"model",
"transform"
] |
cf46d52afd1a036ae2146f1aca543f9e2d2e5c98 | 9,141 | cpp | C++ | src/mutatee/mutatee.cpp | ikitayama/cobi | e9bc4a5675ead1874ad9ffa953de8edb3a763479 | [
"BSD-3-Clause"
] | null | null | null | src/mutatee/mutatee.cpp | ikitayama/cobi | e9bc4a5675ead1874ad9ffa953de8edb3a763479 | [
"BSD-3-Clause"
] | null | null | null | src/mutatee/mutatee.cpp | ikitayama/cobi | e9bc4a5675ead1874ad9ffa953de8edb3a763479 | [
"BSD-3-Clause"
] | 1 | 2018-12-14T02:45:41.000Z | 2018-12-14T02:45:41.000Z | /*****************************************************************************
** Cobi http://www.scalasca.org/ **
*****************************************************************************
** Copyright (c) 2009-2010 **
** Forschungszentrum Juelich, Juelich Supercomputing Centre **
** **
** See the file COPYRIGHT in the base directory for details **
*****************************************************************************/
/**
* @file mutatee.cpp
* @author Jan Mussler
* @brief Mutatee implementation
*/
#include <set>
#include "BPatch_statement.h"
#include "mutatee.h"
#include "callgraph.h"
#include "instrumentablefunction.h"
using namespace std;
using namespace gi::mutatee;
using namespace gi::instrumenter;
using namespace gi::mutatee::graph;
using namespace gi::filter;
BPatch_point* getFirstEnterPointOfFunction(BPatch_function* func) {
assert(func != 0);
vector<BPatch_point*>* points = func->findPoint(BPatch_entry);
if (points->size() > 1) {
Function f(func);
std::cout << "[Warning]: "
<< f.getName() << " has multiplie entry points, \"Init\" code placed at 1st! only\n";
}
else if (points->size() == 0) {
Function f(func);
std::cout << "[Error]: "
<< f.getName() << " has no entry points, \"Init\" code could not be inserted!\n";
exit(EXIT_FAILURE);
}
BPatch_point* p = (*points)[0];
delete points;
return p;
}
Mutatee::Mutatee() : baseFunctions(0), baseSet(0), callGraph(0), initInsertPoint(0), finalizeInsertPoints(0) {
adapterRule = new RFalse();
}
Mutatee::Mutatee(BPatch_binaryEdit* as, BPatch_image* im) : addressSpace(as), image(im), baseFunctions(0), baseSet(0), callGraph(0), initInsertPoint(0), finalizeInsertPoints(0) {
adapterRule = new RFalse();
}
Mutatee::~Mutatee() {
for (set<IInstrumentableFunction*>::iterator i = baseSet->begin(); i != baseSet->end(); i++) {
delete (*i);
}
baseSet->clear();
delete finalizeInsertPoints;
delete callGraph;
delete baseSet;
delete baseFunctions;
delete addressSpace;
delete adapterRule;
}
void Mutatee::setAdapterRule(IRule* rule) {
delete adapterRule;
if (rule == 0) {
adapterRule = new RFalse();
return;
}
adapterRule = rule;
}
vector<Module>* Mutatee::getModules() {
vector<Module>* ms = new vector<Module > ();
vector<BPatch_module*>* dynModules = image->getModules();
for (vector<BPatch_module*>::iterator dynMod = dynModules->begin();
dynMod != dynModules->end();
dynMod++) {
ms->push_back(Module(*dynMod));
}
return ms;
}
vector<Function*>* Mutatee::getAllFunctions() {
if (baseFunctions != 0) return baseFunctions;
baseFunctions = new vector<Function*> ();
vector<BPatch_function*>* dynFunctions = image->getProcedures();
for (vector<BPatch_function*>::iterator dynFunc = dynFunctions->begin();
dynFunc != dynFunctions->end();
dynFunc++) {
baseFunctions->push_back(new Function((*dynFunc)));
}
delete dynFunctions;
return baseFunctions;
}
set<IInstrumentableFunction*>* Mutatee::getAllInstrumentableFunctions() {
if (baseSet != 0) return baseSet;
assert(adapterRule != 0);
std::cout << "=== requesting all instrumentable functions ===\n";
baseSet = new set<IInstrumentableFunction*>();
vector<BPatch_function*>* dynFunctions = image->getProcedures(false);
std::cout << "number of functions in mutatee: " << dynFunctions->size() << "\n";
for (vector<BPatch_function*>::iterator dynFunc = dynFunctions->begin();
dynFunc != dynFunctions->end();
dynFunc++) {
Function* function = new Function((*dynFunc));
/**
* adapter rule excludes all functions according to the adapte filter defined adapter spec file
*/
if (!adapterRule->match(function)) {
InstrumentableFunction* insF = new InstrumentableFunction(function);
baseSet->insert(insF);
}
else {
delete function;
}
}
std::cout << " after adapter filter: " << baseSet->size() << "\n";
delete dynFunctions;
std::cout << "===============================================\n\n";
return baseSet;
}
BPatch_function* Mutatee::getFunction(std::string name) {
vector<BPatch_function*> fs;
image->findFunction(name.c_str(), fs);
if (fs.size() > 1) {
std::cout << "warn: more than one function with name " << name << " found ( using 1st one )\n";
}
else if (fs.size() == 0) {
return 0;
}
return fs[0];
}
void Mutatee::insertCode(vector<BPatch_point*> points, BPatch_snippet* snippet) {
addressSpace->insertSnippet(*snippet, points);
}
void Mutatee::insertCode(vector<BPatch_point*> points, BPatch_snippet* snippet, BPatch_callWhen w, BPatch_snippetOrder o) {
addressSpace->insertSnippet(*snippet, points, w, o);
}
bool Mutatee::save(string fileName) {
assert(initFunction != 0);
if (initInsertPoint == 0) {
initInsertPoint = getFirstEnterPointOfFunction(initFunction);
}
assert(initInsertPoint != 0);
vector<BPatch_point*> points;
points.push_back(initInsertPoint);
/*
Insert intialization code in reverser order to produce correct result
need first snippet, as point may be instrumented by "enter" code, which must run after init code
*/
for (mapPrioToSnippets::reverse_iterator i = initSnippets.rbegin();
i != initSnippets.rend(); i++) {
for (vector<BPatch_snippet*>::reverse_iterator j = (*i).second.rbegin();
j != (*i).second.rend(); j++) {
insertCode(points, (*j), BPatch_callBefore, BPatch_firstSnippet);
}
}
return addressSpace->writeFile(fileName.c_str());
}
SourceLine::SourceLine(int l, string f) : line(l), file(f) {
}
SourceLine Mutatee::getFirstSourceLineOfAddress(unsigned long address) {
vector<BPatch_statement> statements;
if (addressSpace->getSourceLines(address, statements)) {
if (!statements.size() > 0) {
return SourceLine(0, "unknown");
}
return SourceLine(statements[0].lineNumber(), statements[0].fileName());
}
else {
return SourceLine(0, "unknown - (getSourceLines returned false)");
}
}
CallGraph* getCallGraphForMutatee(Mutatee* m) {
CallGraph* gr = new CallGraph();
// do not delete allFs!! mutatee takes care of that, and will allways return the same vector!!
vector<Function*>* allFs = m->getAllFunctions();
for (vector<Function*>::iterator i = allFs->begin();
i != allFs->end();
i++) {
gr->addFunction(*i);
}
return gr;
}
graph::CallGraph& Mutatee::getCallGraph() {
if (callGraph == 0) {
callGraph = getCallGraphForMutatee(this);
callGraph->transformTmpCalls();
}
return *callGraph;
}
BPatch_variableExpr* Mutatee::createVariable(int size) {
return addressSpace->malloc(size);
}
BPatch_variableExpr* Mutatee::createVariable(string typeName) {
BPatch_type* type = image->findType(typeName.c_str());
if (type == 0) {
return 0;
}
return addressSpace->malloc(*type);
}
void Mutatee::insertInitCode(BPatch_snippet* snippet, int prio) {
insertInitCode(snippet, BPatch_callBefore, BPatch_firstSnippet, prio);
}
/**
*
* order of snippets ignored, use priority and inverse order in save with firstsnippet to insert correctly
*
* @param snippet snippet to insert
* @param w
* @param o
* @param prio priority of snippet according to other init codes, smaller means executed first
*/
void Mutatee::insertInitCode(BPatch_snippet* snippet, BPatch_callWhen w, BPatch_snippetOrder o, int prio) {
assert(initFunction != 0);
assert(snippet!=0);
initSnippets[prio].push_back(snippet);
}
void Mutatee::insertFinalizeCode(BPatch_snippet* snippet) {
// TODO finalize code support priority, too?
insertFinalizeCode(snippet, BPatch_callAfter, BPatch_lastSnippet);
}
void Mutatee::insertFinalizeCode(BPatch_snippet* snippet, BPatch_callWhen w, BPatch_snippetOrder o) {
assert(initFunction != 0);
if (finalizeInsertPoints == 0) {
finalizeInsertPoints = finalizeFunction->findPoint(BPatch_exit);
}
insertCode(*finalizeInsertPoints, snippet, w, o);
}
void Mutatee::setNameOfFunctionWhereToPlaceInit(string name) {
initFunction = getFunction(name);
assert(initFunction != 0);
}
void Mutatee::setNameOfFunctionWhereToPlaceFinalize(string name) {
finalizeFunction = getFunction(name);
assert(finalizeFunction != 0);
}
void Mutatee::addDependency(gii::Dependency dep) {
if (!addressSpace->loadLibrary((dep.path + dep.name).c_str(), false)) {
std::cout << "[WARNING] could not load library!\n";
}
}
| 29.204473 | 178 | 0.614484 | [
"vector"
] |
cf555990cea662bd383d6a46f5ff8d56045e5c9f | 1,288 | cpp | C++ | source_code/Scenes/Game/Map/bonus_points_manager.cpp | nooro/Pac-Man | 46b15ee00a4159696686080ea20f119736f15f45 | [
"MIT"
] | 9 | 2016-12-19T11:15:55.000Z | 2019-12-10T15:46:48.000Z | source_code/Scenes/Game/Map/bonus_points_manager.cpp | nooro/Pac-Man | 46b15ee00a4159696686080ea20f119736f15f45 | [
"MIT"
] | null | null | null | source_code/Scenes/Game/Map/bonus_points_manager.cpp | nooro/Pac-Man | 46b15ee00a4159696686080ea20f119736f15f45 | [
"MIT"
] | 2 | 2017-01-31T23:56:08.000Z | 2022-01-27T12:39:23.000Z | #include "bonus_points_manager.h"
SDL_Texture *BonusPointsManager::texture = NULL;
vector<SDL_Rect> BonusPointsManager::points;
SDL_Color BonusPointsManager::color;
void BonusPointsManager::Add(SDL_Rect rect)
{
BonusPointsManager::points.push_back(rect);
}
void BonusPointsManager::Delete(int index)
{
BonusPointsManager::points.erase(BonusPointsManager::points.begin() + index);
}
void BonusPointsManager::SetColor(SDL_Color color)
{
BonusPointsManager::texture = CreateTexture(POINT_IMAGE);
SDL_SetTextureColorMod(BonusPointsManager::texture, color.r, color.g, color.b);
}
void BonusPointsManager::Clear()
{
BonusPointsManager::points.clear();
}
void BonusPointsManager::Free()
{
SDL_DestroyTexture(BonusPointsManager::texture);
BonusPointsManager::Clear();
delete(&BonusPointsManager::points);
delete(&BonusPointsManager::color);
}
void BonusPointsManager::Render()
{
for(unsigned int i = 0; i < BonusPointsManager::points.size(); i++)
{
SDL_RenderCopy(System::Renderer, BonusPointsManager::texture, NULL, &BonusPointsManager::points[i]);
}
}
SDL_Rect BonusPointsManager::Get(int index) { return BonusPointsManager::points[index]; }
int BonusPointsManager::NumberOfPoints() { return BonusPointsManager::points.size(); }
| 27.404255 | 108 | 0.755435 | [
"render",
"vector"
] |
cf5b6199568fac190613bf5dd6f310f0a4911f0f | 481 | hh | C++ | src/option/option.hh | Idotno-1/MarioLANG | 61871c5e0582a8caff5df85166af84d4e558e6e5 | [
"MIT"
] | null | null | null | src/option/option.hh | Idotno-1/MarioLANG | 61871c5e0582a8caff5df85166af84d4e558e6e5 | [
"MIT"
] | null | null | null | src/option/option.hh | Idotno-1/MarioLANG | 61871c5e0582a8caff5df85166af84d4e558e6e5 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <optional>
#include <sstream>
#include <string>
#include <vector>
namespace option_parser
{
struct Options
{
Options()
{
display_ = false;
delay_ = -1;
}
std::vector<std::string> paths_; // ONE REQUIRED
bool display_; // OPTIONAL
int delay_; // OPTIONAL
};
std::optional<Options> parse_options(int argc, char* argv[]);
} // namespace option_parser | 19.24 | 65 | 0.586279 | [
"vector"
] |
cf5bab0db94c05be17de9e7156f187b741f037e6 | 5,840 | cpp | C++ | cpp/test/util/DictTest.cpp | 311labs/SRL | c3f0069270ada3784f2a81d9ec9e390e31e53a59 | [
"MIT"
] | 2 | 2018-12-21T01:55:23.000Z | 2021-11-29T01:30:37.000Z | cpp/test/util/DictTest.cpp | 311labs/SRL | c3f0069270ada3784f2a81d9ec9e390e31e53a59 | [
"MIT"
] | null | null | null | cpp/test/util/DictTest.cpp | 311labs/SRL | c3f0069270ada3784f2a81d9ec9e390e31e53a59 | [
"MIT"
] | null | null | null |
#include "DictTest.h"
#include "srl/util/Dictionary.h"
#include "srl/sys/System.h"
#include "srl/fs/TextFile.h"
#include "srl/math/Random.h"
using namespace SRL;
using namespace SRL::Test;
// int get_index(Util::Dictionary<int, String>::Entry *entry, Util::Dictionary<int, String> &dict)
// {
// Util::Dictionary<int, String>::Iterator iter = dict.begin();
// int index = 0;
// while (iter != dict.end())
// {
// if (iter._entry == entry)
// return index;
// ++iter;
// ++index;
// }
// return -1;
// }
//
//
// void print_dict(Util::Dictionary<int, String> &dict, const String& output)
// {
// static int counter = 0;
// ++counter;
// String filename = String::Format("%d_tree.png", counter);
// Util::Dictionary<int, String>::Iterator iter = dict.begin();
// Util::Dictionary<int, String>::Entry *entry = dict._root;
//
// Console::write("\nnew tree dump: ");
// Console::writeLine(filename.text());
// FS::TextFile *txtfile = FS::CreateTextFile("graph.dot", true);
//
// txtfile->writeLine("digraph g {");
// txtfile->writeLine("node [fontcolor=white, style=filled, fontname = \"Arial\", shape = record,height=.1];");
//
// String color = "RED";
// int index = 0;
// while (iter != dict.end())
// {
// entry = iter._entry;
// if (entry->_color == Util::Dictionary<int, String>::Entry::RED)
// color = "red";
// else
// color = "black";
//
// txtfile->formatLine("node%d[fillcolor=\"%s\", label = \"<f0> |<f1> %d|<f2> \"]", index, color.text(), entry->hash());
// ++iter;
// ++index;
// }
//
// iter = dict.begin();
// index = 0;
// while (iter != dict.end())
// {
// entry = iter._entry;
// if (entry->_lesser != NULL)
// txtfile->formatLine("\"node%d\":f0 -> \"node%d\":f1;", index, get_index(entry->_lesser, dict));
// if (entry->_greater != NULL)
// txtfile->formatLine("\"node%d\":f2 -> \"node%d\":f1;", index, get_index(entry->_greater, dict));
// ++iter;
// ++index;
// }
//
// txtfile->writeLine("}");
// txtfile->close();
//
// System::Run(String::Format("/opt/local/bin/dot -Tpng graph.dot -o %s", filename.text()));
//
// Console::writeLine("done");
// }
bool DictTest::basicTest()
{
Util::Dictionary<int, String> simple_dict;
simple_dict.add(5, "five"); // 0
TEST_ASSERT(simple_dict.hasKey(5))
TEST_ASSERT(simple_dict.containsValue("five"))
simple_dict.add(4, "four"); // 1
simple_dict.add(3, "three"); // 2
simple_dict.add(2, "two"); // 3
simple_dict.add(1, "one");
simple_dict.add(0, "zero"); // 5
simple_dict.add(50, "fifty");
simple_dict.add(25, "twenty-five");
simple_dict.add(30, "thirty");
simple_dict.add(12, "twelve");
simple_dict.add(26, "twenty-six");
simple_dict.add(24, "twenty-four");
simple_dict.add(66, "sixty-six");
simple_dict.add(84, "eighty-four");
TEST_ASSERT(simple_dict.hasKey(25))
TEST_ASSERT(simple_dict.containsValue("twenty-five"))
simple_dict.add(96, "ninety-six");
simple_dict.add(44, "fourty-four");
simple_dict.add(46, "fourty-six");
simple_dict.add(54, "fifty-four");
simple_dict.add(36, "thirty-six");
simple_dict.add(74, "seventy-four");
simple_dict.add(59, "fifty-nine");
simple_dict.add(72, "seventy-two");
simple_dict.add(62, "sixty-two");
simple_dict.add(91, "ninety-one");
simple_dict.add(88, "eighty-eight");
simple_dict.add(63, "sixty-three");
simple_dict.add(41, "seventy-four");
TEST_ASSERT(simple_dict[46] == "fourty-six")
TEST_ASSERT(simple_dict.size() == 27)
simple_dict.remove(74);
simple_dict.remove(84);
TEST_ASSERT(simple_dict.size() == 25);
simple_dict.remove(30);
simple_dict.remove(25);
simple_dict.remove(66);
simple_dict.remove(4);
TEST_ASSERT(simple_dict.size() == 21);
simple_dict.add(25, "twenty-five");
TEST_ASSERT(simple_dict.size() == 22);
simple_dict.clear();
// now lets do pointers
String name1 = "Bob Jones";
String name2 = "Marco Gomez";
String name3 = "Richard Lump";
String name4 = "Isabella Desilva";
Util::Dictionary<String, String*> ptr_list;
ptr_list.add("bob", &name1);
ptr_list.add("marco", &name2);
ptr_list["richard"] = &name3;
ptr_list.add("isabella", &name4);
TEST_ASSERT(ptr_list.size() == 4)
TEST_ASSERT((*ptr_list["marco"]) == "Marco Gomez")
name2 = "Mario Anders";
TEST_ASSERT(*ptr_list.get("marco") == "Mario Anders")
ptr_list.remove("marco");
TEST_ASSERT((*ptr_list["richard"]) == "Richard Lump")
Math::Random random;
// now lets create 1000 items
uint32 counter = 0;
uint32 first_value = 0;
for (int i=0;i<1000;++i)
{
uint32 value = random.randomInt(999);
if (!simple_dict.hasKey(value))
{
if (first_value == 0)
first_value = value;
++counter;
simple_dict.add(value, String::Val(value));
}
}
TEST_ASSERT(simple_dict.size() == counter)
TEST_ASSERT(simple_dict[first_value] == String::Val(first_value))
for (uint32 i=0;i<1000;++i)
{
if (simple_dict.hasKey(i))
{
simple_dict.remove(i);
}
}
TEST_ASSERT(simple_dict.isEmpty())
return true;
}
bool DictTest::iterationTest()
{
TEST_ASSERT(false)
return true;
}
bool DictTest::sortTest()
{
TEST_ASSERT(false)
return true;
}
bool DictTest::listTest()
{
TEST_ASSERT(false)
return true;
}
| 30.103093 | 128 | 0.568322 | [
"shape"
] |
cf5dfbad7b99faf1b2a9f6fe3707923f48f2edde | 12,969 | cpp | C++ | Game/Source/System.cpp | Micadurp/Blonic-The-Hooker | af35ce1ba18abc94827c79c53bf9605255211772 | [
"MIT"
] | null | null | null | Game/Source/System.cpp | Micadurp/Blonic-The-Hooker | af35ce1ba18abc94827c79c53bf9605255211772 | [
"MIT"
] | null | null | null | Game/Source/System.cpp | Micadurp/Blonic-The-Hooker | af35ce1ba18abc94827c79c53bf9605255211772 | [
"MIT"
] | null | null | null | #include "System.h"
System::System()
{
currentLevel = 0;
gamePlay = nullptr;
LevelInfo level;
level.scene = L"hus01_export";
level.collision = L"hus01_collision";
level.kristall = L"kristall01_collision";
level.winPlane = L"hus01_winning";
levels.push_back(level);
level.scene = L"hus02_export";
level.collision = L"hus02_collision";
level.kristall = L"kristall02_collision";
level.winPlane = L"hus02_winning";
levels.push_back(level);
level.scene = L"hus04_export";
level.collision = L"hus04_collision";
level.kristall = L"crystal04_collision";
level.winPlane = L"hus04_winning";
levels.push_back(level);
}
System::~System()
{
}
bool System::Initialize()
{
bool result;
// Initialize the width and height of the screen to zero before sending the variables into the function.
screenWidth = 0;
screenHeight = 0;
countsPerSecond = 0.0;
counterStart = 0;
frameCount = 0;
fps = 0;
frameTimeOld = 0;
frameTime = 0.0;
// Initialize the windows api.
InitializeWindows(screenWidth, screenHeight);
///////////////
gameState = GameState::gMenu;
direct3D = new Direct3D();
if (!direct3D)
{
return false;
}
timer = new TextClass();
if (!timer)
{
return false;
}
result = direct3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR, timer);
if (!result)
{
MessageBox(hwnd, L"Could not initialize Direct3D", L"Error", MB_OK);
return false;
}
menu = new Menu();
if (!menu)
{
return false;
}
wstring menuButtons[] = { L"menuBtn_newGame", L"menuBtn_howToPlay", L"menuBtn_Quit" };
result = menu->Initialize(direct3D->GetDevice(),3, hwnd, hinstance, L"menuBgrd_menu", menuButtons, (float)screenWidth, (float)screenHeight, SCREEN_NEAR, SCREEN_DEPTH);
if (!result)
{
MessageBox(hwnd, L"Could not initialize main menu", L"Error", MB_OK);
return false;
}
pauseMenu = new Menu();
if (!pauseMenu)
{
return false;
}
wstring pauseMenuButtons[] = { L"menuBtn_resume", L"menuBtn_Quit" };
result = pauseMenu->Initialize(direct3D->GetDevice(),2, hwnd, hinstance, L"menuBgrd_pause", pauseMenuButtons, (float)screenWidth, (float)screenHeight, SCREEN_NEAR, SCREEN_DEPTH);
if (!result)
{
MessageBox(hwnd, L"Could not initialize pause menu", L"Error", MB_OK);
return false;
}
deathScreen = new Menu();
if (!deathScreen)
{
return false;
}
result = deathScreen->Initialize(direct3D->GetDevice(),2, hwnd, hinstance, L"menuBgrd_dead", nullptr, (float)screenWidth, (float)screenHeight, SCREEN_NEAR, SCREEN_DEPTH);
if (!result)
{
MessageBox(hwnd, L"Could not initialize death screen", L"Error", MB_OK);
return false;
}
winScreen = new Menu();
if (!winScreen)
{
return false;
}
result = winScreen->Initialize(direct3D->GetDevice(),1, hwnd, hinstance, L"menuBgrd_win", nullptr, (float)screenWidth, (float)screenHeight, SCREEN_NEAR, SCREEN_DEPTH);
if (!result)
{
MessageBox(hwnd, L"Could not initialize win screen", L"Error", MB_OK);
return false;
}
loadScreen = new Menu();
if (!loadScreen)
{
return false;
}
result = loadScreen->Initialize(direct3D->GetDevice(),2, hwnd, hinstance, L"menuBgrd_load", nullptr, (float)screenWidth, (float)screenHeight, SCREEN_NEAR, SCREEN_DEPTH);
if (!result)
{
MessageBox(hwnd, L"Could not initialize load screen", L"Error", MB_OK);
return false;
}
howToPlay = new Menu();
if (!howToPlay)
{
return false;
}
result = howToPlay->Initialize(direct3D->GetDevice(), 1, hwnd, hinstance, L"menuBgrd_howToPlay", nullptr, (float)screenWidth, (float)screenHeight, SCREEN_NEAR, SCREEN_DEPTH);
if (!result)
{
MessageBox(hwnd, L"Could not initialize how to play screen", L"Error", MB_OK);
return false;
}
return true;
}
void System::Shutdown()
{
if (menu)
{
menu->Shutdown();
delete menu;
menu = 0;
}
if (pauseMenu)
{
pauseMenu->Shutdown();
delete pauseMenu;
pauseMenu = 0;
}
if (deathScreen)
{
deathScreen->Shutdown();
delete deathScreen;
deathScreen = 0;
}
if (winScreen)
{
winScreen->Shutdown();
delete winScreen;
winScreen = 0;
}
if (loadScreen)
{
loadScreen->Shutdown();
delete loadScreen;
loadScreen = 0;
}
if (howToPlay)
{
howToPlay->Shutdown();
delete howToPlay;
howToPlay = 0;
}
if (gamePlay)
{
gamePlay->Shutdown();
delete gamePlay;
gamePlay = nullptr;
}
if (direct3D)
{
direct3D->Shutdown();
delete direct3D;
direct3D = 0;
}
if (timer)
{
timer->ShutDown();
delete timer;
timer = 0;
}
// Shutdown the window.
ShutdownWindows();
}
void System::Run()
{
MSG msg;
bool done, result;
// Initialize the message structure.
ZeroMemory(&msg, sizeof(MSG));
// Loop until there is a quit message from the window or the user.
done = false;
while (!done)
{
// Handle the windows messages.
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// If windows signals to end the application then exit out.
if (msg.message == WM_QUIT)
{
done = true;
}
else
{
frameCount++;
if (GetTime() > 1.0f)
{
fps = frameCount;
frameCount = 0;
StartTimer();
}
frameTime = GetFrameTime();
// Otherwise do the frame processing.
result = Frame(frameTime);
if (!result)
{
done = true;
}
}
// Check if the user pressed escape and wants to quit.
/*if (player->IsEscapePressed() == true)
{
done = true;
}*/
}
return;
}
bool System::Frame(double _time)
{
int state;
#pragma region Update
switch (gameState)
{
case GameState::gGamePlay:
state = gamePlay->Update(_time);
//timer->Update((double)fps);
switch (state)
{
case 1:
gameState = GameState::gPause;
break;
case 2:
gameState = GameState::gDeath;
prevState = GameState::gGamePlay;
break;
case 3: //VICTORY
if (currentLevel < levels.size() - 1)
{
gameState = GameState::gLoading;
currentLevel++;
}
else
{
gameState = GameState::gWin;
currentLevel = 0;
}
}
prevState = GameState::gGamePlay;
break;
case GameState::gMenu:
state = menu->Update();
switch (state)
{
case 0:
gameState = GameState::gLoading;
prevState = GameState::gMenu;
break;
case 1:
gameState = GameState::gHowToPlay;
prevState = GameState::gMenu;
break;
case 2:
return false;
break;
}
break;
case GameState::gPause:
state = pauseMenu->Update();
switch (state)
{
case 1:
gameState = GameState::gGamePlay;
break;
case 2:
gameState = GameState::gMenu;
currentLevel = 0;
gamePlay->Shutdown();
delete gamePlay;
gamePlay = nullptr;
break;
}
break;
case GameState::gDeath:
if (prevState == GameState::gGamePlay)
{
gamePlay->Shutdown();
delete gamePlay;
gamePlay = new GamePlay();
gamePlay->Initialize(direct3D->GetDevice(), hwnd, hinstance, levels.at(currentLevel).scene, levels.at(currentLevel).collision, levels.at(currentLevel).kristall, levels.at(currentLevel).winPlane, currentLevel);
gameState = GameState::gGamePlay;
}
prevState = GameState::gDeath;
break;
case GameState::gLoading:
if (prevState == GameState::gGamePlay)
{
gamePlay->Shutdown();
delete gamePlay;
gamePlay = new GamePlay();
gamePlay->Initialize(direct3D->GetDevice(), hwnd, hinstance, levels.at(currentLevel).scene, levels.at(currentLevel).collision, levels.at(currentLevel).kristall, levels.at(currentLevel).winPlane, currentLevel);
gameState = GameState::gGamePlay;
}
else if(prevState == GameState::gMenu)
{
gamePlay = new GamePlay();
gamePlay->Initialize(direct3D->GetDevice(), hwnd, hinstance, levels.at(currentLevel).scene, levels.at(currentLevel).collision, levels.at(currentLevel).kristall, levels.at(currentLevel).winPlane, currentLevel);
gameState = GameState::gGamePlay;
}
prevState = GameState::gLoading;
break;
case GameState::gHowToPlay:
state = howToPlay->Update();
if (state != -1)
{
gameState = GameState::gMenu;
}
break;
default:
break;
}
#pragma endregion
#pragma region Draw
direct3D->BeginScene(1.0f, 0.0f, 0.0f, 1.0f);
switch (gameState)
{
case GameState::gGamePlay:
gamePlay->RenderHUD(direct3D, timer);
direct3D->DeferredFirstPass();
gamePlay->Render(direct3D, timer);
direct3D->DeferredRender();
break;
case GameState::gHowToPlay:
howToPlay->Render(direct3D);
break;
case GameState::gMenu:
menu->Render(direct3D);
break;
case GameState::gPause:
pauseMenu->Render(direct3D);
break;
case GameState::gDeath:
deathScreen->Render(direct3D);
break;
case GameState::gWin:
winScreen->Render(direct3D);
break;
case GameState::gLoading:
loadScreen->Render(direct3D);
break;
}
direct3D->EndScene();
#pragma endregion
return true;
}
LRESULT CALLBACK System::MessageHandler(HWND _hwnd, UINT _umsg, WPARAM _wparam, LPARAM _lparam)
{
return DefWindowProc(_hwnd, _umsg, _wparam, _lparam);
}
void System::InitializeWindows(int& _screenWidth, int& _screenHeight)
{
WNDCLASSEX wcex;
DEVMODE dmScreenSettings;
int posX, posY;
// Get an external pointer to this object.
ApplicationHandle = this;
// Get the instance of this application.
hinstance = GetModuleHandle(NULL);
// Give the application a name.
applicationName = L"The Legend Of Blonic: Hookarina of Time";
// Setup the windows class with default settings.
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hinstance;
wcex.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wcex.hIconSm = wcex.hIcon;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = applicationName;
wcex.cbSize = sizeof(WNDCLASSEX);
// Register the window class.
RegisterClassEx(&wcex);
// Determine the resolution of the clients desktop screen.
_screenWidth = GetSystemMetrics(SM_CXSCREEN);
_screenHeight = GetSystemMetrics(SM_CYSCREEN);
// Setup the screen settings depending on whether it is running in full screen or in windowed mode.
if (FULL_SCREEN)
{
// If full screen set the screen to maximum size of the users desktop and 32bit.
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
dmScreenSettings.dmSize = sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = (unsigned long)_screenWidth;
dmScreenSettings.dmPelsHeight = (unsigned long)_screenHeight;
dmScreenSettings.dmBitsPerPel = 32;
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
// Change the display settings to full screen.
ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
// Set the position of the window to the top left corner.
posX = posY = 0;
}
else
{
// If windowed then set it to 800x600 resolution.
_screenWidth = 800;
_screenHeight = 600;
// Place the window in the middle of the screen.
posX = (GetSystemMetrics(SM_CXSCREEN) - _screenWidth) / 2;
posY = (GetSystemMetrics(SM_CYSCREEN) - _screenHeight) / 2;
}
// Create the window with the screen settings and get the handle to it.
hwnd = CreateWindowEx(WS_EX_APPWINDOW,
applicationName,
applicationName,
WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_CAPTION | WS_SYSMENU,
posX,
posY,
_screenWidth,
_screenHeight,
nullptr,
nullptr,
hinstance,
nullptr);
// Bring the window up on the screen and set it as main focus.
ShowWindow(hwnd, SW_SHOW);
SetForegroundWindow(hwnd);
SetFocus(hwnd);
// Hide the mouse cursor.
ShowCursor(false);
return;
}
void System::ShutdownWindows()
{
// Show the mouse cursor.
ShowCursor(true);
// Fix the display settings if leaving full screen mode.
if (FULL_SCREEN)
{
ChangeDisplaySettings(NULL, 0);
}
// Remove the window.
DestroyWindow(hwnd);
hwnd = NULL;
// Remove the application instance.
UnregisterClass(applicationName, hinstance);
hinstance = NULL;
// Release the pointer to this class.
ApplicationHandle = NULL;
return;
}
LRESULT CALLBACK WndProc(HWND _hWnd, UINT _message, WPARAM _wParam, LPARAM _lParam)
{
switch (_message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_CLOSE:
{
PostQuitMessage(0);
return 0;
}
}
return DefWindowProc(_hWnd, _message, _wParam, _lParam);
}
void System::StartTimer()
{
LARGE_INTEGER frequencyCount;
QueryPerformanceFrequency(&frequencyCount);
countsPerSecond = double(frequencyCount.QuadPart);
QueryPerformanceCounter(&frequencyCount);
counterStart = frequencyCount.QuadPart;
}
double System::GetTime()
{
LARGE_INTEGER currentTime;
QueryPerformanceCounter(¤tTime);
return double(currentTime.QuadPart - counterStart) / countsPerSecond;
}
double System::GetFrameTime()
{
LARGE_INTEGER currentTime;
__int64 tickCount;
QueryPerformanceCounter(¤tTime);
tickCount = currentTime.QuadPart - frameTimeOld;
frameTimeOld = currentTime.QuadPart;
if (tickCount < 0.0f)
{
tickCount = 0;
}
return float(tickCount) / countsPerSecond;
} | 20.985437 | 212 | 0.702753 | [
"render",
"object"
] |
cf6be5acf38ebfde0285f448f8c36e130481ca03 | 4,836 | cpp | C++ | util/hardwareabstraction.cpp | OpenTactile/ScratchyShow | 475c460a5f7280092afc90e8b53c1c868af8b155 | [
"MIT"
] | 3 | 2017-11-17T11:48:51.000Z | 2018-04-25T14:39:20.000Z | util/hardwareabstraction.cpp | OpenTactile/ScratchyShow | 475c460a5f7280092afc90e8b53c1c868af8b155 | [
"MIT"
] | null | null | null | util/hardwareabstraction.cpp | OpenTactile/ScratchyShow | 475c460a5f7280092afc90e8b53c1c868af8b155 | [
"MIT"
] | null | null | null | #include "hardwareabstraction.h"
#include "view/view.h"
#include "model/tactiledisplay.h"
#include "model/actuator.h"
#include <itchy/tactilemousequery.h>
#include <scratchy/mousepositionquery.h>
#include <scratchy/graphicaldisplay.h>
#include <scratchy/signalmanager.h>
#include <unistd.h>
#include <mutex>
#include <QDebug>
#include <iostream>
static std::mutex hwlock;
#define float2q15(x) ((short)(x*32768))
#define q152float(x) ((((short)x)/32768.0f))
#define float2q5(x) ((short)(x*32))
HardwareAbstraction::HardwareAbstraction(View *view, bool perfMon):
view(view)
{
hwlock.lock();
controller = nullptr;
display = new GraphicalDisplay();
hwlock.unlock();
doStats = perfMon;
}
PositionQuery* HardwareAbstraction::connectInputdevice(PositionQuery* fallback)
{
view->showInfo("Input dev.", "Searching for\nTactileMouse");
//sleep(1);
// Try tactileMouse
PositionQuery* query = nullptr;
hwlock.lock();
query = new TactileMouseQuery(true);
if(!query->initialize())
{
hwlock.unlock();
delete query;
view->showInfo("Input dev.", "Searching for\nSimpleMouse");
//sleep(1);
hwlock.lock();
query = new MousePositionQuery();
if(!query->initialize())
{
hwlock.unlock();
delete query;
view->showInfo("Input dev.", "Using fallback");
query = fallback;
sleep(2);
view->clearInfo();
return query;
}
}
if(query)
delete fallback;
hwlock.unlock();
view->clearInfo();
return query;
}
void HardwareAbstraction::initializeSignalBoards()
{
view->showInfo("Initialization", "Initializing SignalBoards");
hwlock.lock();
if(!controller)
controller = new SignalManager();
controller->maskDevice(60); // Skip OLED Display
controller->initializeBoards(); // Default initialization to runlevel 3
hwlock.unlock();
view->clearInfo();
}
bool HardwareAbstraction::checkAdressLayout(const TactileDisplay *tactileDisplay)
{
#ifdef FAKEMODE
return true;
#endif
hwlock.lock();
auto devices = controller->scanDevices();
for(auto device : devices)
actuatorMapping.insert(device, std::array<FrequencyTable, 4>());
usleep(100000);
hwlock.unlock();
// Check if selected display matches current hardware configuration
for(const Actuator& actuator : tactileDisplay->actuators())
{
// Check if Actuator exists
if(!actuatorMapping.contains(actuator.PortID))
{
return false;
}
}
return true;
}
HardwareAbstraction::DisplayButton HardwareAbstraction::currentButton()
{
hwlock.lock();
if(display->isPressed(Button::Up))
{
hwlock.unlock();
usleep(200000);
return DisplayButton::Up;
}
if(display->isPressed(Button::Down))
{
hwlock.unlock();
usleep(200000);
return DisplayButton::Down;
}
if(display->isPressed(Button::Select))
{
hwlock.unlock();
usleep(200000);
return DisplayButton::Select;
}
if(display->isPressed(Button::Back))
{
hwlock.unlock();
sleep(1);
hwlock.lock();
if(display->isPressed(Button::Back))
{
hwlock.unlock();
usleep(200000);
return DisplayButton::Reset;
}
hwlock.unlock();
return DisplayButton::Back;
}
hwlock.unlock();
return DisplayButton::None;
}
void HardwareAbstraction::shutdown()
{
view->showInfo("Exiting", "Shutting down SignalBoards");
// Send Shutdown signal to all teensys
hwlock.lock();
for(SignalGenerator& g : controller->generators())
{
g.shutdown();
}
// Clear screen before exiting program
display->clear();
hwlock.unlock();
}
void HardwareAbstraction::sendTables(const TactileDisplay* display,
const QVector<FrequencyTable>& data)
{
#ifdef FAKEMODE
return;
#endif
hwlock.lock();
for(int i = 0; i < data.size(); i++)
{
const Actuator& actuator = display->actuators()[i];
actuatorMapping[actuator.PortID][actuator.PinID] = data[i];
}
for(SignalGenerator& g : controller->generators())
g.send(actuatorMapping[g.address()]);
hwlock.unlock();
if(doStats)
{
if(!statsDone)
{
//this->display->detach();
statsDone = true;
timer.start();
}
if(ticks > 0 && ticks % 1000 == 0)
{
//float us = timer.nsecsElapsed()/float(ticks) * 1.0e-9;
//qDebug() << "s: " << us << "\tHz: " << 1.0/us;
ticks = 0;
timer.restart();
}
ticks++;
}
}
| 22.919431 | 81 | 0.594706 | [
"model"
] |
cf772a13357dbb03b046231f77363694a25b613b | 782 | cpp | C++ | src/caffe/layers/activation/dropout_layer.cpp | JEF1056/MetaLearning-Neural-Style | 94ac33cb6a62c4de8ff2aeac3572afd61f1bda5d | [
"MIT"
] | 126 | 2017-09-14T01:53:15.000Z | 2021-03-24T08:57:41.000Z | src/caffe/layers/activation/dropout_layer.cpp | hli1221/styletransfer | 5101f2c024638d3e111644c64398b3290fdeaec6 | [
"BSD-2-Clause"
] | 17 | 2017-09-14T09:11:50.000Z | 2019-11-27T08:56:52.000Z | src/caffe/layers/activation/dropout_layer.cpp | hli1221/styletransfer | 5101f2c024638d3e111644c64398b3290fdeaec6 | [
"BSD-2-Clause"
] | 34 | 2017-09-14T09:14:21.000Z | 2020-12-16T09:49:40.000Z | // TODO (sergeyk): effect should not be dependent on phase. wasted memcpy.
#include <vector>
#include "caffe/layers/activation/dropout_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
void DropoutLayer::LayerSetUp(const vector<Blob*>& bottom, const vector<Blob*>& top)
{
threshold_ = this->layer_param_.dropout_param().dropout_ratio();
DCHECK(threshold_ > 0.);
DCHECK(threshold_ < 1.);
}
void DropoutLayer::Reshape(const vector<Blob*>& bottom, const vector<Blob*>& top)
{
int num = bottom[0]->num();
int channels = bottom[0]->channels();
int height = bottom[0]->height();
int width = bottom[0]->width();
top[0]->ReshapeLike(*bottom[0]);
rand_vec_.Reshape(1,channels,1,1);
}
REGISTER_LAYER_CLASS(Dropout);
} // namespace caffe
| 20.578947 | 85 | 0.699488 | [
"vector"
] |
cf77b11e08a62a922ea1569d6346d39afa5be774 | 3,127 | cpp | C++ | src/DiagHN.cpp | lgds/NRG_USP | ff66846e92498aa429cce6fc5793bec23ad03eb4 | [
"MIT"
] | 3 | 2015-09-21T20:58:45.000Z | 2019-03-20T01:21:41.000Z | src/DiagHN.cpp | lgds/NRG_USP | ff66846e92498aa429cce6fc5793bec23ad03eb4 | [
"MIT"
] | null | null | null | src/DiagHN.cpp | lgds/NRG_USP | ff66846e92498aa429cce6fc5793bec23ad03eb4 | [
"MIT"
] | null | null | null |
#include "NRGclasses.hpp"
void CNRGmatrix::DiagHN(vector<double> ParamsHN,
CNRGbasisarray* pAbasis,
CNRGbasisarray* pSingleSite,
CNRGmatrix* MatArray,
CNRGarray* pAeig,bool display)
{
// New (July 08) // display is dummy, can be omitted
ClearAll();
SyncNRGarray(*pAbasis);
int icount=0;
for (int ibl=0;ibl<pAbasis->NumBlocks();ibl++)
//for (int ibl=0;ibl<=2;ibl++)
{
cout << " Setting up H_(N =" << pAbasis->Nshell << " : ibl = " << ibl
<< " size = " << pAbasis->GetBlockSize(ibl)
<< " (Nbls = " << pAbasis->NumBlocks() << ")" << endl;
cout << " Limits : " << pAbasis->GetBlockLimit(ibl,0) << " "
<< pAbasis->GetBlockLimit(ibl,1) << endl;
// HN is block diagonal (ibl,ibl) so we are setting the blocks
MatBlockMap.push_back(ibl);
MatBlockMap.push_back(ibl);
// Each MatBlock is Nbl x Nbl in lenght
MatBlockBegEnd.push_back(icount);
//icount+=pAbasis->GetBlockSize(ibl)*pAbasis->GetBlockSize(ibl);
// New
int sizebl=pAbasis->GetBlockSize(ibl);
if (UpperTriangular){
icount+=(sizebl*(sizebl+1))/2;
//cout << "Got here " << endl;
}
else
icount+=sizebl*sizebl;
MatBlockBegEnd.push_back(icount-1);
for (int ist=pAbasis->GetBlockLimit(ibl,0);
ist<=pAbasis->GetBlockLimit(ibl,1);ist++)
{
// for (int jst=pAbasis->GetBlockLimit(ibl,0);
// jst<=pAbasis->GetBlockLimit(ibl,1);jst++)
// NEW THING! only calculates half of matrix els!
int j0;
if (UpperTriangular) j0=ist;
else j0=pAbasis->GetBlockLimit(ibl,0);
for (int jst=j0;
jst<=pAbasis->GetBlockLimit(ibl,1);jst++){
if (!IsComplex){
double auxEl=CalcHNMatEl(ParamsHN,
pAbasis,
pSingleSite,
MatArray,
ist,jst);
MatEl.push_back(auxEl);
}else{
complex<double> auxEl=CalcHNMatElCplx(ParamsHN,
pAbasis,
pSingleSite,
MatArray,
ist,jst);
MatElCplx.push_back(auxEl);
}
// end if is complex
}
// end loop in ist
}
// end loop in ist
}
// end loop in blocks
cout << " Done setting up HN. " << endl;
cout << "Updating Aeig... " << endl;
pAeig->ClearAll();
// Syncronize with HN
pAeig->Nshell=CNRGarray::Nshell;
pAeig->NQNumbers=CNRGarray::NQNumbers;
pAeig->QNumbers=CNRGarray::QNumbers;
pAeig->BlockBegEnd=CNRGarray::BlockBegEnd;
pAeig->totalS=CNRGarray::totalS;
pAeig->Sqnumbers=CNRGarray::Sqnumbers;
// Set dEn,dEigVec
pAeig->dEn.clear();
pAeig->dEigVec.clear();
pAeig->cEigVec.clear();
for (int ibl=0;ibl<NumBlocks();ibl++)
{
if (display){
cout << " ******************* " << endl;
pAbasis->PrintBlockBasis(ibl);
PrintMatBlock(ibl,ibl);
}
cout << " Diagonalizing block " << ibl << " of " << NumBlocks()-1 << endl;
if(!IsComplex) DiagBlock(ibl,pAeig->dEn,pAeig->dEigVec);
else DiagBlock(ibl,pAeig->dEn,pAeig->cEigVec);
// if (display){pAeig->PrintBlockEn(ibl);}
if (display){pAeig->PrintBlock(ibl);}
}
//uset this later
pAeig->SetE0zero();
}
// end subroutine
| 25.842975 | 80 | 0.600256 | [
"vector"
] |
cf7c8591ac066e241833cae9cc7010e36bb45782 | 19,934 | cpp | C++ | src/graph/executor/algo/BatchShortestPath.cpp | pengweisong/nebula | 56856e76a80785da0ec96c3a32f9bf6feb02c740 | [
"Apache-2.0"
] | null | null | null | src/graph/executor/algo/BatchShortestPath.cpp | pengweisong/nebula | 56856e76a80785da0ec96c3a32f9bf6feb02c740 | [
"Apache-2.0"
] | null | null | null | src/graph/executor/algo/BatchShortestPath.cpp | pengweisong/nebula | 56856e76a80785da0ec96c3a32f9bf6feb02c740 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2022 vesoft inc. All rights reserved.
//
// This source code is licensed under Apache 2.0 License.
#include "graph/executor/algo/BatchShortestPath.h"
#include <climits>
#include "graph/service/GraphFlags.h"
#include "sys/sysinfo.h"
using nebula::storage::StorageClient;
DECLARE_uint32(num_path_thread);
namespace nebula {
namespace graph {
folly::Future<Status> BatchShortestPath::execute(const std::unordered_set<Value>& startVids,
const std::unordered_set<Value>& endVids,
DataSet* result) {
size_t rowSize = init(startVids, endVids);
std::vector<folly::Future<Status>> futures;
futures.reserve(rowSize);
for (size_t rowNum = 0; rowNum < rowSize; ++rowNum) {
resultDs_[rowNum].colNames = pathNode_->colNames();
futures.emplace_back(shortestPath(rowNum, 1));
}
return folly::collect(futures)
.via(qctx_->rctx()->runner())
.thenValue([this, result](auto&& resps) {
for (auto& resp : resps) {
NG_RETURN_IF_ERROR(resp);
}
result->colNames = pathNode_->colNames();
for (auto& ds : resultDs_) {
result->append(std::move(ds));
}
return Status::OK();
});
}
size_t BatchShortestPath::init(const std::unordered_set<Value>& startVids,
const std::unordered_set<Value>& endVids) {
size_t rowSize = splitTask(startVids, endVids);
leftVids_.reserve(rowSize);
rightVids_.reserve(rowSize);
allLeftPathMaps_.resize(rowSize);
allRightPathMaps_.resize(rowSize);
currentLeftPathMaps_.reserve(rowSize);
currentRightPathMaps_.reserve(rowSize);
preRightPathMaps_.reserve(rowSize);
terminationMaps_.reserve(rowSize);
resultDs_.resize(rowSize);
for (auto& _startVids : batchStartVids_) {
DataSet startDs;
PathMap leftPathMap;
for (auto& startVid : _startVids) {
startDs.rows.emplace_back(Row({startVid}));
std::vector<CustomPath> dummy;
leftPathMap[startVid].emplace(startVid, std::move(dummy));
}
for (auto& _endVids : batchEndVids_) {
DataSet endDs;
PathMap preRightPathMap;
PathMap rightPathMap;
for (auto& endVid : _endVids) {
endDs.rows.emplace_back(Row({endVid}));
std::vector<CustomPath> dummy;
rightPathMap[endVid].emplace(endVid, dummy);
preRightPathMap[endVid].emplace(endVid, std::move(dummy));
}
// set originRightpath
currentLeftPathMaps_.emplace_back(leftPathMap);
preRightPathMaps_.emplace_back(std::move(preRightPathMap));
currentRightPathMaps_.emplace_back(std::move(rightPathMap));
// set vid for getNeightbor
leftVids_.emplace_back(startDs);
rightVids_.emplace_back(std::move(endDs));
// set terminateMap
std::unordered_multimap<StartVid, std::pair<EndVid, bool>> terminationMap;
for (auto& _startVid : _startVids) {
for (auto& _endVid : _endVids) {
if (_startVid != _endVid) {
terminationMap.emplace(_startVid, std::make_pair(_endVid, true));
}
}
}
terminationMaps_.emplace_back(std::move(terminationMap));
}
}
return rowSize;
}
folly::Future<Status> BatchShortestPath::shortestPath(size_t rowNum, size_t stepNum) {
std::vector<folly::Future<Status>> futures;
futures.emplace_back(getNeighbors(rowNum, stepNum, false));
futures.emplace_back(getNeighbors(rowNum, stepNum, true));
return folly::collect(futures)
.via(qctx_->rctx()->runner())
.thenValue([this, rowNum, stepNum](auto&& resps) {
for (auto& resp : resps) {
if (!resp.ok()) {
return folly::makeFuture<Status>(std::move(resp));
}
}
return handleResponse(rowNum, stepNum);
});
}
folly::Future<Status> BatchShortestPath::getNeighbors(size_t rowNum, size_t stepNum, bool reverse) {
StorageClient* storageClient = qctx_->getStorageClient();
time::Duration getNbrTime;
storage::StorageClient::CommonRequestParam param(pathNode_->space(),
qctx_->rctx()->session()->id(),
qctx_->plan()->id(),
qctx_->plan()->isProfileEnabled());
auto& inputRows = reverse ? rightVids_[rowNum].rows : leftVids_[rowNum].rows;
return storageClient
->getNeighbors(param,
{nebula::kVid},
std::move(inputRows),
{},
pathNode_->edgeDirection(),
nullptr,
pathNode_->vertexProps(),
reverse ? pathNode_->reverseEdgeProps() : pathNode_->edgeProps(),
nullptr,
false,
false,
{},
-1,
nullptr)
.via(qctx_->rctx()->runner())
.thenValue([this, rowNum, reverse, stepNum, getNbrTime](auto&& resp) {
addStats(resp, stats_, stepNum, getNbrTime.elapsedInUSec(), reverse);
return buildPath(rowNum, std::move(resp), reverse);
});
}
Status BatchShortestPath::buildPath(size_t rowNum, RpcResponse&& resps, bool reverse) {
auto result = handleCompleteness(resps, FLAGS_accept_partial_success);
NG_RETURN_IF_ERROR(result);
auto& responses = std::move(resps).responses();
List list;
for (auto& resp : responses) {
auto dataset = resp.get_vertices();
if (dataset == nullptr) {
LOG(INFO) << "Empty dataset in response";
continue;
}
list.values.emplace_back(std::move(*dataset));
}
auto listVal = std::make_shared<Value>(std::move(list));
auto iter = std::make_unique<GetNeighborsIter>(listVal);
return doBuildPath(rowNum, iter.get(), reverse);
}
Status BatchShortestPath::doBuildPath(size_t rowNum, GetNeighborsIter* iter, bool reverse) {
auto& historyPathMap = reverse ? allRightPathMaps_[rowNum] : allLeftPathMaps_[rowNum];
auto& currentPathMap = reverse ? currentRightPathMaps_[rowNum] : currentLeftPathMaps_[rowNum];
for (; iter->valid(); iter->next()) {
auto edgeVal = iter->getEdge();
if (UNLIKELY(!edgeVal.isEdge())) {
continue;
}
auto& edge = edgeVal.getEdge();
auto src = edge.src;
auto dst = edge.dst;
if (src == dst) {
continue;
}
auto vertex = iter->getVertex();
CustomPath customPath;
customPath.emplace_back(std::move(vertex));
customPath.emplace_back(std::move(edge));
auto findSrcFromHistory = historyPathMap.find(src);
if (findSrcFromHistory == historyPathMap.end()) {
// first step
auto findDstFromCurrent = currentPathMap.find(dst);
if (findDstFromCurrent == currentPathMap.end()) {
std::vector<CustomPath> tmp({std::move(customPath)});
currentPathMap[dst].emplace(src, std::move(tmp));
} else {
auto findSrc = findDstFromCurrent->second.find(src);
if (findSrc == findDstFromCurrent->second.end()) {
std::vector<CustomPath> tmp({std::move(customPath)});
findDstFromCurrent->second.emplace(src, std::move(tmp));
} else {
// same <src, dst>, different edge type or rank
findSrc->second.emplace_back(std::move(customPath));
}
}
} else {
// not first step
auto& srcPathMap = findSrcFromHistory->second;
auto findDstFromHistory = historyPathMap.find(dst);
if (findDstFromHistory == historyPathMap.end()) {
// dst not in history
auto findDstFromCurrent = currentPathMap.find(dst);
if (findDstFromCurrent == currentPathMap.end()) {
// dst not in current, new edge
for (const auto& srcPath : srcPathMap) {
currentPathMap[dst].emplace(srcPath.first, createPaths(srcPath.second, customPath));
}
} else {
// dst in current
for (const auto& srcPath : srcPathMap) {
auto newPaths = createPaths(srcPath.second, customPath);
auto findSrc = findDstFromCurrent->second.find(srcPath.first);
if (findSrc == findDstFromCurrent->second.end()) {
findDstFromCurrent->second.emplace(srcPath.first, std::move(newPaths));
} else {
findSrc->second.insert(findSrc->second.begin(),
std::make_move_iterator(newPaths.begin()),
std::make_move_iterator(newPaths.end()));
}
}
}
} else {
// dst in history
auto& dstPathMap = findDstFromHistory->second;
for (const auto& srcPath : srcPathMap) {
if (dstPathMap.find(srcPath.first) != dstPathMap.end()) {
// loop : a->b->c->a or a->b->c->b
// filter out path that with duplicate vertex or have already been found before
continue;
}
auto findDstFromCurrent = currentPathMap.find(dst);
if (findDstFromCurrent == currentPathMap.end()) {
currentPathMap[dst].emplace(srcPath.first, createPaths(srcPath.second, customPath));
} else {
auto newPaths = createPaths(srcPath.second, customPath);
auto findSrc = findDstFromCurrent->second.find(srcPath.first);
if (findSrc == findDstFromCurrent->second.end()) {
findDstFromCurrent->second.emplace(srcPath.first, std::move(newPaths));
} else {
findSrc->second.insert(findSrc->second.begin(),
std::make_move_iterator(newPaths.begin()),
std::make_move_iterator(newPaths.end()));
}
}
}
}
}
}
// set nextVid
setNextStepVid(currentPathMap, rowNum, reverse);
return Status::OK();
}
folly::Future<Status> BatchShortestPath::handleResponse(size_t rowNum, size_t stepNum) {
return folly::makeFuture(Status::OK())
.via(qctx_->rctx()->runner())
.thenValue([this, rowNum](auto&& status) {
// odd step
UNUSED(status);
return conjunctPath(rowNum, true);
})
.thenValue([this, rowNum, stepNum](auto&& terminate) {
// even Step
if (terminate || stepNum * 2 > maxStep_) {
return folly::makeFuture<bool>(true);
}
return conjunctPath(rowNum, false);
})
.thenValue([this, rowNum, stepNum](auto&& result) {
if (result || stepNum * 2 >= maxStep_) {
return folly::makeFuture<Status>(Status::OK());
}
auto& leftVids = leftVids_[rowNum].rows;
auto& rightVids = rightVids_[rowNum].rows;
if (leftVids.empty() || rightVids.empty()) {
return folly::makeFuture<Status>(Status::OK());
}
// update allPathMap
auto& leftPathMap = currentLeftPathMaps_[rowNum];
auto& rightPathMap = currentRightPathMaps_[rowNum];
preRightPathMaps_[rowNum] = rightPathMap;
for (auto& iter : leftPathMap) {
allLeftPathMaps_[rowNum][iter.first].insert(std::make_move_iterator(iter.second.begin()),
std::make_move_iterator(iter.second.end()));
}
for (auto& iter : rightPathMap) {
allRightPathMaps_[rowNum][iter.first].insert(std::make_move_iterator(iter.second.begin()),
std::make_move_iterator(iter.second.end()));
}
leftPathMap.clear();
rightPathMap.clear();
return shortestPath(rowNum, stepNum + 1);
});
}
folly::Future<std::vector<Value>> BatchShortestPath::getMeetVids(size_t rowNum,
bool oddStep,
std::vector<Value>& meetVids) {
if (!oddStep) {
return getMeetVidsProps(meetVids);
}
std::vector<Value> vertices;
vertices.reserve(meetVids.size());
for (auto& meetVid : meetVids) {
for (auto& dstPaths : currentRightPathMaps_[rowNum]) {
bool flag = false;
for (auto& srcPaths : dstPaths.second) {
for (auto& path : srcPaths.second) {
auto& vertex = path.values[path.size() - 2];
auto& vid = vertex.getVertex().vid;
if (vid == meetVid) {
vertices.emplace_back(vertex);
flag = true;
break;
}
}
if (flag) {
break;
}
}
if (flag) {
break;
}
}
}
return folly::makeFuture<std::vector<Value>>(std::move(vertices));
}
folly::Future<bool> BatchShortestPath::conjunctPath(size_t rowNum, bool oddStep) {
auto& _leftPathMaps = currentLeftPathMaps_[rowNum];
auto& _rightPathMaps = oddStep ? preRightPathMaps_[rowNum] : currentRightPathMaps_[rowNum];
std::vector<Value> meetVids;
meetVids.reserve(_leftPathMaps.size());
for (const auto& leftPathMap : _leftPathMaps) {
auto findCommonVid = _rightPathMaps.find(leftPathMap.first);
if (findCommonVid != _rightPathMaps.end()) {
meetVids.emplace_back(findCommonVid->first);
}
}
if (meetVids.empty()) {
return folly::makeFuture<bool>(false);
}
auto future = getMeetVids(rowNum, oddStep, meetVids);
return future.via(qctx_->rctx()->runner()).thenValue([this, rowNum, oddStep](auto&& vertices) {
if (vertices.empty()) {
return false;
}
std::unordered_map<Value, Value> verticesMap;
for (auto& vertex : vertices) {
verticesMap[vertex.getVertex().vid] = std::move(vertex);
}
auto& terminationMap = terminationMaps_[rowNum];
auto& leftPathMaps = currentLeftPathMaps_[rowNum];
auto& rightPathMaps = oddStep ? preRightPathMaps_[rowNum] : currentRightPathMaps_[rowNum];
for (const auto& leftPathMap : leftPathMaps) {
auto findCommonVid = rightPathMaps.find(leftPathMap.first);
if (findCommonVid == rightPathMaps.end()) {
continue;
}
auto findCommonVertex = verticesMap.find(findCommonVid->first);
if (findCommonVertex == verticesMap.end()) {
continue;
}
auto& rightPaths = findCommonVid->second;
for (const auto& srcPaths : leftPathMap.second) {
auto range = terminationMap.equal_range(srcPaths.first);
if (range.first == range.second) {
continue;
}
for (const auto& dstPaths : rightPaths) {
for (auto found = range.first; found != range.second; ++found) {
if (found->second.first == dstPaths.first) {
if (singleShortest_ && !found->second.second) {
break;
}
doConjunctPath(srcPaths.second, dstPaths.second, findCommonVertex->second, rowNum);
found->second.second = false;
}
}
}
}
}
// update terminationMap
for (auto iter = terminationMap.begin(); iter != terminationMap.end();) {
if (!iter->second.second) {
iter = terminationMap.erase(iter);
} else {
++iter;
}
}
if (terminationMap.empty()) {
return true;
}
return false;
});
}
void BatchShortestPath::doConjunctPath(const std::vector<CustomPath>& leftPaths,
const std::vector<CustomPath>& rightPaths,
const Value& commonVertex,
size_t rowNum) {
auto& resultDs = resultDs_[rowNum];
if (rightPaths.empty()) {
for (const auto& leftPath : leftPaths) {
auto forwardPath = leftPath.values;
auto src = forwardPath.front();
forwardPath.erase(forwardPath.begin());
Row row;
row.emplace_back(std::move(src));
row.emplace_back(List(std::move(forwardPath)));
row.emplace_back(commonVertex);
resultDs.rows.emplace_back(std::move(row));
if (singleShortest_) {
return;
}
}
return;
}
for (const auto& leftPath : leftPaths) {
for (const auto& rightPath : rightPaths) {
auto forwardPath = leftPath.values;
auto backwardPath = rightPath.values;
auto src = forwardPath.front();
forwardPath.erase(forwardPath.begin());
forwardPath.emplace_back(commonVertex);
std::reverse(backwardPath.begin(), backwardPath.end());
forwardPath.insert(forwardPath.end(),
std::make_move_iterator(backwardPath.begin()),
std::make_move_iterator(backwardPath.end()));
auto dst = forwardPath.back();
forwardPath.pop_back();
Row row;
row.emplace_back(std::move(src));
row.emplace_back(List(std::move(forwardPath)));
row.emplace_back(std::move(dst));
resultDs.rows.emplace_back(std::move(row));
if (singleShortest_) {
return;
}
}
}
}
// [a, a->b, b, b->c ] insert [c, c->d] result is [a, a->b, b, b->c, c, c->d]
std::vector<Row> BatchShortestPath::createPaths(const std::vector<CustomPath>& paths,
const CustomPath& path) {
std::vector<CustomPath> newPaths;
newPaths.reserve(paths.size());
for (const auto& p : paths) {
auto customPath = p;
customPath.values.insert(customPath.values.end(), path.values.begin(), path.values.end());
newPaths.emplace_back(std::move(customPath));
}
return newPaths;
}
void BatchShortestPath::setNextStepVid(const PathMap& paths, size_t rowNum, bool reverse) {
std::vector<Row> nextStepVids;
nextStepVids.reserve(paths.size());
for (const auto& path : paths) {
Row row;
row.values.emplace_back(path.first);
nextStepVids.emplace_back(std::move(row));
}
if (reverse) {
rightVids_[rowNum].rows.swap(nextStepVids);
} else {
leftVids_[rowNum].rows.swap(nextStepVids);
}
}
size_t BatchShortestPath::splitTask(const std::unordered_set<Value>& startVids,
const std::unordered_set<Value>& endVids) {
size_t threadNum = FLAGS_num_path_thread;
size_t startVidsSize = startVids.size();
size_t endVidsSize = endVids.size();
size_t maxSlices = startVidsSize < threadNum ? startVidsSize : threadNum;
int minValue = INT_MAX;
size_t startSlices = 1;
size_t endSlices = 1;
for (size_t i = maxSlices; i >= 1; --i) {
auto j = threadNum / i;
auto val = std::abs(static_cast<int>(startVidsSize / i) - static_cast<int>(endVidsSize / j));
if (val < minValue) {
minValue = val;
startSlices = i;
endSlices = j;
}
}
// split tasks
{
auto batchSize = startVidsSize / startSlices;
size_t i = 0;
size_t slices = 1;
size_t count = 1;
std::vector<StartVid> tmp;
tmp.reserve(batchSize);
for (auto& startVid : startVids) {
tmp.emplace_back(startVid);
if ((++i == batchSize && slices != startSlices) || count == startVidsSize) {
batchStartVids_.emplace_back(std::move(tmp));
tmp.reserve(batchSize);
i = 0;
++slices;
}
++count;
}
}
{
auto batchSize = endVidsSize / endSlices;
size_t i = 0;
size_t slices = 1;
size_t count = 1;
std::vector<EndVid> tmp;
tmp.reserve(batchSize);
for (auto& endVid : endVids) {
tmp.emplace_back(endVid);
if ((++i == batchSize && slices != endSlices) || count == endVidsSize) {
batchEndVids_.emplace_back(std::move(tmp));
tmp.reserve(batchSize);
i = 0;
++slices;
}
++count;
}
}
std::stringstream ss;
ss << "{\n"
<< "startVids' size : " << startVidsSize << " endVids's size : " << endVidsSize;
ss << " thread num : " << threadNum;
ss << " start blocks : " << startSlices << " end blocks : " << endSlices << "\n}";
stats_->emplace(folly::sformat("split task "), ss.str());
return startSlices * endSlices;
}
} // namespace graph
} // namespace nebula
| 36.778598 | 100 | 0.599478 | [
"vector"
] |
cf7d52429b153412c0007f7cf611608ab610bf57 | 11,311 | cpp | C++ | interfaces/matlab/src/funcs.cpp | nzjrs/opencv_old_libdc1394 | b4ed48568cd774e8ec47336d59887261eb8d518c | [
"BSD-3-Clause"
] | 1 | 2016-05-09T04:17:32.000Z | 2016-05-09T04:17:32.000Z | interfaces/matlab/src/funcs.cpp | hcl3210/opencv | b34b1c3540716a3dadfd2b9e3bbc4253774c636d | [
"BSD-3-Clause"
] | null | null | null | interfaces/matlab/src/funcs.cpp | hcl3210/opencv | b34b1c3540716a3dadfd2b9e3bbc4253774c636d | [
"BSD-3-Clause"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "funcs.h"
//-----------------------------------------------------------------------------
std::string get_string( const mxArray *mxArr )
{
int l = mxGetN(mxArr);
char* buf = new char[l + 2];
mxGetString(mxArr, buf, l + 1);
std::string s(buf);
delete[] buf;
return s;
}
//------------------------------------------------------------------------------
// verifyDepth
//
void verifyDepth( mxClassID classID, bool bAnyDepth, int &depth )
{
int _depth = depth;
switch( classID )
{
case mxUINT8_CLASS:
depth = IPL_DEPTH_8U;
break;
case mxUINT16_CLASS:
depth = IPL_DEPTH_16U;
break;
case mxSINGLE_CLASS:
depth = IPL_DEPTH_32F;
break;
case mxINT8_CLASS:
depth = IPL_DEPTH_8S;
break;
case mxINT16_CLASS:
depth = IPL_DEPTH_16S;
break;
case mxINT32_CLASS:
depth = IPL_DEPTH_32S;
break;
default:
throw_error( "Unsupported image format." );
return;
break;
}
if( !bAnyDepth && depth != _depth )
{
throw_error( "Incorrect image type." );
return;
}
}
//------------------------------------------------------------------------------
// verifyArray
//
void verifyArray( mxArray *mxArr, int *dims, int &ndim, bool bAllowEmpty,
bool bAnyClass, mxClassID &classID )
{
bool bEmpty = mxIsEmpty( mxArr );
if( !bAllowEmpty && bEmpty )
{
throw_error( "Array should be not empty." );
return;
}
if( bEmpty )
{
if( ndim <= 0 )
{
ndim = mxGetNumberOfDimensions( mxArr );
}
int dim = 0;
for( dim = 0; dim < ndim; dim++ )
{
if( dims[dim] < 0 )
{
dims[dim] = 0;
}
}
return;
}
mxClassID _classID = classID;
classID = mxGetClassID( mxArr );
if( !bAnyClass && classID != _classID )
{
throw_error( "Incorrect array type." );
return;
}
int _ndim = ndim;
ndim = mxGetNumberOfDimensions( mxArr );
if( _ndim > 0 && ndim != _ndim )
{
std::ostringstream ostr;
ostr << "Incorrect array size. " <<
"Array should have " << _ndim << " dimensions.";
throw_error( ostr.str() );
return;
}
const int *_dims = mxGetDimensions( mxArr );
int dim = 0;
for( dim = 0; dim < ndim; dim++ )
{
if( dims[dim] > 0 && dims[dim] != _dims[dim] )
{
std::ostringstream ostr;
ostr << "Incorrect array size. " <<
"Dimension: " << (dim + 1) << ".";
throw_error( ostr.str() );
return;
}
dims[dim] = _dims[dim];
} // for each dimension
}
//------------------------------------------------------------------------------
// verifyMatrix
//
void verifyMatrix( mxArray *mxArr, int &rows, int &cols, bool bAllowEmpty,
bool bAnyClass, mxClassID &classID )
{
int ndim = 2;
int dims[2];
dims[0] = rows;
dims[1] = cols;
verifyArray( mxArr, dims, ndim, bAllowEmpty, bAnyClass, classID );
rows = dims[0];
cols = dims[1];
}
//------------------------------------------------------------------------------
// verifyVector
//
void verifyVector( mxArray *mxArr, int &num, VecType &type, bool bAllowEmpty,
bool bAnyClass, mxClassID &classID )
{
bool bEmpty = mxIsEmpty( mxArr );
if( !bAllowEmpty && bEmpty )
{
throw_error( "Vector should be not empty." );
return;
}
if( bEmpty )
{
if( num < 0 )
{
num = 0;
}
return;
}
mxClassID _classID = classID;
classID = mxGetClassID( mxArr );
if( !bAnyClass && classID != _classID )
{
throw_error( "Incorrect vector type." );
return;
}
const int *dims = mxGetDimensions( mxArr );
if( type == any )
{
type = ( dims[0] > dims[1] ) ? col : row;
}
int _num = num;
num = mxGetNumberOfElements( mxArr );
if( _num > 0 && _num != num )
{
std::ostringstream ostr;
ostr << "Incorrect vector size. " <<
"Vector should have " << _num << " element(s).";
throw_error( ostr.str() );
return;
}
if( mxGetNumberOfDimensions( mxArr ) != 2 ||
( type == row && dims[0] != 1 ) ||
( type == col && dims[1] != 1 ) )
{
std::ostringstream ostr;
ostr << "Should be " << (( type == row ) ? "row" : "column") <<
" vector.";
throw_error( ostr.str() );
return;
}
}
//------------------------------------------------------------------------------
// verifySeq
//
void verifySeq( mxArray *mxArr, int maxIndex, int index,
mxClassID &dataClass, void *&dataPtr, int &dataNum,
CvRect &rect, int &type,
int &h_prev, int &h_next, int &v_prev, int &v_next )
{
if( index >= maxIndex || index < 0 )
{
throw_error( "Invalid index." );
return;
}
mxArray *mxFdata = mxGetField( mxArr, index, "data" );
mxArray *mxFrect = mxGetField( mxArr, index, "rect" );
mxArray *mxFtype = mxGetField( mxArr, index, "type" );
mxArray *mxFh_prev = mxGetField( mxArr, index, "h_prev" );
mxArray *mxFh_next = mxGetField( mxArr, index, "h_next" );
mxArray *mxFv_prev = mxGetField( mxArr, index, "v_prev" );
mxArray *mxFv_next = mxGetField( mxArr, index, "v_next" );
/* data */
if( !mxFdata || mxIsEmpty( mxFdata ) ||
mxGetNumberOfDimensions( mxFdata ) != 2 ||
!mxIsNumeric( mxFdata ) )
{
std::ostringstream ostr;
ostr << "Invalid 'data' field in struct number " << index
<< ". It should be n by 2 numeric array.";
throw_error( ostr.str() );
return;
}
dataClass = mxGetClassID( mxFdata );
dataPtr = (void *)mxGetData( mxFdata );
dataNum = mxGetM( mxFdata );
/* rect */
if( !mxFrect || mxIsEmpty( mxFrect ) ||
mxGetNumberOfDimensions( mxFrect ) != 2 ||
!mxIsNumeric( mxFrect ) || mxGetM( mxFrect ) != 1 ||
mxGetN( mxFrect ) != 4 )
{
std::ostringstream ostr;
ostr << "Invalid 'rect' field in struct number " << index
<< ". It should be 1 by 4 numeric array.";
throw_error( ostr.str() );
return;
}
MXTYPE_DATAPTR( mxGetClassID( mxFrect ), ;, rectData, mxGetData( mxFrect );
castCopy( rectData, (int *)(&rect), 1, 4, 1, 1, 1, 1 ); );
/* type */
if( !mxFtype || mxIsEmpty( mxFtype ) ||
mxGetNumberOfDimensions( mxFtype ) != 2 ||
!mxIsNumeric( mxFtype ) || mxGetM( mxFtype ) != 1 ||
mxGetN( mxFtype ) != 1 )
{
std::ostringstream ostr;
ostr << "Invalid 'type' field in struct number " << index
<< ". It should be 1 by 1 numeric array.";
throw_error( ostr.str() );
return;
}
MXTYPE_DATAPTR( mxGetClassID( mxFtype ), ;, typeData, mxGetData( mxFtype );
castCopy( typeData, (int *)(&type), 1, 1, 1, 1, 1, 1 ); );
/* h_prev */
if( !mxFh_prev || mxIsEmpty( mxFh_prev ) ||
mxGetNumberOfDimensions( mxFh_prev ) != 2 ||
!mxIsNumeric( mxFh_prev ) || mxGetM( mxFh_prev ) != 1 ||
mxGetN( mxFh_prev ) != 1 )
{
std::ostringstream ostr;
ostr << "Invalid 'h_prev' field in struct number " << index
<< ". It should be 1 by 1 numeric array.";
throw_error( ostr.str() );
return;
}
MXTYPE_DATAPTR( mxGetClassID( mxFh_prev ), ;,
h_prevData, mxGetData( mxFh_prev );
castCopy( h_prevData, (int *)(&h_prev), 1, 1, 1, 1, 1, 1 ); );
if( h_prev > maxIndex || h_prev < 0 )
{
std::ostringstream ostr;
ostr << "Invalid 'h_prev' value in struct number " << index
<< ".";
throw_error( ostr.str() );
return;
}
/* h_next */
if( !mxFh_next || mxIsEmpty( mxFh_next ) ||
mxGetNumberOfDimensions( mxFh_next ) != 2 ||
!mxIsNumeric( mxFh_next ) || mxGetM( mxFh_next ) != 1 ||
mxGetN( mxFh_next ) != 1 )
{
std::ostringstream ostr;
ostr << "Invalid 'h_next' field in struct number " << index
<< ". It should be 1 by 1 numeric array.";
throw_error( ostr.str() );
return;
}
MXTYPE_DATAPTR( mxGetClassID( mxFh_next ), ;,
h_nextData, mxGetData( mxFh_next );
castCopy( h_nextData, (int *)(&h_next), 1, 1, 1, 1, 1, 1 ); );
if( h_next > maxIndex || h_next < 0 )
{
std::ostringstream ostr;
ostr << "Invalid 'h_next' value in struct number " << index
<< ".";
throw_error( ostr.str() );
return;
}
/* v_prev */
if( !mxFv_prev || mxIsEmpty( mxFv_prev ) ||
mxGetNumberOfDimensions( mxFv_prev ) != 2 ||
!mxIsNumeric( mxFv_prev ) || mxGetM( mxFv_prev ) != 1 ||
mxGetN( mxFv_prev ) != 1 )
{
std::ostringstream ostr;
ostr << "Invalid 'v_prev' field in struct number " << index
<< ". It should be 1 by 1 numeric array.";
throw_error( ostr.str() );
return;
}
MXTYPE_DATAPTR( mxGetClassID( mxFv_prev ), ;,
v_prevData, mxGetData( mxFv_prev );
castCopy( v_prevData, (int *)(&v_prev), 1, 1, 1, 1, 1, 1 ); );
if( v_prev > maxIndex || v_prev < 0 )
{
std::ostringstream ostr;
ostr << "Invalid 'v_prev' value in struct number " << index
<< ".";
throw_error( ostr.str() );
return;
}
/* v_next */
if( !mxFv_next || mxIsEmpty( mxFv_next ) ||
mxGetNumberOfDimensions( mxFv_next ) != 2 ||
!mxIsNumeric( mxFv_next ) || mxGetM( mxFv_next ) != 1 ||
mxGetN( mxFv_next ) != 1 )
{
std::ostringstream ostr;
ostr << "Invalid 'v_next' field in struct number " << index
<< ". It should be 1 by 1 numeric array.";
throw_error( ostr.str() );
return;
}
MXTYPE_DATAPTR( mxGetClassID( mxFv_next ), ;,
v_nextData, mxGetData( mxFv_next );
castCopy( v_nextData, (int *)(&v_next), 1, 1, 1, 1, 1, 1 ); );
if( v_next > maxIndex || v_next < 0 )
{
std::ostringstream ostr;
ostr << "Invalid 'v_next' value in struct number " << index
<< ".";
throw_error( ostr.str() );
return;
}
}
| 28.708122 | 90 | 0.594377 | [
"vector"
] |
cf7e37991c425fd125a336f6088e021487599ff5 | 12,006 | cpp | C++ | Sandbox/Source/Source.cpp | TheFlyingPandaa/Leaf-Drop | 476a957fc2a958b2f741fb11b49d9e3172246524 | [
"Apache-2.0"
] | 1 | 2019-02-27T06:24:49.000Z | 2019-02-27T06:24:49.000Z | Sandbox/Source/Source.cpp | TheFlyingPandaa/Leaf-Drop | 476a957fc2a958b2f741fb11b49d9e3172246524 | [
"Apache-2.0"
] | null | null | null | Sandbox/Source/Source.cpp | TheFlyingPandaa/Leaf-Drop | 476a957fc2a958b2f741fb11b49d9e3172246524 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <Core.h>
#include "Leaf-Drop/Objects/Lights/DirectionalLight.h"
#include "Leaf-Drop/Objects/Lights/PointLight.h"
#include <algorithm>
#if _DEBUG
//Allocates memory to the console
void _alocConsole() {
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
AllocConsole();
FILE* fp;
freopen_s(&fp, "CONOUT$", "w", stdout);
}
#endif
void printFrameTime(double dt);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
srand(static_cast<UINT>(time(0)));
srand(0);
#if _DEBUG
_alocConsole();
#endif
Core * core = new Core();
Timer timer;
if (SUCCEEDED(core->Init(hInstance)))
{
Camera cam;
cam.CreateProjectionMatrix(0.01f, 500.0f);
cam.SetPosition(0, 0, 0);
cam.SetAsActiveCamera();
/*cam.SetPosition(0, -43.2657, 0);
cam.SetDirection(-0.685973, -0.00897975, -0.727571);*/
cam.SetPosition(-39.6452, -36.4232, 22.2482);
cam.SetDirection(0.995644, -0.0104395, -0.0926499);
cam.Update();
StaticMesh * m = new StaticMesh();
StaticMesh * m2 = new StaticMesh();
StaticMesh * bunny = new StaticMesh();
StaticMesh * sphere2 = new StaticMesh();
Texture * t = new Texture[3];
t[0].LoadTexture(L"..\\Assets\\Textures\\Magnus_Mirror\\Mirror_diffuseOriginal.bmp");
t[1].LoadTexture(L"..\\Assets\\Textures\\Magnus_Mirror\\Mirror_normal.bmp");
t[2].LoadTexture(L"..\\Assets\\Textures\\Magnus_Mirror\\Mirror_metallic.bmp");
Texture * t2 = new Texture[3];
t2[0].LoadTexture(L"..\\Assets\\Textures\\Magnus_Brick\\Brick_diffuseOriginal.bmp");
t2[1].LoadTexture(L"..\\Assets\\Textures\\Magnus_Brick\\Brick_normal.bmp");
t2[2].LoadTexture(L"..\\Assets\\Textures\\Magnus_Brick\\Brick_metallic.bmp");
Texture * bunnyTexture = new Texture[3];
bunnyTexture[0].LoadTexture(L"..\\Assets\\Textures\\BobTheBunny\\BobTheBunny_diffuseOriginal.bmp");
bunnyTexture[1].LoadTexture(L"..\\Assets\\Textures\\BobTheBunny\\BobTheBunny_normal.bmp");
bunnyTexture[2].LoadTexture(L"..\\Assets\\Textures\\BobTheBunny\\BobTheBunny_metallic.bmp");
Texture * Mirror2 = new Texture[3];
Mirror2[0].LoadTexture(L"..\\Assets\\Textures\\Mirror\\Mirror_diffuseOriginal.bmp");
Mirror2[1].LoadTexture(L"..\\Assets\\Textures\\Mirror\\Mirror_normal.bmp");
Mirror2[2].LoadTexture(L"..\\Assets\\Textures\\Mirror\\Mirror_metallic.bmp");
Texture * Roof = new Texture[3];
Roof[0].LoadTexture(L"..\\Assets\\Textures\\Roof\\Roof_diffuseOriginal.bmp");
Roof[1].LoadTexture(L"..\\Assets\\Textures\\Wall\\Wall_normal.bmp");
Roof[2].LoadTexture(L"..\\Assets\\Textures\\Wall\\Wall_metallic.bmp");
Texture * Wall = new Texture[3];
Wall[0].LoadTexture(L"..\\Assets\\Textures\\Wall\\Wall_diffuseOriginal.bmp");
Wall[1].LoadTexture(L"..\\Assets\\Textures\\Wall\\Wall_normal.bmp");
Wall[2].LoadTexture(L"..\\Assets\\Textures\\Wall\\Wall_metallic.bmp");
Texture * Wall2 = new Texture[3];
Wall2[0].LoadTexture(L"..\\Assets\\Textures\\Wall\\Wall2_diffuseOriginal.bmp");
Wall2[1].LoadTexture(L"..\\Assets\\Textures\\Wall\\Wall_normal.bmp");
Wall2[2].LoadTexture(L"..\\Assets\\Textures\\Wall\\Wall_metallic.bmp");
m->LoadMesh("..\\Assets\\Models\\Cube.fbx");
m2->LoadMesh("..\\Assets\\Models\\Sphere.fbx");
bunny->LoadMesh("..\\Assets\\Models\\BobTheBunny.fbx");
sphere2->LoadMesh("..\\Assets\\Models\\NormalSphere.fbx");
const UINT NUMBER_OF_DRAWABLES = 8;
const UINT NUMBER_OF_DYNAMIC_DRAWABLES = 4;
const UINT NUMBER_OF_LIGHTS = 200;
const UINT MAX_DISTANCE = 50;
const UINT MAX_LIGHT_DISTANCE = 50;
PointLight * pointLight = new PointLight[NUMBER_OF_LIGHTS];
for (int i = 0; i < NUMBER_OF_LIGHTS; i++)
{
float r = static_cast<float>(rand() % 10 + 90) / 100.0f;
float g = static_cast<float>(rand() % 10 + 90) / 100.0f;
float b = static_cast<float>(rand() % 10 + 90) / 100.0f;
pointLight[i].SetColor(r, g, b, 1);
pointLight[i].SetColor(1, 1, 1, 1);
pointLight[i].SetDropOff(1.0f);
pointLight[i].SetPow(2.0f);
float x = static_cast<float>(rand() % MAX_LIGHT_DISTANCE + 2) * (rand() % 2 ? 1 : -1);
float y = static_cast<float>(rand() % MAX_LIGHT_DISTANCE + 2) * (rand() % 2 ? 1 : -1);
float z = static_cast<float>(rand() % MAX_LIGHT_DISTANCE + 2) * (rand() % 2 ? 1 : -1);
float scl = static_cast<float>(rand() % 40 + 10 );
pointLight[i].SetPosition(x, y, z);
pointLight[i].SetIntensity(scl);
}
std::vector<Drawable> d(NUMBER_OF_DRAWABLES);
std::vector<Drawable> dynamicD(NUMBER_OF_DYNAMIC_DRAWABLES);
Drawable dynamicDrawable;
dynamicDrawable.SetTexture(&t[0]);
dynamicDrawable.SetNormal(&t[1]);
dynamicDrawable.SetMetallic(&t[2]);
dynamicDrawable.SetMesh(m);
dynamicDrawable.SetScale(10, 10, 10);
dynamicDrawable.SetRotation(0, DirectX::XMConvertToRadians(45), 0);
for (int i = 0; i < NUMBER_OF_DRAWABLES; i++)
{
d[i].SetTexture(&t[0]);
d[i].SetNormal(&t[0]);
d[i].SetMetallic(&t[0]);
d[i].SetAsStatic();
d[i].SetMesh(m);
float x = (FLOAT)(rand() % MAX_DISTANCE) * (rand() % 2 ? 1 : -1);
float y = (FLOAT)(rand() % MAX_DISTANCE) * (rand() % 2 ? 1 : -1);
float z = (FLOAT)(rand() % MAX_DISTANCE) * (rand() % 2 ? 1 : -1);
float scl = (FLOAT)(rand() % 3 + 1);
d[i].SetPosition(x, y, z);
d[i].SetScale(scl, scl, scl);
d[i].SetScale(1,1,1);
}
d[0].SetPosition(0, 0, 50);
d[0].SetScale(100, 100, 1);
d[0].SetTexture(&Wall[0]);
d[0].SetNormal(&Wall[1]);
d[0].SetMetallic(&Wall[2]);
d[1].SetPosition(0, 0, -50);
d[1].SetScale(100, 100, 1);
d[1].SetTexture(&Wall[0]);
d[1].SetNormal(&Wall[1]);
d[1].SetMetallic(&Wall[2]);
d[2].SetPosition(0,-50,0);
d[2].SetScale(100,1,100);
d[2].SetTexture(&Roof[0]);
d[2].SetNormal(&Roof[1]);
d[2].SetMetallic(&Roof[2]);
d[3].SetPosition(0, 50, 0);
d[3].SetScale(100, 1, 100);
d[3].SetTexture(&Roof[0]);
d[3].SetNormal(&Roof[1]);
d[3].SetMetallic(&Roof[2]);
d[4].SetPosition(50, 0, 0);
d[4].SetScale(1, 100, 100);
d[4].SetTexture(&Wall2[0]);
d[4].SetNormal(&Wall2[1]);
d[4].SetMetallic(&Wall2[2]);
d[5].SetPosition(-50, 0, 0);
d[5].SetScale(1, 100, 100);
d[5].SetTexture(&Wall2[0]);
d[5].SetNormal(&Wall2[1]);
d[5].SetMetallic(&Wall2[2]);
d[6].SetPosition(46, -40.0, -1.55212);
d[6].SetScale(1, 20, 20);
d[6].SetRotation(0, 0, DirectX::XMConvertToRadians(-20));
d[6].SetTexture(&t[0]);
d[6].SetNormal(&t[1]);
d[6].SetMetallic(&t[2]);
d[7].SetPosition(-45.9758, -40, 31.1561);
d[7].SetScale(20, 20, 20);
d[7].SetRotation(0, 0, 0);
d[7].SetTexture(&t[0]);
d[7].SetNormal(&t[1]);
d[7].SetMetallic(&t[2]);
dynamicD[0].SetPosition(-42, -52.5f, 42);
dynamicD[0].SetScale(100, 100, 100);
dynamicD[0].SetRotation(0, DirectX::XMConvertToRadians(180), 0);
dynamicD[0].SetMesh(bunny);
dynamicD[0].SetTexture(&bunnyTexture[0]);
dynamicD[0].SetNormal(&bunnyTexture[1]);
dynamicD[0].SetMetallic(&bunnyTexture[2]);
dynamicD[1].SetPosition(30, -30, 30);
dynamicD[1].SetRotation(0, DirectX::XMConvertToRadians(45), 0);
dynamicD[1].SetScale(35, 40, 1);
dynamicD[1].SetMesh(m);
dynamicD[1].SetTexture(&t[0]);
dynamicD[1].SetNormal(&t[1]);
dynamicD[1].SetMetallic(&t[2]);
dynamicD[2].SetPosition(40, -40.5f, -40);
dynamicD[2].SetScale(10, 10, 10);
dynamicD[2].SetMesh(m2);
dynamicD[2].SetTexture(&bunnyTexture[0]);
dynamicD[2].SetNormal(&bunnyTexture[1]);
dynamicD[2].SetMetallic(&bunnyTexture[2]);
dynamicD[3].SetPosition(-45.9758, 20, -31.1561);
dynamicD[3].SetScale(10, 10, 10);
dynamicD[3].SetMesh(m);
dynamicD[3].SetTexture(&t2[0]);
dynamicD[3].SetNormal(&t2[1]);
dynamicD[3].SetMetallic(&t2[2]);
float rot = 0;
timer.Start();
Window * wnd = Window::GetInstance();
POINT mpStart = wnd->GetWindowSize();
DirectX::XMFLOAT2 mousePosLastFrame = { (float)mpStart.x, (float)mpStart.y };
mousePosLastFrame.x /= 2;
mousePosLastFrame.y /= 2;
wnd->ResetMouse();
DirectionalLight light;
light.SetDirection(1, -1, 0);
light.SetIntensity(0.5f);
for (int i = 0; i < NUMBER_OF_DRAWABLES; i++)
{
d[i].Update();
}
for (UINT i = 0; i < NUMBER_OF_DYNAMIC_DRAWABLES; i++)
{
dynamicD[i].Update();
}
while (core->Running())
{
POINT mp = wnd->GetMousePosition();
DirectX::XMFLOAT2 mouseThisFrame = { (float)mp.x, (float)mp.y };
static const float MOVE_SPEED = 5.0f;
static const float SPRINT_SPEED = 50.0f;
static const float MOUSE_SENSITIVITY = 0.05f;
const double dt = timer.Stop();
printFrameTime(dt);
DirectX::XMFLOAT3 moveDir(0.0f, 0.0f, 0.0f);
DirectX::XMFLOAT3 rotDir(0.0f, 0.0f, 0.0f);
if (Camera::GetActiveCamera() == &cam && false)
{
if (wnd->IsKeyPressed(Input::W))
moveDir.z += (MOVE_SPEED + SPRINT_SPEED * wnd->IsKeyPressed(Input::SHIFT));
if (wnd->IsKeyPressed(Input::A))
moveDir.x -= (MOVE_SPEED + SPRINT_SPEED * wnd->IsKeyPressed(Input::SHIFT));
if (wnd->IsKeyPressed(Input::S))
moveDir.z -= (MOVE_SPEED + SPRINT_SPEED * wnd->IsKeyPressed(Input::SHIFT));
if (wnd->IsKeyPressed(Input::D))
moveDir.x += (MOVE_SPEED + SPRINT_SPEED * wnd->IsKeyPressed(Input::SHIFT));
if (wnd->IsKeyPressed(Input::SPACE))
moveDir.y += (MOVE_SPEED + SPRINT_SPEED * wnd->IsKeyPressed(Input::SHIFT));
if (wnd->IsKeyPressed(Input::C))
moveDir.y -= (MOVE_SPEED + SPRINT_SPEED * wnd->IsKeyPressed(Input::SHIFT));
float deltaMouseX = mouseThisFrame.x - mousePosLastFrame.x;
float deltaMouseY = mouseThisFrame.y - mousePosLastFrame.y;
rotDir.y = DirectX::XMConvertToRadians(deltaMouseX) * MOUSE_SENSITIVITY;
rotDir.x = DirectX::XMConvertToRadians(deltaMouseY) * MOUSE_SENSITIVITY;
static bool moveCamera = true;
if (moveCamera)
{
cam.Rotate(rotDir);
wnd->ResetMouse();
}
if (wnd->IsKeyPressed(Input::Z))
moveCamera = true;
if (wnd->IsKeyPressed(Input::X))
moveCamera = false;
moveDir.x *= (FLOAT)dt;
moveDir.y *= (FLOAT)dt;
moveDir.z *= (FLOAT)dt;
cam.Translate(moveDir, false);
cam.Update();
}
if (wnd->IsKeyPressed(Input::ESCAPE))
wnd->Close();
static float mover = 0.0f;
static const float SPEED = 1.0f / 60.0f;
dynamicDrawable.SetPosition(-42, -40, -42);
dynamicDrawable.SetScale(15, 15, 15);
static float translate = 0.136f;
dynamicD[1].SetRotation(0, mover, 0.0f);
dynamicD[3].Translate(translate * 1.35f, -translate, translate);
dynamicD[3].SetRotation(0, 0, mover);
mover += SPEED;
if (mover >= DirectX::XM_2PI)
{
mover = 0;
translate *= -1.0f;
}
for (int i = 0; i < NUMBER_OF_DRAWABLES; i++)
{
d[i].Update();
d[i].Draw();
}
for (UINT i = 0; i < NUMBER_OF_DYNAMIC_DRAWABLES; i++)
{
dynamicD[i].Update();
dynamicD[i].Draw();
}
dynamicDrawable.Update();
dynamicDrawable.Draw();
for (UINT i = 0; i < NUMBER_OF_LIGHTS; i++)
{
pointLight[i].Queue();
}
if (FAILED(core->Flush()))
{
DEBUG::CreateError("LOL");
break;
}
}
core->ClearGPU();
m->Release();
delete m;
m2->Release();
delete m2;
bunny->Release();
delete bunny;
sphere2->Release();
delete sphere2;
for (UINT i = 0; i < 3; i++)
{
t[i].Release();
t2[i].Release();
bunnyTexture[i].Release();
Wall[i].Release();
Wall2[i].Release();
Roof[i].Release();
Mirror2[i].Release();
}
delete[] t;
delete[] t2;
delete[] bunnyTexture;
delete[] pointLight;
delete[] Wall;
delete[] Wall2;
delete[] Roof;
delete[] Mirror2;
}
core->Release();
delete core;
return 0;
}
void printFrameTime(double dt)
{
static int counter = 0;
static const int MAX_DATA = 64;
static double allTime = 0.0;
allTime += dt * 1000.0;
counter++;
static UINT64 counter2 = 0;
Window::GetInstance()->SetWindowTitle("Frame: " + std::to_string(counter2++));
if (counter >= MAX_DATA)
{
counter = 0;
allTime /= MAX_DATA;
//std::cout << allTime << std::endl;
allTime = 0.0;
}
} | 27.727483 | 101 | 0.642345 | [
"vector"
] |
cf804fe832790dc25918f77001455228e79b933c | 7,142 | cpp | C++ | HelperFunctions/getVkBufferImageCopyCollection.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | HelperFunctions/getVkBufferImageCopyCollection.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | HelperFunctions/getVkBufferImageCopyCollection.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2020 Douglas Kaip
*
* 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 "JVulkanHelperFunctions.hh"
#include "slf4j.hh"
namespace jvulkan
{
void getVkBufferImageCopy(
JNIEnv *env,
const jobject jVkBufferImageCopyObject,
VkBufferImageCopy *vkBufferImageCopy,
std::vector<void *> *memoryToFree)
{
jclass vkBufferImageCopyClass = env->GetObjectClass(jVkBufferImageCopyObject);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
jmethodID methodId = env->GetMethodID(vkBufferImageCopyClass, "getBufferOffset", "()J");
if (env->ExceptionOccurred())
{
return;
}
jlong bufferOffset = env->CallLongMethod(jVkBufferImageCopyObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkBufferImageCopyClass, "getBufferRowLength", "()I");
if (env->ExceptionOccurred())
{
return;
}
jint bufferRowLength = env->CallIntMethod(jVkBufferImageCopyObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkBufferImageCopyClass, "getBufferImageHeight", "()I");
if (env->ExceptionOccurred())
{
return;
}
jint bufferImageHeight = env->CallIntMethod(jVkBufferImageCopyObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkBufferImageCopyClass, "getImageSubresource", "()Lcom/CIMthetics/jvulkan/VulkanCore/Structures/VkImageSubresourceLayers;");
if (env->ExceptionOccurred())
{
return;
}
jobject jVkImageSubresourceLayersObject = env->CallObjectMethod(jVkBufferImageCopyObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
getVkImageSubresourceLayers(
env,
jVkImageSubresourceLayersObject,
&(vkBufferImageCopy->imageSubresource),
memoryToFree);
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkBufferImageCopyClass, "getImageOffset", "()Lcom/CIMthetics/jvulkan/VulkanCore/Structures/VkOffset3D;");
if (env->ExceptionOccurred())
{
return;
}
jobject jVkOffset3DObject = env->CallObjectMethod(jVkBufferImageCopyObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
getVkOffset3D(
env,
jVkOffset3DObject,
&(vkBufferImageCopy->imageOffset),
memoryToFree);
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkBufferImageCopyClass, "getImageExtent", "()Lcom/CIMthetics/jvulkan/VulkanCore/Structures/VkExtent3D;");
if (env->ExceptionOccurred())
{
return;
}
jobject jVkExtent3DObject = env->CallObjectMethod(jVkBufferImageCopyObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
getVkExtent3D(
env,
jVkExtent3DObject,
&(vkBufferImageCopy->imageExtent),
memoryToFree);
vkBufferImageCopy->bufferOffset = bufferOffset;
vkBufferImageCopy->bufferRowLength = bufferRowLength;
vkBufferImageCopy->bufferImageHeight = bufferImageHeight;
}
void getVkBufferImageCopyCollection(
JNIEnv *env,
const jobject jVkBufferImageCopyCollectionObject,
VkBufferImageCopy **vkBufferImageCopies,
int *numberOfVkBufferImageCopies,
std::vector<void *> *memoryToFree)
{
jclass vkBufferImageCopyCollectionClass = env->GetObjectClass(jVkBufferImageCopyCollectionObject);
if (env->ExceptionOccurred())
{
return;
}
jmethodID methodId = env->GetMethodID(vkBufferImageCopyCollectionClass, "size", "()I");
if (env->ExceptionOccurred())
{
return;
}
jint numberOfElements = env->CallIntMethod(jVkBufferImageCopyCollectionObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
*numberOfVkBufferImageCopies = numberOfElements;
*vkBufferImageCopies = (VkBufferImageCopy *)calloc(numberOfElements, sizeof(VkBufferImageCopy));
memoryToFree->push_back(*vkBufferImageCopies);
jmethodID iteratorMethodId = env->GetMethodID(vkBufferImageCopyCollectionClass, "iterator", "()Ljava/util/Iterator;");
if (env->ExceptionOccurred())
{
return;
}
jobject iteratorObject = env->CallObjectMethod(jVkBufferImageCopyCollectionObject, iteratorMethodId);
if (env->ExceptionOccurred())
{
return;
}
jclass iteratorClass = env->GetObjectClass(iteratorObject);
if (env->ExceptionOccurred())
{
return;
}
jmethodID hasNextMethodId = env->GetMethodID(iteratorClass, "hasNext", "()Z");
if (env->ExceptionOccurred())
{
return;
}
jmethodID nextMethod = env->GetMethodID(iteratorClass, "next", "()Ljava/lang/Object;");
if (env->ExceptionOccurred())
{
return;
}
int i = 0;
do
{
jboolean hasNext = env->CallBooleanMethod(iteratorObject, hasNextMethodId);
if (env->ExceptionOccurred())
{
break;
}
if (hasNext == false)
{
break;
}
jobject jVkBufferImageCopyObject = env->CallObjectMethod(iteratorObject, nextMethod);
if (env->ExceptionOccurred())
{
break;
}
getVkBufferImageCopy(
env,
jVkBufferImageCopyObject,
&((*vkBufferImageCopies)[i]),
memoryToFree);
i++;
} while(true);
}
}
| 31.60177 | 160 | 0.547606 | [
"object",
"vector"
] |
cf94a89b4a44a23aa2402d9bc12dc051ddb55f58 | 16,290 | cc | C++ | riscos/libs/tbx/tbx/view/listview.cc | riscoscloverleaf/chatcube | a7184ef76108f90a74a88d3183a3d21c1249a0f5 | [
"MIT"
] | null | null | null | riscos/libs/tbx/tbx/view/listview.cc | riscoscloverleaf/chatcube | a7184ef76108f90a74a88d3183a3d21c1249a0f5 | [
"MIT"
] | null | null | null | riscos/libs/tbx/tbx/view/listview.cc | riscoscloverleaf/chatcube | a7184ef76108f90a74a88d3183a3d21c1249a0f5 | [
"MIT"
] | null | null | null | /*
* tbx RISC OS toolbox library
*
* Copyright (C) 2010 Alan Buckley 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.
*/
/*
* listview.cc
*
* Created on: 25 Mar 2010
* Author: alanb
*/
#include "listview.h"
#include "../osgraphics.h"
#include <algorithm>
namespace tbx {
namespace view {
/**
* Constructor
*/
ListView::ListView(tbx::Window window, ItemRenderer *item_renderer)
: ItemView(window),
_item_renderer(item_renderer),
_height(0),
_width(0)
{
}
/**
* Destructor
*/
ListView::~ListView()
{
}
/**
* Change the item renderer.
*
* If there are items already defined it will
* resize or refresh the view depending on if
* auto_size is set.
*/
void ListView::item_renderer(ItemRenderer *ir)
{
_item_renderer = ir;
if (_count)
{
if (_flags & AUTO_SIZE)
{
// Force resize
auto_size(false);
auto_size(true);
} else
{
refresh();
}
}
}
/**
* Change the row height.
*
* If the row height is 0. It will take the height from
* the first item in the list. This is how the view
* starts up.
*/
void ListView::row_height(unsigned int height)
{
if (height == 0 && _count && _item_renderer != 0)
{
height = _item_renderer->height(0);
}
if (height != _height)
{
_height = height;
if (_count && updates_enabled())
{
update_window_extent();
refresh();
}
}
}
/**
* Turn on or off auto sizing.
*
* When auto sizing is on the item width is checked whenever an
* item is added, changed or removed.
*
* To prevent a scan of the whole list on removal call the
* removing method before actually doing a removal.
*/
void ListView::auto_size(bool on)
{
if (on)
{
if ((_flags & AUTO_SIZE)==0)
{
size_to_width();
_flags |= AUTO_SIZE;
}
} else
{
_flags &= ~AUTO_SIZE;
}
}
/**
* Set the width.
*
* Setting the width automatically turns of auto sizing
*/
void ListView::width(unsigned int width)
{
_flags &= ~AUTO_SIZE;
if (width != _width)
{
_width = width;
if (_count && updates_enabled())
{
update_window_extent();
}
}
}
/**
* Measure the maximum width for a range of rows.
*
* Measures from first to end-1
*
*@param from first row to measure (inclusive)
*@param end last row to measure (not inclusive)
*/
unsigned int ListView::max_width(unsigned int from, unsigned int end)
{
unsigned int max_width = 0;
for (unsigned int row = 0; row < end; row++)
{
unsigned int item_width = _item_renderer->width(row);
if (item_width > max_width) max_width = item_width;
}
return max_width;
}
/**
* Check if width has been reduced to less then _width
*
* Measures from first to end-1
*
*@param from first row to measure (inclusive)
*@param end last row to measure (not inclusive)
*@return maximum width in the range.
*/
unsigned int ListView::check_width(unsigned int from, unsigned int end)
{
unsigned int max_width = 0;
for (unsigned int row = 0; row < end; row++)
{
unsigned int item_width = _item_renderer->width(row);
if (item_width > max_width) max_width = item_width;
if (item_width == _width) break; // Don't need to do any more
}
return max_width;
}
/**
* Size width to match content.
* Does nothing if there is no content
*
* Using this function to set the width automatically turns off auto sizing
*/
void ListView::size_to_width(unsigned int min/* = 0*/, unsigned int max /*= 0xFFFFFFFF*/)
{
_flags &= ~AUTO_SIZE;
if (_item_renderer == 0 || _count == 0) return;
unsigned int new_width = max_width(0, _count);
if (new_width < min) new_width = min;
if (new_width > max) new_width = max;
if (new_width != _width)
{
width(new_width);
}
}
/**
* Redraw the List view
*/
void ListView::redraw(const tbx::RedrawEvent & event)
{
BBox work_clip = event.visible_area().work(event.clip());
unsigned int first_row = (-work_clip.max.y - _margin.top) / _height;
unsigned int last_row = (-work_clip.min.y - _margin.top) / _height;
if (first_row < 0) first_row = 0;
if (last_row < 0) return; // Nothing to draw
if (first_row >= _count) return; // Nothing to draw
if (last_row >= _count) last_row = _count - 1;
ItemRenderer::Info cell_info(event);
cell_info.bounds.max.y = -first_row * _height - _margin.top;
cell_info.screen.y = event.visible_area().screen_y(cell_info.bounds.max.y);
cell_info.screen.x = event.visible_area().screen_x(_margin.left);
cell_info.bounds.min.x = _margin.left;
cell_info.bounds.max.x = _margin.left + _width;
for (unsigned int row = first_row; row <= last_row; row++)
{
cell_info.bounds.min.y = cell_info.bounds.max.y - _height;
cell_info.screen.y -= _height;
cell_info.index = row;
cell_info.selected = (_selection != 0 && _selection->selected(row));
if (cell_info.selected)
{
// Fill background with selected colour
OSGraphics g;
g.foreground(Colour::black);
g.fill_rectangle(cell_info.screen.x, cell_info.screen.y,
cell_info.screen.x + _width -1,
cell_info.screen.y + _height - 1);
}
_item_renderer->render(cell_info);
cell_info.bounds.max.y = cell_info.bounds.min.y;
}
}
/**
* Update the Window extent after a change in size.
*/
void ListView::update_window_extent()
{
if (!updates_enabled()) return;
int width = _width + _margin.left + _margin.right;
int height = _count * _height + _margin.top + _margin.bottom;
WindowState state;
_window.get_state(state);
if (width < state.visible_area().bounds().width())
width = state.visible_area().bounds().width();
if (height < state.visible_area().bounds().height())
height = state.visible_area().bounds().height();
BBox extent(0,-height, width, 0);
_window.extent(extent);
}
/**
* Refresh the whole report view.
*
* It should also be called if all the data changes.
*/
void ListView::refresh()
{
if (updates_enabled())
{
BBox all(_margin.left, -_margin.top - _count * _height,
_margin.left + _width, -_margin.top);
_window.force_redraw(all);
}
}
/**
* Inform the view that items have been inserted.
*
* @param where location for insertion
* @param how_many number of items inserted
*/
void ListView::inserted(unsigned int where, unsigned int how_many)
{
if (_item_renderer != 0)
{
// Automatically set the height if not set
if (_height == 0) _height = _item_renderer->height(where);
if ((_flags & AUTO_SIZE))
{
// Auto size
unsigned int width = max_width(where, where + how_many);
if (width > _width) _width = width;
}
}
_count += how_many;
if (updates_enabled()) update_window_extent();
if (_selection) _selection->inserted(where, how_many);
//TODO: Use window block copy to update
if (updates_enabled())
{
BBox dirty(_margin.left,
- _count * _height - _margin.top,
_width + _margin.left,
- where * _height - _margin.top);
_window.force_redraw(dirty);
}
}
/**
* Inform the view that items are about to be removed.
*
* This call is optional, but it stops the need for a full
* scan every time something is removed when auto size is on.
*
* @param where location items will be removed from
* @param how_many number of items that will be removed
*/
void ListView::removing(unsigned int where, unsigned int how_many)
{
_flags |= AUTO_SIZE_CHECKED;
if (_flags & AUTO_SIZE)
{
for (unsigned int row = where; row < where + how_many; row++)
{
unsigned int item_width = _item_renderer->width(row);
if (item_width == _width)
{
_flags |= WANT_AUTO_SIZE;
break;
}
}
}
}
/**
* Inform the view that items have been removed.
*
* @param where location for removal
* @param how_many number of items removed
*/
void ListView::removed(unsigned int where, unsigned int how_many)
{
if ((_flags & AUTO_SIZE) && !(_flags & AUTO_SIZE_CHECKED))
{
_flags |= WANT_AUTO_SIZE;
}
_flags &= ~ AUTO_SIZE_CHECKED;
_count -= how_many;
unsigned int old_width = _width;
if (_flags & WANT_AUTO_SIZE)
{
_flags &= ~WANT_AUTO_SIZE;
if (_count == 0) _width = 0;
else _width = check_width(0, _count);
}
//TODO: Use window block copy to update
BBox dirty(_margin.left,
-_count * _height - _margin.top,
old_width + _margin.left,
-where * _height - _margin.top);
if (_selection) _selection->removed(where, how_many);
if (updates_enabled())
{
update_window_extent();
_window.force_redraw(dirty);
}
}
/**
* Inform the view that items are about to be changed
*
* This call is optional, but it stops the need for a full
* scan every time something an item is changed when auto size is on.
*
* @param where location items will be changed from
* @param how_many number of items that will be changed
*/
void ListView::changing(unsigned int where, unsigned int how_many)
{
_flags |= AUTO_SIZE_CHECKED;
if (_flags & AUTO_SIZE)
{
for (unsigned int row = where; row < where + how_many; row++)
{
unsigned int item_width = _item_renderer->width(row);
if (item_width == _width)
{
_flags |= WANT_AUTO_SIZE;
break;
}
}
}
}
/**
* Inform the view that items have been changed.
*
* @param where location of first change
* @param how_many number of items changed
*/
void ListView::changed(unsigned int where, unsigned int how_many)
{
bool may_shrink = true;
if ((_flags & AUTO_SIZE))
{
if (_flags & AUTO_SIZE_CHECKED)
{
if ((_flags & WANT_AUTO_SIZE) == 0) may_shrink = false;
}
unsigned int new_width = (may_shrink) ? 0 : _width;
for (unsigned int row = where; row < where + how_many; row++)
{
unsigned int item_width = _item_renderer->width(row);
if (item_width > new_width) new_width = item_width;
}
if (new_width < _width)
{
unsigned int check;
if (where > 0)
{
check = check_width(0, where);
if (check > new_width) new_width = check;
}
if (new_width != _width && where+how_many <=_count)
{
check = check_width(where+how_many-1, _count);
if (check > new_width) new_width = check;
}
}
if (new_width != _width)
{
width(new_width);
_flags |= AUTO_SIZE;
}
}
_flags &= ~(AUTO_SIZE_CHECKED | WANT_AUTO_SIZE);
if (updates_enabled())
{
int last_row = where + how_many;
BBox dirty(_margin.left,
-last_row * _height - _margin.top,
_width + _margin.left,
-where * _height - _margin.top);
_window.force_redraw(dirty);
}
}
/**
* Whole view has been cleared
*/
void ListView::cleared()
{
if (_count)
{
refresh();
_count = 0;
if (_flags & AUTO_SIZE) _width = 0;
if (_selection) _selection->clear();
if (updates_enabled())
{
update_window_extent();
WindowState state;
_window.get_state(state);
Point &scroll = state.visible_area().scroll();
if (scroll.x != 0 || scroll.y != 0)
{
scroll.x = 0;
scroll.y = 0;
_window.open_window(state);
}
}
}
}
/**
* Return the index for inserting an item from a screen
* point.
*/
unsigned int ListView::insert_index(const Point &scr_pt) const
{
WindowState state;
_window.get_state(state);
int work_y = state.visible_area().work_y(scr_pt.y) + _margin.top;
unsigned int row = (-work_y + _height/2) / _height;
if (row < 0) row = 0;
else if (row > _count) row = _count;
return row;
}
/**
* Return the index under the screen point, does not check
* if it hits content of the item renderer.
*/
unsigned int ListView::screen_index(const Point &scr_pt) const
{
WindowState state;
_window.get_state(state);
unsigned int row;
Point work_pt = state.visible_area().work(scr_pt);
if (work_pt.x < _margin.left || work_pt.x > _margin.left + (int)_width
|| work_pt.y > -_margin.top)
{
row = NO_INDEX;
} else
{
row = (-work_pt.y - _margin.top) / _height;
if (row >= _count) row = NO_INDEX;
}
return row;
}
/**
* Return the index under the screen point, checks
* if it hits content of the item renderer.
*
* Returns: NO_INDEX if doesn't hit content
*/
unsigned int ListView::hit_test(const Point &scr_pt) const
{
unsigned int index;
if (_item_renderer == 0 || _count == 0)
{
index = NO_INDEX;
} else
{
WindowState state;
_window.get_state(state);
Point work_pt = state.visible_area().work(scr_pt);
if (work_pt.x < _margin.left || work_pt.x > _margin.left + (int)_width
|| work_pt.y > -_margin.top)
{
index= NO_INDEX;
} else
{
index = (-work_pt.y - _margin.top) / _height;
if (index >= _count) index = NO_INDEX;
}
if (index != NO_INDEX)
{
BBox bounds;
get_bounds(bounds, index);
Point in_item;
in_item.x = work_pt.x - bounds.min.x;
in_item.y = work_pt.y - bounds.min.y;
if (!_item_renderer->hit_test(index, Size(_width, _height), in_item))
index = NO_INDEX;
}
}
return index;
}
/**
* Get bounding box of the given index in work area coordinates
*/
void ListView::get_bounds(BBox &bounds, unsigned int index) const
{
bounds.min.x = _margin.left;
bounds.max.x = bounds.min.x + _width;
bounds.max.y = -_margin.top - index * _height;
bounds.min.y = bounds.max.y - _height;
}
/**
* Get bounding box of the range of indices in work area coordinates
*/
void ListView::get_bounds(BBox &bounds, unsigned int first, unsigned int last) const
{
bounds.min.x = _margin.left;
bounds.max.x = bounds.min.x + _width;
bounds.max.y = -_margin.top - first * _height;
bounds.min.y = -_margin.top - (last+1) * _height;
}
/**
* Override this method to process selection by dragging.
*
* allow_drag_selection must be set for this to be called.
*
* @param drag_box Final bounding box of drag
* @param adjust adjust button was used for selection
*/
void ListView::process_drag_selection(const BBox &drag_box, bool adjust)
{
WindowState state;
_window.get_state(state);
Point first_pt(state.visible_area().work(drag_box.max));
Point last_pt(state.visible_area().work(drag_box.min));
if (first_pt.y < last_pt.y)
{
std::swap<Point>(first_pt, last_pt);
}
first_pt.y += _margin.top;
last_pt.y += _margin.top;
unsigned int first = -first_pt.y / _height;
if (first >= _count) return;
unsigned int last = -last_pt.y / _height;
if (last < 0) return;
if (last >= _count) last = _count - 1;
bool first_top = ((-first_pt.y - (_height * first)) <= _height/2);
bool last_top = ((-last_pt.y - (_height * last)) <= _height/2);
Size line_size(_width, _height);
if (!first_top)
{
first_pt.x -= _margin.left;
if (_item_renderer->hit_test(first, line_size, first_pt) == NO_INDEX) first++;
}
if (last_top)
{
last_pt.x -= _margin.left;
if (_item_renderer->hit_test(last, line_size, last_pt) == NO_INDEX) last--;
}
if (first <= last)
{
if (adjust) _selection->toggle(first, last);
else _selection->select(first, last);
}
}
// End of namespaces
}
}
| 24.570136 | 90 | 0.647452 | [
"render"
] |
cf99e43ec8863803c7216212a375fd70604b8877 | 1,254 | cc | C++ | jml/boosting/testing/orthogonal_test.cc | etnrlz/rtbkit | 0d9cd9e2ee2d7580a27453ad0a2d815410d87091 | [
"Apache-2.0"
] | 737 | 2015-01-04T01:40:46.000Z | 2022-03-07T10:09:23.000Z | jml/boosting/testing/orthogonal_test.cc | TuanTranEngineer/rtbkit | 502d06acc3f8d90438946b6ae742190f2f4b4fbb | [
"Apache-2.0"
] | 56 | 2015-01-05T16:01:03.000Z | 2020-06-22T19:02:37.000Z | jml/boosting/testing/orthogonal_test.cc | TuanTranEngineer/rtbkit | 502d06acc3f8d90438946b6ae742190f2f4b4fbb | [
"Apache-2.0"
] | 329 | 2015-01-01T06:54:27.000Z | 2022-02-12T22:21:02.000Z | /* orthogonal_test.cc
Jeremy Barnes, 22 March 2006
Copyright (c) Jeremy Barnes, 2006. All rights reserved.
$Source$
Test of the orthogonal array.
*/
#include <iostream>
#include "jml/boosting/config_impl.h"
#include <boost/multi_array.hpp>
#include "jml/stats/distribution.h"
using namespace std;
typedef boost::multi_array<unsigned char, 2> Array;
/** Calculate the Hamming distance between two points. */
int distance(const Array & array, int n1, int n2)
{
int result = 0;
int l = array.shape()[1];
for (unsigned i = 0; i < l; ++i)
result += (array[n1][i] != array[n2][i]);
return result;
}
void test(const Array & array, const distribution<float> & weights)
{
int n = array.shape()[0];
int l = array.shape()[1];
int min_dist = 1000;
for (unsigned n1 = 0; n1 < n; ++n1) {
for (unsigned n2 = 0; n2 < n; ++n2) {
int dist = distance(array, n1, n2);
if (dist < min_dist) min_dist = dist;
}
}
}
/** Algorithm to generate a maximally distant encoding to expand a set
of values into a higher coded representation.
We start with a part of the best hamming code.
*/
int main(int argc, char ** argv)
{
return 0;
}
| 21.254237 | 70 | 0.61244 | [
"shape"
] |
cfa03d0eafa893d23466b20148ff51900b20d2e6 | 1,399 | hh | C++ | src/designstate.hh | bert/arachne-pnr | c40fb2289952f4f120cc10a5a4c82a6fb88442dc | [
"MIT"
] | 299 | 2015-05-27T13:33:37.000Z | 2018-08-21T23:36:24.000Z | src/designstate.hh | bert/arachne-pnr | c40fb2289952f4f120cc10a5a4c82a6fb88442dc | [
"MIT"
] | 81 | 2015-05-31T16:34:33.000Z | 2018-07-24T14:03:35.000Z | src/designstate.hh | bert/arachne-pnr | c40fb2289952f4f120cc10a5a4c82a6fb88442dc | [
"MIT"
] | 69 | 2015-05-28T09:06:06.000Z | 2018-08-20T19:57:26.000Z | /* Copyright (C) 2015 Cotton Seed
This file is part of arachne-pnr. Arachne-pnr is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License version 2 as published by the Free Software
Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef PNR_DESIGNSTATE_HH
#define PNR_DESIGNSTATE_HH
#include "netlist.hh"
#include "chipdb.hh"
#include "pcf.hh"
#include "carry.hh"
#include "configuration.hh"
class DesignState
{
public:
const ChipDB *chipdb;
const Package &package;
Design *d;
Models models;
Model *top;
Constraints constraints;
CarryChains chains;
std::set<Instance *, IdLess> locked;
std::map<Instance *, int, IdLess> placement;
std::map<Instance *, uint8_t, IdLess> gb_inst_gc;
std::vector<Net *> cnet_net;
Configuration conf;
public:
DesignState(const ChipDB *chipdb_, const Package &package_, Design *d_);
bool is_dual_pll(Instance *inst) const;
std::vector<int> pll_out_io_cells(Instance *inst, int cell) const;
};
#endif
| 28.55102 | 74 | 0.731237 | [
"vector",
"model"
] |
cfa6e33fbf3072f017d24c98138edb3f24921733 | 1,616 | cpp | C++ | ACM-ICPC/12791.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | ACM-ICPC/12791.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | ACM-ICPC/12791.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int n, x, y;
vector<pair<int, string> > v;
vector<pair<int, string> > ans;
int main() {
v.push_back({ 1967, "DavidBowie" });
v.push_back({ 1969, "SpaceOddity" });
v.push_back({ 1970, "TheManWhoSoldTheWorld" });
v.push_back({ 1971, "HunkyDory" });
v.push_back({ 1972, "TheRiseAndFallOfZiggyStardustAndTheSpidersFromMars" });
v.push_back({ 1973, "AladdinSane" });
v.push_back({ 1973, "PinUps" });
v.push_back({ 1974, "DiamondDogs" });
v.push_back({ 1975, "YoungAmericans" });
v.push_back({ 1976, "StationToStation" });
v.push_back({ 1977, "Low" });
v.push_back({ 1977, "Heroes" });
v.push_back({ 1979, "Lodger" });
v.push_back({ 1980, "ScaryMonstersAndSuperCreeps" });
v.push_back({ 1983, "LetsDance" });
v.push_back({ 1984, "Tonight" });
v.push_back({ 1987, "NeverLetMeDown" });
v.push_back({ 1993, "BlackTieWhiteNoise" });
v.push_back({ 1995, "1.Outside" });
v.push_back({ 1997, "Earthling" });
v.push_back({ 1999, "Hours" });
v.push_back({ 2002, "Heathen" });
v.push_back({ 2003, "Reality" });
v.push_back({ 2013, "TheNextDay" });
v.push_back({ 2016, "BlackStar" });
cin >> n;
while (n--) {
cin >> x >> y;
for (int i = 0; i < v.size(); i++) {
if (x <= v[i].first && y >= v[i].first) {
ans.push_back(v[i]);
}
}
if (ans.size() == 0) {
cout << 0 << endl;
}
else {
cout << ans.size() << endl;
for (int i = 0; i < ans.size(); i++) {
cout << ans[i].first << " " << ans[i].second << endl;
}
}
ans.clear();
}
} | 26.933333 | 78 | 0.568688 | [
"vector"
] |
cfa8d397075732eb1198ffe7ef5b62f59667dc70 | 6,123 | cpp | C++ | apps/source_apps/AppList.cpp | Matt99-MK/SEth | 3fb36631bce88755e6e66e5b8425b694ef633eee | [
"MIT"
] | null | null | null | apps/source_apps/AppList.cpp | Matt99-MK/SEth | 3fb36631bce88755e6e66e5b8425b694ef633eee | [
"MIT"
] | null | null | null | apps/source_apps/AppList.cpp | Matt99-MK/SEth | 3fb36631bce88755e6e66e5b8425b694ef633eee | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
// Name: AppList.cpp
// Author: Mateusz Kosmala <mateuszkosmala1@gmail.com>
// Created: 2012-03-03
// Copyright: (c) 2020 by Mateusz Kosmala
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include<ColumnRender.h>
#include <AppList.h>
#include<MainXmlDocument.h>
#include<MainWindow.h>
#include<MainApp.h>
#include "DatabaseConnection.h"
#include<Poco/Tuple.h>
#include <wx/dcgraph.h>
#include <Poco/Nullable.h>
using namespace Poco::Data::Keywords;
using Poco::Data::Session;
using Poco::Data::Statement;
wxIMPLEMENT_DYNAMIC_CLASS(AppList, wxDataViewListCtrl);
BEGIN_EVENT_TABLE(AppList, wxDataViewListCtrl)
EVT_DATAVIEW_SELECTION_CHANGED(wxID_ANY, AppList::SelectionChanged)
END_EVENT_TABLE()
AppList::AppList(wxWindow* parent, wxWindowID id,
const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator)
: wxDataViewListCtrl(parent, id, pos, size, style, validator)
{
Last_focused = 0;
Row_counts = 0;
AppendBitmapColumn(wxString("BitMapColumn"), 0);
wxDataViewTextRenderer* const markupRenderer = new wxDataViewTextRenderer();
markupRenderer->EnableMarkup();
wxDataViewColumn* m_attributes = new wxDataViewColumn("attributes", markupRenderer, 1, 80, wxALIGN_LEFT);
AppendColumn(m_attributes);
SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));
SetRowHeight(60);
FrameOnActiveBack.LoadFile(wxString("C:\\Users\\metju\\Desktop\\Programming\\ConsoleApplications\\SEth\\SEth\\extern_files\\Icons\\color3.png"), wxBITMAP_TYPE_PNG);
FrameOnDisActiveBack.LoadFile(wxString("C:\\Users\\metju\\Desktop\\Programming\\ConsoleApplications\\SEth\\SEth\\extern_files\\Icons\\color1.png"), wxBITMAP_TYPE_PNG);
CircleOnActive.LoadFile(wxString("C:\\Users\\metju\\Desktop\\Programming\\ConsoleApplications\\SEth\\SEth\\extern_files\\Icons\\circle1.png"), wxBITMAP_TYPE_PNG);
wxImage Circle = FrameOnActiveBack.ConvertToImage();
Circle.Rescale(58, 58, wxIMAGE_QUALITY_HIGH);
FrameOnActiveBack = Circle;
this->model = nullptr;
wxImage Circle1 = FrameOnDisActiveBack.ConvertToImage();
Circle1.Rescale(58, 58, wxIMAGE_QUALITY_HIGH);
FrameOnDisActiveBack = Circle1;
connection = new DatabaseConnection("192.168.0.105");
//MainApp& reference = wxGetApp();
//users = reference.frame->usersstructure;
}
bool AppList::RecreateList(void)
{
int i = 0;
while (!(i >= this->Row_counts))
{
this->SetValue(wxVariant(PaintProfil(this->RowToItem(i), UserModelData::STATUS_DISACTIVE)), this->ItemToRow(this->RowToItem(i)), 0);
++i;
}
return true;
}
void AppList::SelectionChanged(wxDataViewEvent& event)
{
this->UnselectAll();
if (this->Last_focused != 0 || this->Last_focused == 0)
{
this->SetValue(wxVariant(PaintProfil(this->RowToItem(this->Last_focused), UserModelData::STATUS_DISACTIVE)), this->Last_focused, 0);
}
wxDataViewItem item;
if (item = event.GetItem())
{
actual_item = item;
this->Select(item);
this->Last_focused = this->ItemToRow(item);
this->SetValue(wxVariant(PaintProfil(item, UserModelData::STATUS_ACTIV)), this->Last_focused, 0);
event.Skip();
}
}
bool ImageToCircle(const wxImage& sourceImage,
const wxPoint& circleCenter, const wxCoord circleRadius,
wxImage& resultImage)
{
const wxRect circleRect(circleCenter.x - circleRadius, circleCenter.y - circleRadius,
2 * circleRadius, 2 * circleRadius);
wxRect resultRect(wxPoint(0, 0), sourceImage.GetSize());
resultRect.Intersect(circleRect);
wxBitmap maskBitmap(sourceImage.GetSize(), 1);
wxBitmap resultBitmap(sourceImage);
// Draw the mask to mask out the part of the resulting image
// outside the circle.
wxMemoryDC memoryDC(maskBitmap);
wxDCBrushChanger brushChanger(memoryDC, *wxWHITE_BRUSH);
wxDCPenChanger penChanger(memoryDC, *wxWHITE_PEN);
// black pixels will be fully transparent
memoryDC.SetBackground(*wxBLACK_BRUSH);
memoryDC.Clear();
memoryDC.SetBackground(wxNullBrush);
// white pixels inside the circle will remain unchanged
memoryDC.DrawCircle(circleCenter, circleRadius);
memoryDC.SelectObject(wxNullBitmap);
resultBitmap.SetMask(new wxMask(maskBitmap));
resultImage = resultBitmap.GetSubBitmap(resultRect).ConvertToImage();
return true;
}
wxBitmap AppList::PaintProfil(const wxDataViewItem& profil, const int& background)
{
model = (UserModelData*)(this->GetItemData(profil));
image.LoadFile(model->GetPath(), wxBITMAP_TYPE_JPEG);
image.Rescale(58, 58, wxIMAGE_QUALITY_HIGH);
wxBitmap Photo(image);
wxMemoryDC changer(Photo);
if(UserModelData::STATUS_ACTIV == background)
changer.DrawBitmap(FrameOnActiveBack, wxPoint(0, 0));
else
changer.DrawBitmap(FrameOnDisActiveBack, wxPoint(0, 0));
if (model->GetStatus() == UserModelData::STATUS_ACTIV)
changer.DrawBitmap(CircleOnActive, wxPoint(40, 40));
return Photo;
}
bool AppList::CreateAccount(UserModelData* usermodel) //INPUT -AND OUTPUT FULL DATE INFO OF USER
{
//#Getting information from database
Poco::Tuple<int, std::string, std::string, std::string, std::string> Data1 = connection->SelectOne(usermodel->GetID());
usermodel->SetName(Data1.get<1>());
usermodel->SetSurname(Data1.get<2>());
usermodel->SetIP(Data1.get<3>());
usermodel->SetCity(Data1.get<4>());
data.clear();
image.LoadFile(usermodel->GetPath(), wxBITMAP_TYPE_JPEG);
image.Rescale(58, 58);
wxBitmap Photo(image);
wxMemoryDC changer(Photo);
changer.DrawBitmap(FrameOnDisActiveBack, wxPoint(0, 0));
changer.DrawBitmap(CircleOnActive, wxPoint(40, 40));
wxString FinalColumnname("<span color=\"#000000\" size=\"100\">");
FinalColumnname.Append(usermodel->GetName());
FinalColumnname.Append(" ");
FinalColumnname.Append(usermodel->GetSurname());
FinalColumnname.Append("</span> ");
data.push_back(wxVariant(Photo));
data.push_back(wxVariant(FinalColumnname.c_str()));
AppendItem(data);
wxDataViewItem item = this->RowToItem(Row_counts);
this->SetItemData(item, (wxUIntPtr)usermodel);
++Row_counts;
return true;
}
AppList::~AppList()
{
delete connection;
} | 30.311881 | 168 | 0.73526 | [
"model"
] |
bbbca34b0f543cbb77222bbfe6cc89d33fc89bed | 49,963 | cpp | C++ | src/evaluate.cpp | moterink/Delocto | e421871de34f9a6d461e7e429e732a4d971a4ce1 | [
"MIT"
] | 13 | 2018-02-04T21:04:04.000Z | 2022-03-10T08:03:44.000Z | src/evaluate.cpp | moterink/Delocto | e421871de34f9a6d461e7e429e732a4d971a4ce1 | [
"MIT"
] | 3 | 2021-01-26T18:13:05.000Z | 2022-01-15T09:27:55.000Z | src/evaluate.cpp | moterink/Delocto | e421871de34f9a6d461e7e429e732a4d971a4ce1 | [
"MIT"
] | null | null | null | /*
Delocto Chess Engine
Copyright (c) 2018-2021 Moritz Terink
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 "evaluate.hpp"
#include "movegen.hpp"
#include "uci.hpp"
EvalTerm PieceSquareTable[2][6][64];
// Piece Square Table Values
// The values are mirrored for each color at execution time
static const EvalTerm PstValues[6][32] = {
// Pawns
{
V( 0, 0), V( 0, 0), V( 0, 0), V( 0, 0),
V(-1, -7), V( 2, -2), V( 7, 4), V( 9, 5),
V(-7, -3), V(-3, -4), V( 8, -2), V(11, 2),
V(-5, -1), V(-5, -3), V( 6, -5), V(14, -4),
V( 4, 4), V(-3, 4), V(-4, -1), V( 3, -6),
V(-5, 10), V(-7, 6), V(-3, 7), V( 3, 14),
V(-4, 2), V( 4, -2), V(-5, 8), V(-2, 11),
V( 0, 0), V( 0, 0), V( 0, 0), V( 0, 0)
},
// Knights
{
V(-79, -49), V(-45, -35), V(-38, -22), V(-37, -8),
V(-37, -33), V(-18, -26), V(-11, -7), V( -4, 3),
V(-30, -18), V( -9, -15), V( 2, -2), V( 9, 13),
V(-13, -17), V( 2, 0), V( 19, 6), V( 22, 16),
V(-14, -19), V( 6, -9), V( 20, 2), V( 24, 16),
V( -5, -24), V( 13, -18), V( 30, -8), V( 26, 9),
V(-31, -30), V(-10, -21), V( 3, -17), V( 17, 8),
V(-94, -46), V(-38, -42), V(-25, -25), V(-15, -8),
},
// Bishops
{
V(-21, -30), V(-2, -14), V(-5, -16), V(-13, -4),
V( -8, -18), V( 3, -6), V( 7, -7), V( 1, 0),
V( -4, -8), V(11, 0), V(-1, -3), V( 7, 6),
V( 0, -12), V( 4, -1), V(12, 0), V( 17, 8),
V( -3, -11), V(14, -3), V(11, -5), V( 13, 8),
V( -8, -12), V( 2, 1), V( 0, 0), V( 4, 8),
V(-10, -16), V(-9, -8), V( 5, -3), V( -3, 4),
V(-23, -24), V(-1, -19), V(-6, -18), V(-12, -9),
},
// Rooks
{
V(-11, -1), V( -6, -3), V(-3, -1), V( 1, -1),
V( -8, -5), V( -5, -3), V(-2, 0), V( 4, 0),
V(-10, 5), V( -3, -2), V( 1, 1), V( 0, -1),
V( -6, -2), V( -2, 1), V(-2, -4), V(-3, 4),
V(-11, -4), V( -6, 2), V( 0, 2), V( 3, -4),
V(-11, 1), V( -2, -1), V( 2, -5), V( 5, 3),
V( -4, 0), V( 3, 1), V( 5, 8), V( 6, -4),
V(-10, 6), V(-11, -3), V(-3, 6), V( 2, 3)
},
// Queens
{
V( 1, -32), V(-2, -27), V(-2, -22), V( 2, -12),
V(-1, -26), V( 2, -15), V( 4, -10), V( 6, -2),
V(-1, -18), V( 3, -8), V( 6, -4), V( 3, 1),
V( 2, -11), V( 2, -1), V( 4, 6), V( 4, 11),
V( 0, -14), V( 7, -3), V( 6, 4), V( 2, 10),
V(-2, -18), V( 5, -8), V( 3, -6), V( 4, 0),
V(-2, -23), V( 3, -13), V( 5, -11), V( 4, -4),
V(-1, -35), V(-1, -24), V( 0, -20), V(-1, -17)
},
// King
{
V(128, 0), V(153, 19), V(128, 38), V(89, 44),
V(130, 27), V(143, 46), V(112, 65), V(86, 62),
V( 93, 40), V(119, 65), V( 79, 77), V(56, 81),
V( 79, 48), V( 90, 71), V( 64, 79), V(51, 79),
V( 68, 46), V( 83, 78), V( 53, 92), V(32, 91),
V( 56, 41), V( 75, 77), V( 40, 82), V(17, 89),
V( 41, 19), V( 56, 46), V( 30, 60), V(12, 66),
V( 30, 2), V( 41, 28), V( 23, 35), V( 0, 35)
}
};
// Imbalance matrix
static const int Imbalance[2][6][6] = {
{
{ 42 },
{ 1, 1 },
{ 1, 7, -1 },
{ 0, 3, 0, 0 },
{ -1, 1, 3, -6 },
{ -5, 3, 4, -4, 0 }
},
{
{ 0 },
{ 1, 0 },
{ 0, 2, 0 },
{ 2, 2, 1, 0 },
{ 1, 1, 1, -1, 0 },
{ 3, 3, -1, 4, 9, 0 }
}
};
// Bitboards for outposts and boni for having minors on those squares or attacking them
static const Bitboard OutpostSquares[2] = { BB_RANK_3 | BB_RANK_4 | BB_RANK_5, BB_RANK_6 | BB_RANK_5 | BB_RANK_4 };
static const EvalTerm OutpostBonus[2] = { V(34, 11), V(17, 6) };
static const EvalTerm OutpostReachableBonus[2] = { V(17, 6), V( 8, 3) };
// Mobilty Values
// The more squares available to the piece, the higher the value
static const EvalTerm Mobility[4][28] = {
// Knights
{ V(-29, -35), V(-22, -25), V(-5, -12), V(-2, -6), V(2, 4), V(6, 8), V(9, 11), V(12, 14), V(14, 15) },
// Bishops
{ V(-21, -32), V(-9, -11), V(8, 1), V(12, 6), V(17, 11), V(21, 16), V(24, 23), V(29, 27), V(30, 31), V(32, 34), V(37, 36), V(38, 39), V(41, 40), V(44, 43) },
// Rooks
{ V(-27, -36), V(-13, -8), V(-7, 12), V(-4, 19), V(-3, 25), V(-1, 36), V(4, 45), V(8, 47), V(12, 53), V(12, 57), V(14, 63), V(15, 65), V(17, 67), V(20, 68), V(23, 68) },
// Queens
{ V(-25, -40), V(-8, -2), V(0, 6), V(1, 9), V(5, 18), V(8, 23), V(12, 28), V(15, 32), V(16, 34), V(19, 38), V(21, 42), V(24, 45), V(25, 46), V(27, 46), V(27, 49), V(28, 51), V(29, 52), V(30, 54), V(32, 56), V(34, 58), V(35, 62), V(39, 66), V(40, 70), V(40, 75), V(41, 79), V(43, 81), V(44, 83), V(45, 84) }
};
// Pawns
static const EvalTerm pawnDoubledPenalty = V(8, 14);
static const EvalTerm pawnIsolatedPenalty[2] = { V(11, 12), V(5, 7) };
static const EvalTerm pawnBackwardPenalty[2] = { V(17, 11), V(10, 5) };
static const EvalTerm pawnLeverBonus[8] = { V(0, 0), V(0, 0), V(0, 0), V(0, 0), V(7, 6), V(13, 13), V(0, 0), V(0, 0) };
static const int pawnConnectedBonus[8] = {
0, 3, 4, 6, 14, 23, 40, 0
};
static const EvalTerm pawnPhalanxBonus[2][8] = {
{ V(0, 0), V(8, 0), V(9, 0), V(16, 2), V(37, 18), V(57, 43), V(105, 105), V(0, 0) },
{ V(0, 0), V(4, 0), V(4, 0), V( 9, 1), V(18, 9), V(29, 21), V( 52, 52), V(0, 0) }
};
static const EvalTerm pawnSupportBonus = V(6, 2);
static const EvalTerm pawnPassedRankBonus[8] = { V(0, 0), V(4, 13), V(8, 15), V(7, 19), V(29, 34), V(79, 83), V(130, 122), V(0, 0) };
static const EvalTerm pawnPassedFilePenalty[8] = { V(0, 0), V(5, 4), V(10, 8), V(15, 12), V(15, 12), V(10, 8), V(5, 4), V(0, 0) };
static const EvalTerm pawnCandidateBonus[8] = { V(0, 0), V(0, 0), V(5, 15), V(10, 30), V(20, 45), V(30, 50), V(40, 60), V(0, 0) };
static const EvalTerm passedPawnNoAttacks = V(16, 18);
static const EvalTerm passedPawnSafePath = V( 9, 11);
static const EvalTerm passedPawnSafePush = V( 4, 6);
static const EvalTerm passedPawnBlockSqDefended = V( 2, 3);
// Bishops
static const EvalTerm bishopPawnsSameColorPenalty = V( 1, 3);
static const EvalTerm bishopCenterAlignBonus = V(21, 0);
// Minors
static const EvalTerm OutpostReachable[2] = { V(8, 0), V(4, 0) };
static const EvalTerm minorPawnShield = V(8, 1);
// Rooks
static const EvalTerm rookOpenFileBonus = V(19, 9);
static const EvalTerm rookSemiOpenFileBonus = V( 6, 4);
static const EvalTerm rookPawnAlignBonus = V( 3, 12);
static const EvalTerm rookTrappedPenalty = V(22, 2);
// Queens
static const EvalTerm UnsafeQueen = V(23, 7);
// King
static const unsigned queenSafeCheckWeight = 365;
static const unsigned rookSafeCheckWeight = 505;
static const unsigned bishopSafeCheckWeight = 300;
static const unsigned knightSafeCheckWeight = 370;
static const unsigned kingUnsafeCheck = 65;
static const unsigned kingRingAttackWeight = 32;
static const unsigned kingRingWeakSquareAttack = 86;
static const unsigned kingSliderBlocker = 65;
static const unsigned kingKnightDefender = 47;
static const unsigned kingBishopDefender = 18;
static const unsigned kingNoQueenAttacker = 410;
static const unsigned attackerWeight[5] = { 0, 36, 26, 21, 5 };
static const EvalTerm kingPawnlessFlank = V(8, 45);
static const EvalTerm kingFlankAttack = V(4, 0);
static const EvalTerm kingProtectorDistancePenalty = V(3, 4);
static const int kingPawnShelterValues[4][8] = {
{ -3, 38, 44, 27, 18, 8, 12, 0 },
{ -20, 29, 16, -23, -14, -5, -30, 0 },
{ -5, 35, 11, -1, 15, 1, -21, 0 },
{ -18, -6, -14, -24, -23, -31, -78, 0 }
};
static const int kingPawnStormValues[4][8] = {
{ 42, -134, -87, 44, 27, 21, 24, 0 },
{ 21, -8, 58, 22, 18, -3, 11, 0 },
{ 2, 24, 76, 17, 3, -7, -1, 0 },
{ -5, -7, 42, 7, 1, -3, -8, 0 }
};
// Threats
static const EvalTerm safePawnAttack = V(85, 46);
static const EvalTerm loosePawnWeight = V(16, 28);
static const EvalTerm HangingPiece = V(32, 17);
static const EvalTerm pawnPushThreat = V(20, 12);
static const EvalTerm pieceVulnerable = V( 6, 0);
static const EvalTerm mobilityRestriction = V( 3, 3);
static const EvalTerm KnightQueenAttackThreat = V( 8, 6);
static const EvalTerm BishopQueenAttackThreat = V(28, 8);
static const EvalTerm RookQueenAttackThreat = V(28, 8);
static const EvalTerm KingAttackThreat = V(11, 42);
static const EvalTerm minorAttackWeight[PIECETYPE_COUNT] = {
V(0, 15), V(19, 20), V(28, 22), V(34, 55), V(30, 59), V(0, 0)
};
static const EvalTerm rookAttackWeight[PIECETYPE_COUNT] = {
V(0, 11), V(18, 34), V(16, 32), V( 0, 17), V(25, 19), V(0, 0)
};
// Tempo Bonus
static const int tempoBonus = 12;
int KingDistance[64][64];
static int kingPawnShelter[8][8];
static int kingPawnStorm[8][8];
// Initialize king distance arrays
void init_king_distance() {
unsigned int findex, tindex;
for (findex = 0; findex < 64; findex++) {
for (tindex = 0; tindex < 64; tindex++) {
KingDistance[findex][tindex] = std::max(std::abs((int)rank(tindex) - (int)rank(findex)), std::abs((int)file(tindex) - (int)file(findex)));
}
}
}
// Initialize the piece square tables
void init_psqt() {
for (Piecetype pt = PAWN; pt < PIECE_NONE; pt++) {
for (unsigned sq = 0; sq < 32; sq++) {
const unsigned r = sq / 4;
const unsigned f = sq & 0x3;
EvalTerm value = PstValues[pt][sq];
PieceSquareTable[WHITE][pt][8 * r + f] = value;
PieceSquareTable[WHITE][pt][8 * r + (7 - f)] = value;
PieceSquareTable[BLACK][pt][8 * (7 - r) + f] = value;
PieceSquareTable[BLACK][pt][8 * (7 - r) + (7 - f)] = value;
}
}
}
// Initialize evaluation terms
void init_eval() {
// Mirror King Pawn Shelter Values
for (unsigned int f = 0; f < 4; f++) {
for (unsigned int r = 0; r < 8; r++) {
kingPawnShelter[f][r] = kingPawnShelterValues[f][r];
kingPawnShelter[7 - f][r] = kingPawnShelterValues[f][r];
}
}
// Mirror King Pawn Storm Values
for (unsigned int f = 0; f < 4; f++) {
for (unsigned int r = 0; r < 8; r++) {
kingPawnStorm[f][r] = kingPawnStormValues[f][r];
kingPawnStorm[7 - f][r] = kingPawnStormValues[f][r];
}
}
}
// Check if there is enough mating material on the board
bool Board::is_material_draw() const {
if (bbPieces[PAWN] || bbPieces[ROOK] || bbPieces[QUEEN]) {
return false;
} else if (popcount(bbColors[BOTH]) > 3) {
return false;
}
return true;
}
// Update attack info for calculating king safety
static void update_attack_info(Color color, Piecetype pt, Bitboard moves, EvalInfo& info) {
// Merge the piece moves into the piece attacks bitboard
info.pieceAttacks[color][pt] |= moves;
info.multiAttacks[color] |= info.colorAttacks[color] & moves; // Squares which are attacked more than once
info.colorAttacks[color] |= moves; // All attacks by a color on the board
// Detect attacks on the king area
const Bitboard kingAttacks = moves & info.kingRing[!color];
// If there is an attack, count the attacked squares and add the attacker weight
if (kingAttacks) {
info.kingAttackersWeight[!color] += attackerWeight[pt];
info.kingAttackersNum[!color]++;
info.kingRingAttacks[!color] += popcount(kingAttacks);
}
}
// Evaluate all knights on the board for a given color
static const EvalTerm evaluate_knights(const Board& board, const Color color, EvalInfo& info) {
EvalTerm value;
Bitboard knights = board.pieces(color, KNIGHT);
while (knights) {
Square sq = pop_lsb(knights);
Bitboard moves = gen_knight_moves(sq, 0);
if (board.get_king_blockers(color) & SQUARES[sq]) {
moves &= LineTable[sq][info.kingSq[color]];
}
// Bonus for outposts
Bitboard outposts = OutpostSquares[color] & info.pieceAttacks[color][PAWN] & ~info.pawnAttacksSpan[!color];
if (outposts & SQUARES[sq]) {
value += OutpostBonus[0];
} else if (outposts & moves & ~board.pieces(color)) {
value += OutpostReachableBonus[0];
}
// Bonus for being behind a friendly pawn
if (SQUARES[sq] & shift_down(board.pieces(PAWN), color)) {
value += minorPawnShield;
}
// Penalty for being far away from the king
value -= kingProtectorDistancePenalty * KingDistance[sq][info.kingSq[color]];
info.mobility[color] += Mobility[0][popcount(moves & info.mobilityArea[color])];
update_attack_info(color, KNIGHT, moves, info);
}
return value;
}
// Evaluate all bishops on the board for a given color
static const EvalTerm evaluate_bishops(const Board& board, const Color color, EvalInfo& info) {
EvalTerm value;
Bitboard bishops = board.pieces(color, BISHOP);
while (bishops) {
Square sq = pop_lsb(bishops);
// Exclude queen for xrays
Bitboard moves = gen_bishop_moves(sq, board.pieces(BOTH) & ~board.pieces(QUEEN), 0);
if (board.get_king_blockers(color) & SQUARES[sq]) {
moves &= LineTable[sq][info.kingSq[color]];
}
// Bonus for outposts
Bitboard outposts = OutpostSquares[color] & info.pieceAttacks[color][PAWN] & ~info.pawnAttacksSpan[!color];
if (outposts & SQUARES[sq]) {
value += OutpostBonus[1];
} else if (outposts & moves & ~board.pieces(color)) {
value += OutpostReachableBonus[1];
}
// Bonus for being behind a friendly pawn
if (SQUARES[sq] & shift_down(board.pieces(PAWN), color)) {
value += minorPawnShield;
}
// Penalty for having many pawns on the same square color as the bishop,
// since this restricts the mobility of the bishop
Bitboard pawnsOnSameColor = board.get_same_colored_squares(sq) & board.pieces(color, PAWN);
value -= bishopPawnsSameColorPenalty * popcount(pawnsOnSameColor) * (1 + popcount(info.blockedPawns[color] & CENTRAL_FILES));
// Bonus for being attacking central squares
if (popcount(gen_bishop_moves(sq, board.pieces(PAWN), 0) & CENTRAL_SQUARES) > 1) {
value += bishopCenterAlignBonus;
}
// Penalty for being far away from the king
value -= kingProtectorDistancePenalty * KingDistance[sq][info.kingSq[color]];
info.mobility[color] += Mobility[1][popcount(moves & info.mobilityArea[color])];
update_attack_info(color, BISHOP, moves, info);
}
return value;
}
// Evaluate all rooks on the board for a given color
static const EvalTerm evaluate_rooks(const Board& board, const Color color, EvalInfo& info) {
EvalTerm value;
Bitboard rooks = board.pieces(color, ROOK);
while (rooks) {
Square sq = pop_lsb(rooks);
// Exclude queens and rooks for xrays
Bitboard moves = gen_rook_moves(sq, board.pieces(BOTH) & ~board.majors(), 0);
if (board.get_king_blockers(color) & SQUARES[sq]) {
moves &= LineTable[sq][info.kingSq[color]];
}
const File f = file(sq);
const unsigned mob = popcount(moves & info.mobilityArea[color]);
// Bonus for being on an open file (no pawns)
if (!(FILES[f] & board.pieces(PAWN))) {
value += rookOpenFileBonus;
// Bonus for being on a semi-open file (no friendly pawns)
} else if (!(FILES[f] & board.pieces(color, PAWN))) {
value += rookSemiOpenFileBonus;
} else {
// Penalty for being in the corner and having low mobility
const int kingFile = file(info.kingSq[color]);
if (mob <= 3 && ((kingFile > 3) == (f > kingFile))) {
value -= rookTrappedPenalty;
}
}
// Bonus for aligning on file with enemy pawn
if (relative_rank(color, sq) >= 4) {
value += rookPawnAlignBonus * popcount(moves & board.pieces(!color, PAWN));
}
info.mobility[color] += Mobility[2][mob];
update_attack_info(color, ROOK, moves, info);
}
return value;
}
// Evaluate all queens on the board for a given color
static const EvalTerm evaluate_queens(const Board& board, const Color color, EvalInfo& info) {
EvalTerm value;
Bitboard queens = board.pieces(color, QUEEN);
while (queens) {
Square sq = pop_lsb(queens);
Bitboard moves = get_queen_moves(sq, board.pieces(BOTH), 0);
if (board.get_king_blockers(color) & SQUARES[sq]) {
moves &= LineTable[sq][info.kingSq[color]];
}
// Penalty for being in a discoverd attack by a slider
if (board.get_slider_blockers(board.pieces(!color, BISHOP) | board.pieces(!color, ROOK), sq)) {
value -= UnsafeQueen;
}
info.mobility[color] += Mobility[3][popcount(moves & info.mobilityArea[color])];
update_attack_info(color, QUEEN, moves, info);
}
return value;
}
// Evaluate all pawns on the board for a given color
static const EvalTerm evaluate_pawns(const Board& board, const Color color, EvalInfo& info) {
EvalTerm value;
const Bitboard ownPawns = board.pieces(color, PAWN);
const Bitboard oppPawns = board.pieces(!color, PAWN);
Bitboard pawns = ownPawns;
while (pawns) {
const Square sq = pop_lsb(pawns);
const File f = file(sq);
const Rank r = relative_rank(color, sq);
const Bitboard front = FrontFileMask[color][sq];
const Bitboard neighbours = ADJ_FILES[f] & ownPawns;
const Bitboard stoppers = PassedPawnMask[color][sq] & oppPawns;
const Bitboard lever = PawnAttacks[color][sq] & oppPawns;
info.pawnAttacksSpan[color] |= PawnAttacksSpan[color][sq];
const bool doubled = front & ownPawns; // Two friendly pawns on the same file
const bool opposed = front & oppPawns;
const bool isolated = !neighbours; // A pawn is isolated if there are no friendly pawns on the adjacent squares
const bool passed = !(stoppers ^ lever); // No enemy pawn can hinder the pawn from promoting
const Bitboard supported = (neighbours & RANKS[rank(sq + direction(color, DOWN))]);
const Bitboard phalanx = (neighbours & RANKS[rank(sq)]); // Friendly pawns which are on the same rank and on adjacent squares
bool backward = false;
// A pawn is considered backwards if there are no other friendly pawns
// on the same rank or behind the pawn and there are also no enemy pawns
// ahead of the pawn. The pawn is only backwards however if it can be captured
// by enemy pawns if he pushes one square north.
if (!isolated && !phalanx && r <= 4 && !lever) {
const Bitboard br = RANKS[rank(lsb_index(most_backward(color, neighbours | stoppers)))];
backward = (br | shift_up(ADJ_FILES[f] & br, color)) & stoppers;
}
// Penalty for doubled pawns
if (doubled) {
value -= pawnDoubledPenalty;
// Passed pawns bitboard gets saved in a pawn hash table entry
} else if (passed) {
info.passedPawns |= SQUARES[sq];
}
if (phalanx || supported) {
int bonus = pawnConnectedBonus[r] * (phalanx ? 3 : 2) / (opposed ? 2 : 1) + 8 * popcount(supported);
value += V(bonus, bonus * (r - 2) / 4);
}
// Bonus for adjacent friendy pawns on the same rank
if (phalanx) {
value += pawnPhalanxBonus[opposed][r];
// Penalty for not having any friendly pawns on adjacent files
} else if (isolated) {
value -= pawnIsolatedPenalty[opposed];
// Penalty for not having
} else if (backward) {
value -= pawnBackwardPenalty[opposed];
}
// Bonus for attacking enemy pawns
if (lever) {
value += pawnLeverBonus[r];
}
}
return value;
}
// Evaluate Pawn Shelter and Pawn Storm on the board for a given color
static int evaluate_shelter_storm(const Board& board, const Color color, const unsigned kingSq, const int oldValue) {
int value = 0;
const Bitboard notBehind = ~KingShelterSpan[!color][kingSq];
const Bitboard ourPawns = board.pieces(color, PAWN) & notBehind;
const Bitboard oppPawns = board.pieces(!color, PAWN) & notBehind;
const int kingFile = file(kingSq);
const int centralFile = std::max(1, std::min(kingFile, 6)); // The central file for the shelter. Adjusted on the edges
// Loop over each file ahead of the king
for (int f = centralFile - 1; f <= centralFile + 1; f++) {
Bitboard owns = FILES[f] & ourPawns;
Bitboard opps = FILES[f] & oppPawns;
// Get the square of the most backward friendly and most forward enemy pawn on the file
unsigned ownRank = owns ? relative_rank(color, lsb_index(most_backward(color, owns))) : 0;
unsigned oppRank = opps ? relative_rank(color, lsb_index(most_forward(!color, opps))) : 0;
// Add shelter bonus for our pawns and subtract storm penalty for enemy pawns
value += kingPawnShelter[f][ownRank];
value -= kingPawnStorm[f][oppRank];
}
// If we have not castled yet and the shelter score is greater
// once we castle, use the better value
if (oldValue > value) {
return oldValue;
}
return value;
}
// King Safety Evaluation
static const EvalTerm evaluate_king_safety(const Board& board, const Color color, const EvalInfo& info) {
EvalTerm value = V(0, 0);
// Evaluate pawn shelter and pawn storms
int pawnValue = evaluate_shelter_storm(board, color, info.kingSq[color], -VALUE_INFINITE);
// Idea from Stockfish
// If we can still castle, and the shelter bonus after the castling is greater, use the better value
if (board.may_castle(CASTLE_TYPES[color][CASTLE_SHORT])) {
pawnValue = evaluate_shelter_storm(board, color, CASTLE_KING_TARGET_SQUARE[color][CASTLE_SHORT], pawnValue);
}
if (board.may_castle(CASTLE_TYPES[color][CASTLE_LONG])) {
pawnValue = evaluate_shelter_storm(board, color, CASTLE_KING_TARGET_SQUARE[color][CASTLE_LONG], pawnValue);
}
const File kingFile = file(info.kingSq[color]);
// All squares attacked on the flank of the king excluding the base ranks (first 3 ranks) for our color
// Count the number of squares which are attacked once and multiple times
const Bitboard flankAttackedSquares = KING_FLANK[kingFile] & (SQUARES_ALL ^ COLOR_BASE_RANKS[!color]) & info.colorAttacks[!color];
const unsigned flankAttacksCount = popcount(flankAttackedSquares) + popcount(flankAttackedSquares & info.multiAttacks[!color]);
// The squares surrounding the king
const Bitboard ring = KingRing[color][info.kingSq[color]];
// Weak squares are squares are squares which we do not attack or only with queens or the king.
// These squares are considered weak if the enemy attacks them, but not if we protect them with
// multiple pieces
const Bitboard weakSquares = (info.colorAttacks[!color] & ~info.multiAttacks[color]) & (~info.colorAttacks[color] | info.pieceAttacks[color][QUEEN] | info.pieceAttacks[color][KING]);
// A square is considered safe for a enemy check if there it is not attacked by us or
// it is a weak square which is attacked by multiple enemy pieces
const Bitboard safeCheckSquares = ~board.pieces(!color) & (~info.colorAttacks[color] | (weakSquares & info.multiAttacks[!color]));
const Bitboard knightCheckSquares = gen_knight_moves(info.kingSq[color], board.pieces(color));
const Bitboard bishopCheckSquares = gen_bishop_moves(info.kingSq[color], board.pieces(BOTH) ^ board.pieces(color, QUEEN), 0);
const Bitboard rookCheckSquares = gen_rook_moves(info.kingSq[color], board.pieces(BOTH) ^ board.pieces(color, QUEEN), 0);
Bitboard unsafeChecks = 0;
const Bitboard queenChecks = info.pieceAttacks[!color][QUEEN] & (bishopCheckSquares | rookCheckSquares) & ~info.pieceAttacks[color][QUEEN];
const Bitboard rookChecks = info.pieceAttacks[!color][ROOK] & rookCheckSquares;
const Bitboard bishopChecks = info.pieceAttacks[!color][BISHOP] & bishopCheckSquares;
const Bitboard knightChecks = info.pieceAttacks[!color][KNIGHT] & knightCheckSquares;
int danger = 0;
// If there is no enemy queen, decrease the king danger value drastically
if (!board.pieces(!color, QUEEN)) {
danger -= kingNoQueenAttacker;
}
// Add a check weight value to the king danger balance if there is a safe check
if (queenChecks & (safeCheckSquares & ~rookChecks)) {
danger += queenSafeCheckWeight;
}
if (rookChecks & safeCheckSquares) {
danger += rookSafeCheckWeight;
} else {
unsafeChecks |= rookChecks;
}
if (bishopChecks & (safeCheckSquares & ~queenChecks)) {
danger += bishopSafeCheckWeight;
} else {
unsafeChecks |= bishopChecks;
}
if (knightChecks & safeCheckSquares) {
danger += knightSafeCheckWeight;
} else {
unsafeChecks |= knightChecks;
}
unsafeChecks &= info.mobilityArea[!color];
/*std::cout << "Color: " << color << std::endl;
std::cout << "Safe Checks & No Queen: " << danger << std::endl;*/
// Calculate the king danger.
// We multiply the total king attacker weights by the number of total attacks
// Attacks on the king ring and on weak squares are also considered.
// We count the total number of unsafe checks and add it to the danger value.
// Also, minors within the king ring count as defenders and decrease the king danger.
danger += info.kingAttackersNum[color] * info.kingAttackersWeight[color]
+ kingRingAttackWeight * info.kingRingAttacks[color]
+ kingRingWeakSquareAttack * popcount(ring & weakSquares)
+ kingUnsafeCheck * popcount(unsafeChecks)
+ kingSliderBlocker * popcount(board.get_king_blockers(color))
+ 2 * flankAttacksCount / 8
+ info.mobility[!color].mg - info.mobility[color].mg
- kingKnightDefender * popcount(ring & info.pieceAttacks[color][KNIGHT])
- kingBishopDefender * popcount(ring & info.pieceAttacks[color][BISHOP])
- 6 * pawnValue / 9;
/*std::cout << "Flank Attacks: " << kingFlankAttack * flankAttacksCount << std::endl;
std::cout << "Attackers: " << (info.kingAttackersNum[color] * info.kingAttackersWeight[color]) << std::endl;
std::cout << "Ring Attacks: " << (kingRingAttackWeight * info.kingRingAttacks[color]) << std::endl;
std::cout << "Ring Weak Square Attack: " << kingRingWeakSquareAttack * popcount(ring & weakSquares) << std::endl;
std::cout << "Unsafe Checks: " << kingUnsafeCheck * popcount(unsafeChecks) << std::endl;
std::cout << "Slider Blockers: " << kingSliderBlocker * popcount(board.get_king_blockers(color)) << std::endl;
std::cout << "Flank Attacks Count: " << 2 * flankAttacksCount / 8 << std::endl;
std::cout << "Mobility: " << (info.mobility[!color].mg - info.mobility[color].mg) << std::endl;
std::cout << "Knight Defender: " << (kingKnightDefender * popcount(ring & info.attackedSquares[Knight(color)])) << std::endl;
std::cout << "Bishop Defender: " << (kingBishopDefender * popcount(ring & info.attackedSquares[Bishop(color)])) << std::endl;
std::cout << "Pawn EvalTerm: " << pawnValue << ":" << (6 * pawnValue / 9) << std::endl;
std::cout << "Final: " << danger << ":" << std::max(0, (danger * danger / 2048)) << std::endl << std::endl;*/
// We transform the king danger into a value which is subtracted from the king safety
if (danger > 0) {
value -= V(danger * danger / 2048, danger / 16);
}
// If there are no pawns on the king flank, we decrease the king safety value
if (!(board.pieces(color, PAWN) & KING_FLANK[kingFile])) {
value -= kingPawnlessFlank;
}
value -= kingFlankAttack * flankAttacksCount;
value.mg += pawnValue;
return V(std::min(80, value.mg), value.eg);
}
// Evaluate Passed Pawns on the board by a given color
static const EvalTerm evaluate_passers(const Board& board, const Color color, const EvalInfo& info) {
EvalTerm value;
Bitboard passers = info.passedPawns & board.pieces(color);
// Loop over all passed pawns
while (passers) {
const Square sq = pop_lsb(passers);
const Square blocksq = sq + direction(color, UP);
const Rank r = relative_rank(color, sq);
const File f = file(sq);
const unsigned rfactor = (r - 2) * (r - 1) / 2;
// Add a bonus based on both king's distance to the pawn
value += V(0, ((5 * KingDistance[info.kingSq[!color]][blocksq]) - (2 * KingDistance[info.kingSq[color]][blocksq])) * rfactor);
if (r > 2 && !(SQUARES[blocksq] & board.pieces(BOTH))) {
EvalTerm bonus = V(0, 0);
Bitboard path = FrontFileMask[color][sq];
Bitboard behind = FrontFileMask[!color][sq];
Bitboard attacked = PassedPawnMask[color][sq];
Bitboard majorsBehind = behind & board.majors();
// If there are no major enemy pieces on the file behind the pawn,
// check if there are any squares in front of the pawn atttacked
if (!(majorsBehind & board.pieces(!color))) {
attacked &= info.colorAttacks[!color];
}
// If the block square is defended, add a bonus
if ((info.colorAttacks[color] & SQUARES[blocksq]) || (majorsBehind & board.pieces(color))) {
bonus += passedPawnBlockSqDefended;
}
// Add a bonus based on the kind of attacks on the pawn
if (!attacked) {
bonus += passedPawnNoAttacks;
} else if (!(attacked & path)) {
bonus += passedPawnSafePath;
} else if (!(attacked & SQUARES[blocksq])) {
bonus += passedPawnSafePush;
}
// Multiply the bonus with a factor based on the relative rank
// and add it to the passed pawns evaluation
value += bonus * rfactor;
}
// Add a bonus based on the rank and the file of the pawn
value += pawnPassedRankBonus[r] - pawnPassedFilePenalty[f];
}
// No negative evaluation for passed pawns
return V(std::max(0, value.mg), std::max(0, value.eg));
}
// Evaluate all material imbalances on the board for the given color
static const EvalTerm evaluate_imbalances(const Board& board, const Color color) {
EvalTerm value;
const unsigned pieceCounts[2][6] = {
{ board.piececount(WHITE, BISHOP) > 1, board.piececount(WHITE, PAWN), board.piececount(WHITE, KNIGHT), board.piececount(WHITE, BISHOP), board.piececount(WHITE, ROOK), board.piececount(WHITE, QUEEN) },
{ board.piececount(BLACK, BISHOP) > 1, board.piececount(BLACK, PAWN), board.piececount(BLACK, KNIGHT), board.piececount(BLACK, BISHOP), board.piececount(BLACK, ROOK), board.piececount(BLACK, QUEEN) }
};
// Loop over all piece types
for (unsigned pt1index = 0; pt1index <= 5; pt1index++) {
if (pieceCounts[color][pt1index] > 0) {
int v = 0;
// Loop over all the piece types again, and add the imbalance value based
// on how many pieces are on the board
for (unsigned pt2index = 0; pt2index <= pt1index; pt2index++) {
v += Imbalance[0][pt1index][pt2index] * pieceCounts[color][pt2index] + Imbalance[1][pt1index][pt2index] * pieceCounts[!color][pt2index];
}
// Multiply the value with the number of pieces of the current type
value += V(v * pieceCounts[color][pt1index], v * pieceCounts[color][pt1index]);
}
}
return value;
}
// Evaluate all threats on the board for the given color
static const EvalTerm evaluate_threats(const Board& board, const Color color, const EvalInfo& info) {
EvalTerm value;
const Bitboard nonPawnPieces = board.pieces(!color) ^ board.pieces(!color, PAWN); //board.minors_and_majors(!color);
const Bitboard strongSquares = info.pieceAttacks[!color][PAWN] | (info.multiAttacks[!color] & ~info.multiAttacks[color]);
const Bitboard defendedPieces = nonPawnPieces & strongSquares;
const Bitboard weakPieces = board.pieces(!color) & ~strongSquares & info.colorAttacks[color];
// Evaluate minors and rooks attacking weak and defended pieces
// Add a bigger bonus for pieces which are are close to our base
// since they are more vulnerable there
if (defendedPieces | weakPieces) {
Bitboard minorAttacks = (defendedPieces | weakPieces) & (info.pieceAttacks[color][KNIGHT] | info.pieceAttacks[color][BISHOP]);
while (minorAttacks) {
const Square sq = pop_lsb(minorAttacks);
const Piecetype pt = board.piecetype(sq);
value += minorAttackWeight[pt];
if (pt != PAWN) {
value += pieceVulnerable * relative_rank(!color, sq);
}
}
Bitboard rookAttacks = weakPieces & info.pieceAttacks[color][ROOK];
while (rookAttacks) {
const Square sq = pop_lsb(rookAttacks);
const Piecetype pt = board.piecetype(sq);
value += rookAttackWeight[pt];
if (pt != PAWN) {
value += pieceVulnerable * relative_rank(!color, sq);
}
}
// Bonus for king attacking weak pieces
value += KingAttackThreat * popcount(weakPieces & info.pieceAttacks[color][KING]);
// Bonus for unprotected weak pieces and weak pieces which are attacked multiple times by us
value += HangingPiece * popcount(weakPieces & (~info.colorAttacks[!color] | (nonPawnPieces & info.multiAttacks[color])));
}
// Bonus for restricting the mobility of enemy pieces
value += mobilityRestriction * popcount(info.colorAttacks[!color] & ~strongSquares & info.colorAttacks[color]);
const Bitboard safeSquares = info.colorAttacks[color] | ~info.colorAttacks[!color];
const Bitboard safePawns = board.pieces(color, PAWN) & safeSquares;
// Bonus for safe pawns attacking minor and major pieces
value += safePawnAttack * popcount(generate_pawns_attacks(safePawns, color) & nonPawnPieces);
// Bonus for pawn pushes which attack enemy pieces
Bitboard pawnPushes = shift_up(board.pieces(color, PAWN), color) & ~board.pieces(BOTH);
pawnPushes |= shift_up(pawnPushes & PAWN_FIRST_PUSH_RANK[color], color) & ~board.pieces(BOTH);
pawnPushes &= ~info.pieceAttacks[!color][PAWN] & safeSquares;
value += pawnPushThreat * popcount(generate_pawns_attacks(pawnPushes, color) & nonPawnPieces);
// Evaluate possible safe attacks on queen
Bitboard queens = board.pieces(!color, QUEEN);
if (queens) {
Square sq = pop_lsb(queens);
Bitboard knightAttackSquares = gen_knight_moves(sq, board.pieces(color)) & info.pieceAttacks[color][KNIGHT];
Bitboard bishopAttackSquares = gen_bishop_moves(sq, board.pieces(BOTH), 0) & info.pieceAttacks[color][BISHOP];
Bitboard rookAttackSquares = gen_rook_moves(sq, board.pieces(BOTH), 0) & info.pieceAttacks[color][ROOK];
Bitboard safe = info.mobilityArea[color] & ~strongSquares;
value += KnightQueenAttackThreat * popcount(knightAttackSquares & safe);
safe &= info.multiAttacks[color];
value += BishopQueenAttackThreat * popcount(bishopAttackSquares & safe);
value += RookQueenAttackThreat * popcount(rookAttackSquares & safe);
}
return value;
}
// Initialize the evaluation info object
static void init_eval_info(const Board& board, EvalInfo& info) {
// The mobility area is all squares we count for mobility.
// We count all squares except for those attacked by enemy pawns
// and blocked friendly pawns, our queens and king.
info.mobilityArea[WHITE] = SQUARES_ALL & ~((board.pieces(WHITE, KING) | board.pieces(WHITE, QUEEN)) | (board.pieces(WHITE, PAWN) & (shift_down(board.pieces(BOTH), WHITE) | BB_RANK_2 | BB_RANK_3)) | info.pieceAttacks[BLACK][PAWN]);
info.mobilityArea[BLACK] = SQUARES_ALL & ~((board.pieces(BLACK, KING) | board.pieces(BLACK, QUEEN)) | (board.pieces(BLACK, PAWN) & (shift_down(board.pieces(BOTH), BLACK) | BB_RANK_7 | BB_RANK_6)) | info.pieceAttacks[WHITE][PAWN]);
// Set king square and ring area bitboards for each color
info.kingSq[WHITE] = lsb_index(board.pieces(WHITE, KING));
info.kingSq[BLACK] = lsb_index(board.pieces(BLACK, KING));
info.kingRing[WHITE] = KingRing[WHITE][info.kingSq[WHITE]];
info.kingRing[BLACK] = KingRing[BLACK][info.kingSq[BLACK]];
// Bitboards for cumulative piece attacks for each piece type for each color
info.pieceAttacks[WHITE][KING] = KingAttacks[info.kingSq[WHITE]];
info.pieceAttacks[BLACK][KING] = KingAttacks[info.kingSq[BLACK]];
// Bitboards for attacks of each color
info.colorAttacks[WHITE] |= info.pieceAttacks[WHITE][KING] | info.pieceAttacks[WHITE][PAWN];
info.colorAttacks[BLACK] |= info.pieceAttacks[BLACK][KING] | info.pieceAttacks[BLACK][PAWN];
// Squares which are attacked by multiple pieces
info.multiAttacks[WHITE] = info.pieceAttacks[WHITE][KING] & info.pieceAttacks[WHITE][PAWN];
info.multiAttacks[BLACK] = info.pieceAttacks[BLACK][KING] & info.pieceAttacks[BLACK][PAWN];
// Count of total pieces attacking the king for each color
info.kingAttackersNum[WHITE] = popcount(info.pieceAttacks[WHITE][KING] & info.pieceAttacks[BLACK][PAWN]);
info.kingAttackersNum[BLACK] = popcount(info.pieceAttacks[BLACK][KING] & info.pieceAttacks[WHITE][PAWN]);
// Bitboards of pawns which cannot advance because there is a piece on their push square
info.blockedPawns[WHITE] = shift_up(board.pieces(WHITE, PAWN), WHITE) & board.pieces(BOTH);
info.blockedPawns[BLACK] = shift_up(board.pieces(BLACK, PAWN), BLACK) & board.pieces(BOTH);
}
// Evaluate the position statically
int evaluate(const Board& board, const unsigned threadIndex) {
Thread* thread = Threads.get_thread(threadIndex);
EvalTerm value;
EvalInfo info;
// Check for draw by insufficient material
if (board.is_material_draw()) {
return 0;
}
// Probe the pawn hash table
PawnEntry * pentry = thread->pawnTable.probe(board.pawnkey());
if (pentry != NULL) {
value += pentry->value;
info.passedPawns = pentry->passedPawns;
info.pieceAttacks[WHITE][PAWN] = pentry->pawnWAttacks;
info.pieceAttacks[BLACK][PAWN] = pentry->pawnBAttacks;
info.pawnAttacksSpan[WHITE] = pentry->pawnWAttacksSpan;
info.pawnAttacksSpan[BLACK] = pentry->pawnBAttacksSpan;
assert(pentry->value == (evaluate_pawns(board, WHITE, info) - evaluate_pawns(board, BLACK, info)));
} else {
// If there is no entry available, compute the pawn attacks
info.pieceAttacks[WHITE][PAWN] = board.gen_white_pawns_attacks();
info.pieceAttacks[BLACK][PAWN] = board.gen_black_pawns_attacks();
}
// Initialize the evaluation
init_eval_info(board, info);
// Material balance
value += board.material(WHITE);
value -= board.material(BLACK);
// Piece square table values
value += board.pst(WHITE);
value -= board.pst(BLACK);
// Pawns Evaluation (skip if we already have a value from the hash table)
if (pentry == NULL) {
EvalTerm pawnValue = evaluate_pawns(board, WHITE, info) - evaluate_pawns(board, BLACK, info);
thread->pawnTable.store(board.pawnkey(), pawnValue, info.pieceAttacks[WHITE][PAWN], info.pieceAttacks[BLACK][PAWN], info.passedPawns, info.pawnAttacksSpan[WHITE], info.pawnAttacksSpan[BLACK]);
value += pawnValue;
}
// Evaluate the pieces
value += evaluate_knights(board, WHITE, info);
value += evaluate_bishops(board, WHITE, info);
value += evaluate_rooks(board, WHITE, info);
value += evaluate_queens(board, WHITE, info);
value -= evaluate_knights(board, BLACK, info);
value -= evaluate_bishops(board, BLACK, info);
value -= evaluate_rooks(board, BLACK, info);
value -= evaluate_queens(board, BLACK, info);
// Mobility
value += info.mobility[WHITE];
value -= info.mobility[BLACK];
// King Safety
value += evaluate_king_safety(board, WHITE, info);
value -= evaluate_king_safety(board, BLACK, info);
// Passed Pawns
value += evaluate_passers(board, WHITE, info);
value -= evaluate_passers(board, BLACK, info);
// Threats
value += evaluate_threats(board, WHITE, info);
value -= evaluate_threats(board, BLACK, info);
// Imbalances
MaterialEntry * mentry = thread->materialTable.probe(board.materialkey());
if (mentry != NULL) {
value += mentry->value;
assert(mentry->value == (evaluate_imbalances(board, WHITE) - evaluate_imbalances(board, BLACK)));
} else {
EvalTerm imbalanceValue = evaluate_imbalances(board, WHITE) - evaluate_imbalances(board, BLACK);
thread->materialTable.store(board.materialkey(), imbalanceValue);
value += imbalanceValue;
}
assert(std::abs(scaled_eval(board.scale(), value)) < VALUE_MATE_MAX);
// Return the scaled evaluation and add a tempo bonus for the color to move
// Also, invert the evaluation to match the perspective of the color to move
return ((board.turn() == WHITE) ? scaled_eval(board.scale(), value)
: -scaled_eval(board.scale(), value)) + tempoBonus;
}
// Evaluate the position statically and print a table containing
// all evaluation terms to the console. Useful for debugging
void evaluate_info(const Board& board) {
EvalTerm value;
EvalInfo info;
info.pieceAttacks[WHITE][PAWN] = board.gen_white_pawns_attacks();
info.pieceAttacks[BLACK][PAWN] = board.gen_black_pawns_attacks();
init_eval_info(board, info);
// Material
const EvalTerm whiteMaterialPsqt = board.material(WHITE) + board.pst(WHITE);
const EvalTerm blackMaterialPsqt = board.material(BLACK) + board.pst(BLACK);
// Pawns
const EvalTerm whitePawns = evaluate_pawns(board, WHITE, info);
const EvalTerm blackPawns = evaluate_pawns(board, BLACK, info);
// Pieces
const EvalTerm whiteKnights = evaluate_knights(board, WHITE, info);
const EvalTerm whiteBishops = evaluate_bishops(board, WHITE, info);
const EvalTerm whiteRooks = evaluate_rooks(board, WHITE, info);
const EvalTerm whiteQueens = evaluate_queens(board, WHITE, info);
const EvalTerm blackKnights = evaluate_knights(board, BLACK, info);
const EvalTerm blackBishops = evaluate_bishops(board, BLACK, info);
const EvalTerm blackRooks = evaluate_rooks(board, BLACK, info);
const EvalTerm blackQueens = evaluate_queens(board, BLACK, info);
// King Safety
const EvalTerm whiteKingSafety = evaluate_king_safety(board, WHITE, info);
const EvalTerm blackKingSafety = evaluate_king_safety(board, BLACK, info);
// Passed Pawns
const EvalTerm whitePassers = evaluate_passers(board, WHITE, info);
const EvalTerm blackPassers = evaluate_passers(board, BLACK, info);
// Threats
const EvalTerm whiteThreats = evaluate_threats(board, WHITE, info);
const EvalTerm blackThreats = evaluate_threats(board, BLACK, info);
// Imbalances
const EvalTerm whiteImbalances = evaluate_imbalances(board, WHITE);
const EvalTerm blackImbalances = evaluate_imbalances(board, BLACK);
// Output evaluation terms to the console
std::cout << "(White)" << std::endl;
std::cout << "Material & Psqt : " << whiteMaterialPsqt.mg << " | " << whiteMaterialPsqt.eg << std::endl;
std::cout << "Imbalance : " << whiteImbalances.mg << " | " << whiteImbalances.eg << std::endl;
std::cout << "Pawns : " << whitePawns.mg << " | " << whitePawns.eg << std::endl;
std::cout << "Knights : " << whiteKnights.mg << " | " << whiteKnights.eg << std::endl;
std::cout << "Bishops : " << whiteBishops.mg << " | " << whiteBishops.eg << std::endl;
std::cout << "Rooks : " << whiteRooks.mg << " | " << whiteRooks.eg << std::endl;
std::cout << "Queens : " << whiteQueens.mg << " | " << whiteQueens.eg << std::endl;
std::cout << "Mobility : " << info.mobility[WHITE].mg << " | " << info.mobility[WHITE].eg << std::endl;
std::cout << "Passed Pawns : " << whitePassers.mg << " | " << whitePassers.eg << std::endl;
std::cout << "King safety : " << whiteKingSafety.mg << " | " << whiteKingSafety.eg << std::endl;
std::cout << "Threats : " << whiteThreats.mg << " | " << whiteThreats.eg << std::endl;
std::cout << std::endl;
std::cout << "(Black)" << std::endl;
std::cout << "Material & Psqt : " << blackMaterialPsqt.mg << " | " << blackMaterialPsqt.eg << std::endl;
std::cout << "Imbalance : " << blackImbalances.mg << " | " << blackImbalances.eg << std::endl;
std::cout << "Pawns : " << blackPawns.mg << " | " << blackPawns.eg << std::endl;
std::cout << "Knights : " << blackKnights.mg << " | " << blackKnights.eg << std::endl;
std::cout << "Bishops : " << blackBishops.mg << " | " << blackBishops.eg << std::endl;
std::cout << "Rooks : " << blackRooks.mg << " | " << blackRooks.eg << std::endl;
std::cout << "Queens : " << blackQueens.mg << " | " << blackQueens.eg << std::endl;
std::cout << "Mobility : " << info.mobility[BLACK].mg << " | " << info.mobility[BLACK].eg << std::endl;
std::cout << "Passed Pawns : " << blackPassers.mg << " | " << blackPassers.eg << std::endl;
std::cout << "King safety : " << blackKingSafety.mg << " | " << blackKingSafety.eg << std::endl;
std::cout << "Threats : " << blackThreats.mg << " | " << blackThreats.eg << std::endl;
std::cout << std::endl;
value += whiteMaterialPsqt - blackMaterialPsqt;
value += whiteImbalances - blackImbalances;
value += whiteKnights - blackKnights;
value += whiteBishops - blackBishops;
value += whiteRooks - blackRooks;
value += whiteQueens - blackQueens;
value += whitePawns - blackPawns;
value += info.mobility[WHITE] - info.mobility[BLACK];
value += whitePassers - blackPassers;
value += whiteKingSafety - blackKingSafety;
value += whiteThreats - blackThreats;
int finalValue = scaled_eval(board.scale(), value);
int normalEval = evaluate(board, 0);
if (std::abs(finalValue + (board.turn() == WHITE ? tempoBonus : -tempoBonus)) != std::abs(normalEval)) {
std::cout << "ERROR: Difference between evaluation functions!!!" << std::endl;
std::cout << (finalValue + (board.turn() == WHITE ? tempoBonus : -tempoBonus)) << std::endl;
std::cout << normalEval - tempoBonus << std::endl;
abort();
}
std::cout << "Total(For White): " << scaled_eval(board.scale(), value) << std::endl;
}
| 42.485544 | 311 | 0.601045 | [
"object",
"transform"
] |
bbbeaf2ec64092f6c75cd76bdbbe0277a21c4976 | 642 | hpp | C++ | Xcode/PathTracer/HittableVector.hpp | saldavonschwartz/pathTracer | b5a0cfcd6a55c2368be134baaaa6df214838f78e | [
"MIT"
] | null | null | null | Xcode/PathTracer/HittableVector.hpp | saldavonschwartz/pathTracer | b5a0cfcd6a55c2368be134baaaa6df214838f78e | [
"MIT"
] | null | null | null | Xcode/PathTracer/HittableVector.hpp | saldavonschwartz/pathTracer | b5a0cfcd6a55c2368be134baaaa6df214838f78e | [
"MIT"
] | null | null | null | //
// HittableVector.hpp
// PathTracer
//
// Created by Federico Saldarini on 4/16/20.
// Copyright © 2020 Federico Saldarini. All rights reserved.
//
#ifndef HittableVector_hpp
#define HittableVector_hpp
#include "Hittable.hpp"
#include <vector>
#include <memory>
using std::vector;
using std::shared_ptr;
class HittableVector : public Hittable {
public:
vector<shared_ptr<Hittable>> data;
void push_back(shared_ptr<Hittable> hittable);
bool boundingBox(double t0, double t1, AABA& bBox) const override;
bool hit(const Ray& ray, float tmin, float tmax, HitInfo& info) const override;
};
#endif /* HittableVector_hpp */
| 20.709677 | 81 | 0.735202 | [
"vector"
] |
bbbfcd0ae9699240cbc1602ee2eac681d8775ccc | 27,768 | cpp | C++ | src/BehaviorPlanner.cpp | gddavis21/CarND-Path-Planning | f7871afae85c03baf6cec206068119cedc6b54b0 | [
"MIT"
] | null | null | null | src/BehaviorPlanner.cpp | gddavis21/CarND-Path-Planning | f7871afae85c03baf6cec206068119cedc6b54b0 | [
"MIT"
] | null | null | null | src/BehaviorPlanner.cpp | gddavis21/CarND-Path-Planning | f7871afae85c03baf6cec206068119cedc6b54b0 | [
"MIT"
] | null | null | null | #include "BehaviorPlanner.h"
#include <limits>
#include <algorithm>
#include <iostream>
using namespace std;
const static double timeStep = 1.5; // sec
//static const size_t ID_EGO = numeric_limits<size_t>::max();
BehaviorPlanner::BehaviorPlanner(
const DrivingParameters &drivingParams,
const HighwayParameters &highwayParams)
{
_drivingParams = drivingParams;
_highwayParams = highwayParams;
_currentBehavior = KeepLane;
}
BehaviorPlanner::Behavior BehaviorPlanner::CurrentBehavior() const {
return _currentBehavior;
}
size_t BehaviorPlanner::GetLane(const Vehicle &veh) const {
return _highwayParams.WhichLane(veh.LateralPosition());
}
double BehaviorPlanner::LaneCenter(size_t lane) const {
return lane*_highwayParams.LaneWidth + _highwayParams.LaneWidth/2;
}
double BehaviorPlanner::DistanceBehind(const Vehicle &behind, const Vehicle &ahead) const
{
double dist = ahead.Position() - behind.Position();
return (dist < 0.0) ? (dist + _highwayParams.WrapAroundPosition) : dist;
}
bool BehaviorPlanner::IsChangingLanes() const
{
return _currentBehavior == LaneChangeLeft || _currentBehavior == LaneChangeRight;
}
string BehaviorPlanner::BehaviorLabel(Behavior behavior)
{
switch (behavior)
{
case KeepLane: return "Keep Lane";
case PrepareLaneChangeLeft: return "Prepare Lane-Change Left";
case PrepareLaneChangeRight: return "Prepare Lane-Change Right";
case LaneChangeLeft: return "Lane-Change Left";
case LaneChangeRight: return "Lane-Change Right";
}
return "";
}
// Vehicle EgoVehicle::Update(const VehiclePredictions &predictions, const Vehicle &egoStart)
// {
// // _longKinematics = longKinematics;
// // _lateralPos = lateralPos;
// // vector<Behavior> behaviors;
// // vector<VehicleTrajectory> trajectories;
// // vector<double> costs;
// double minCost = numeric_limits<double>::max();
// Behavior nextBehavior = KeepLane;
// Vehicle egoNext;
// // next trajectory always starts with current state
// // Vehicle currentState(*this);
// // compute candidate trajectories & associated costs
// for (Behavior behavior: SuccessorBehaviors())
// {
// Vehicle nextCand = GenerateTrajectory(behavior, predictions, egoNow);
// if (nextCand.IsValid())
// {
// double cost = TrajectoryCost(predictions, egoNow, nextCand);
// if (cost < minCost)
// {
// nextBehavior = behavior;
// minCost = cost;
// egoNext = nextCand;
// }
// }
// }
// _currentBehavior = nextBehavior;
// return egoNext;
// }
BehaviorPlanner::Trajectory BehaviorPlanner::Update(const Vehicle &ego, const vector<Vehicle> &others)
{
double min_cost = numeric_limits<double>::max();
Behavior best_behavior = KeepLane;
Trajectory best_trajectory;
for (Behavior behavior: SuccessorBehaviors(ego))
{
Trajectory traj = GenerateTrajectory(ego, others, behavior);
if (traj.is_valid)
{
double cost = TrajectoryCost(ego, others, behavior, traj);
if (cost < min_cost)
{
best_behavior = behavior;
best_trajectory = traj;
min_cost = cost;
}
}
}
_currentBehavior = best_behavior;
return best_trajectory;
}
vector<BehaviorPlanner::Behavior> BehaviorPlanner::SuccessorBehaviors(const Vehicle &ego) const
{
bool inLeftLane = (GetLane(ego) == 0);
bool inRightLane = (GetLane(ego) == _highwayParams.LaneCount - 1);
vector<Behavior> successors;
switch (_currentBehavior)
{
case KeepLane:
successors.push_back(KeepLane);
if (!inLeftLane)
successors.push_back(PrepareLaneChangeLeft);
if (!inRightLane)
successors.push_back(PrepareLaneChangeRight);
break;
case PrepareLaneChangeLeft:
successors.push_back(KeepLane);
successors.push_back(PrepareLaneChangeLeft);
successors.push_back(LaneChangeLeft);
break;
case PrepareLaneChangeRight:
successors.push_back(KeepLane);
successors.push_back(PrepareLaneChangeRight);
successors.push_back(LaneChangeRight);
break;
case LaneChangeLeft:
successors.push_back(KeepLane);
break;
case LaneChangeRight:
successors.push_back(KeepLane);
break;
}
return successors;
}
// Vehicle EgoVehicle::GenerateTrajectory(
// Behavior behavior,
// const VehiclePredictions &predictions,
// const Vehicle &ego) const
// {
// const bool LEFT = true;
// const bool RIGHT = false;
// switch (behavior)
// {
// case KeepLane: return KeepLaneTrajectory(predictions, ego);
// case PrepareLaneChangeLeft: return PrepareLaneChangeTrajectory(LEFT, predictions, ego);
// case PrepareLaneChangeRight: return PrepareLaneChangeTrajectory(RIGHT, predictions, ego);
// case LaneChangeLeft: return LaneChangeTrajectory(LEFT, predictions, ego);
// case LaneChangeRight: return LaneChangeTrajectory(RIGHT, predictions, ego);
// }
// return Vehicle();
// }
BehaviorPlanner::Trajectory BehaviorPlanner::GenerateTrajectory(
const Vehicle &ego,
const vector<Vehicle> &others,
Behavior behavior) const
{
const bool LEFT = true;
const bool RIGHT = false;
switch (behavior)
{
case KeepLane: return KeepLaneTrajectory(ego, others);
case PrepareLaneChangeLeft: return PrepareLaneChangeTrajectory(ego, others, LEFT);
case PrepareLaneChangeRight: return PrepareLaneChangeTrajectory(ego, others, RIGHT);
case LaneChangeLeft: return LaneChangeTrajectory(ego, others, LEFT);
case LaneChangeRight: return LaneChangeTrajectory(ego, others, RIGHT);
}
return Trajectory { .is_valid = false };
}
// Vehicle EgoVehicle::ConstantSpeedTrajectory(
// const VehiclePredictions &predictions,
// double dt) const
// {
// return Predict(dt);
// }
// Vehicle EgoVehicle::KeepLaneTrajectory(
// const VehiclePredictions &predictions,
// const Vehicle &ego) const
// {
// Kinematics nextKin = GetKinematicsForLane(predictions, ego, ego.GetLane());
// return Vehicle(_highwayParams, nextKin, ego.GetLateralPosition(), ego.GetTime() + 1.0);
// }
// Vehicle BehaviorPlanner::KeepLaneTrajectory(const Vehicle &ego, const vector<Vehicle> &others) const
// {
// return Vehicle(
// _highwayParams,
// GetLaneKinematics(ego, others, ego.Lane(), timeStep),
// ego.LaneCenter(),
// ego.Time() + timeStep);
// }
BehaviorPlanner::Trajectory BehaviorPlanner::KeepLaneTrajectory(
const Vehicle &ego,
const vector<Vehicle> &others) const
{
return {
.is_valid = true,
.goal_velocity = GetLaneVelocity(ego, others, GetLane(ego)),
.goal_lateral_position = LaneCenter(GetLane(ego))
};
}
// Vehicle EgoVehicle::PrepareLaneChangeTrajectory(
// bool moveLeft,
// const VehiclePredictions &predictions,
// const Vehicle &ego) const
// {
// size_t currentLane = ego.GetLane();
// size_t targetLane = moveLeft ? (currentLane - 1) : (currentLane + 1);
// Kinematics currentLaneKinematics = GetKinematicsForLane(predictions, ego, currentLane);
// Kinematics targetLaneKinematics = GetKinematicsForLane(predictions, ego, targetLane);
// double gapBehind = numeric_limits<double>::max();
// size_t behindID;
// if (TryGetVehicleBehind(predictions, ego, currentLane, behindID))
// {
// Vehicle vehBehind = predictions.at(behindID)[0];
// gapBehind = ego.DistanceBehind(vehBehind) / ego.GetLongitudinalVelocity();
// }
// Kinematics nextKin = currentLaneKinematics;
// if (gapBehind > 5 && targetLaneKinematics.velocity < currentLaneKinematics.velocity)
// nextKin = targetLaneKinematics;
// return Vehicle(_highwayParams, nextKin, ego.GetLateralPosition(), ego.GetTime() + 1.0);
// }
// Vehicle BehaviorPlanner::PrepareLaneChangeTrajectory(
// const Vehicle &ego,
// const vector<Vehicle> &others,
// bool moveLeft) const
// {
// size_t currentLane = ego.Lane();
// size_t targetLane = moveLeft ? (currentLane - 1) : (currentLane + 1);
// Kinematics currentLaneKinematics = GetLaneKinematics(ego, others, currentLane, timeStep);
// Kinematics targetLaneKinematics = GetLaneKinematics(ego, others, targetLane, timeStep);
// bool slowToTarget = false;
// if (targetLaneKinematics.velocity < currentLaneKinematics.velocity)
// {
// size_t indexBehind;
// double timeBehind;
// slowToTarget = TryGetVehicleBehind(ego, others, currentLane, indexBehind, timeBehind) && (timeBehind > 3);
// }
// return Vehicle(
// _highwayParams,
// slowToTarget ? targetLaneKinematics : currentLaneKinematics,
// ego.LaneCenter(),
// ego.Time() + timeStep);
// }
BehaviorPlanner::Trajectory BehaviorPlanner::PrepareLaneChangeTrajectory(
const Vehicle &ego,
const vector<Vehicle> &others,
bool change_left) const
{
size_t current_lane = GetLane(ego);
size_t target_lane = change_left ? (current_lane - 1) : (current_lane + 1);
double current_lane_velocity = GetLaneVelocity(ego, others, current_lane);
double target_lane_velocity = GetLaneVelocity(ego, others, target_lane);
bool slow_to_target = false;
if (target_lane_velocity < current_lane_velocity)
{
size_t index;
double dist_behind, time_behind;
slow_to_target = TryGetVehicleBehind(ego, others, current_lane, index, dist_behind, time_behind) && (time_behind > 3);
}
return {
.is_valid = true,
.goal_velocity = slow_to_target ? target_lane_velocity : current_lane_velocity,
.goal_lateral_position = LaneCenter(GetLane(ego))
};
}
// Vehicle EgoVehicle::LaneChangeTrajectory(
// bool moveLeft,
// const VehiclePredictions &predictions,
// const Vehicle &ego) const
// {
// double currentVelocity = ego.GetLongitudinalVelocity();
// size_t currentLane = ego.GetLane();
// size_t targetLane = moveLeft ? (currentLane - 1) : (currentLane + 1);
// size_t aheadID, behindID;
// // detect collision with car ahead in target lane
// if (TryGetVehicleAhead(predictions, ego, targetLane, aheadID))
// {
// Vehicle vehNow = predictions.at(aheadID)[0];
// Vehicle vehPred = predictions.at(aheadID)[1];
// double gapNow = ego.DistanceAhead(vehNow) / currentVelocity;
// double gapPred = ego.Predict(1.0).DistanceAhead(vehPred) / currentVelocity;
// if (gapNow < 1.0 || gapPred < 1.0)
// return Vehicle();
// }
// // detect collision with car behind in target lane
// if (TryGetVehicleBehind(predictions, ego, targetLane, behindID))
// {
// Vehicle vehNow = predictions.at(behindID)[0];
// Vehicle vehPred = predictions.at(behindID)[1];
// double gapNow = ego.DistanceBehind(vehNow) / currentVelocity;
// double gapPred = ego.Predict(1.0).DistanceBehind(vehPred) / currentVelocity;
// if (gapNow < 1.0 || gapPred < 1.0)
// return Vehicle();
// }
// // no collisions detected --> safe to move into target lane
// Kinematics nextKin = GetKinematicsForLane(predictions, ego, targetLane);
// double currentLateral = ego.GetLateralPosition();
// double laneWidth = _highwayParams.LaneWidth;
// double nextLateral = moveLeft ? (currentLateral - laneWidth) : (currentLateral + laneWidth);
// return Vehicle(
// _highwayParams,
// GetKinematicsForLane(predictions, targetLane, dt),
// moveLeft ? (_lateralPos - laneWidth) : (_lateralPos + laneWidth));
// }
// Vehicle BehaviorPlanner::LaneChangeTrajectory(
// const Vehicle &ego,
// const vector<Vehicle> &others,
// bool moveLeft) const
// {
// size_t targetLane = moveLeft ? (ego.Lane() - 1) : (ego.Lane() + 1);
// Kinematics targetLaneKinematics = GetLaneKinematics(ego, others, targetLane, timeStep);
// size_t indexAhead, indexBehind;
// double timeAhead, timeBehind;
// // TODO: parameterize "potential collision" time margin
// // TODO: distinguish between acceptable time ahead & time behind?
// // detect collision with car ahead in target lane
// if (TryGetVehicleAhead(ego, others, targetLane, indexAhead, timeAhead) && (timeAhead < 1.5))
// {
// return Vehicle();
// }
// // detect collision with car behind in target lane
// if (TryGetVehicleBehind(ego, others, targetLane, indexBehind, timeBehind) && (timeBehind < 1.5))
// {
// return Vehicle();
// }
// // no collisions detected --> safe to move into target lane
// double laneWidth = _highwayParams.LaneWidth;
// return Vehicle(
// _highwayParams,
// targetLaneKinematics,
// moveLeft ? (ego.LaneCenter() - laneWidth) : (ego.LaneCenter() + laneWidth),
// ego.Time() + timeStep);
// }
BehaviorPlanner::Trajectory BehaviorPlanner::LaneChangeTrajectory(
const Vehicle &ego,
const vector<Vehicle> &others,
bool change_left) const
{
size_t current_lane = GetLane(ego);
size_t target_lane = change_left ? (current_lane - 1) : (current_lane + 1);
size_t index;
double dist_ahead, time_ahead, dist_behind, time_behind;
// TODO: parameterize "potential collision" time margin
// TODO: distinguish between acceptable time ahead & time behind?
// detect collision with car ahead in target lane
if (TryGetVehicleAhead(ego, others, target_lane, index, dist_ahead, time_ahead) && (time_ahead < 1.5))
{
return Trajectory { .is_valid = false };
}
// detect collision with car behind in target lane
if (TryGetVehicleBehind(ego, others, target_lane, index, dist_behind, time_behind) && (time_behind < 1.5))
{
return Trajectory { .is_valid = false };
}
// no collisions detected --> safe to move into target lane
return {
.is_valid = true,
.goal_velocity = GetLaneVelocity(ego, others, target_lane),
.goal_lateral_position = LaneCenter(target_lane)
};
}
// Kinematics EgoVehicle::GetKinematicsForLane(
// const VehiclePredictions &predictions,
// const Vehicle &ego,
// size_t lane) const
// {
// const Kinematics &selfKin = ego.GetLongitudinalKinematics();
// double currentPosition = selfKin.position;
// double currentVelocity = selfKin.velocity;
// double currentAccel = selfKin.acceleration;
// size_t aheadID, behindID;
// bool haveAhead = TryGetVehicleAhead(predictions, ego, lane, aheadID);
// bool haveBehind = TryGetVehicleBehind(predictions, ego, lane, behindID);
// double nextVelocity = 0.0;
// if (haveAhead && haveBehind)
// {
// // boxed in --> must travel at speed of traffic
// nextVelocity = predictions.at(aheadID)[0].GetLongitudinalVelocity();
// }
// else
// {
// // compute constraints on next velocity:
// // 1. don't exceed the legal speed limit
// // 2. don't exceed safe acceleration limits of vehicle
// // 3. maintain safe distance from vehicle ahead (if there is a vehicle ahead)
// double targetVelocity = _highwayParams.SpeedLimit - _drivingParams.SpeedLimitBuffer;
// double safetyConstraint = currentVelocity + _drivingParams.AccelerationLimit;
// double trafficConstraint = numeric_limits<double>::max();
// if (haveAhead)
// {
// // maintain buffer behind vehicle ahead of us
// double aheadPos = predictions.at(aheadID)[1].GetLongitudinalPosition();
// double bufferDist = selfKin.PositionAt(_drivingParams.TrailBufferTime) - currentPosition;
// trafficConstraint = (aheadPos - bufferDist - (currentPosition + 0.5*currentAccel));
// }
// // next velocity = max velocity satisfying all constraints
// nextVelocity = min(min(safetyConstraint, trafficConstraint), targetVelocity);
// }
// Kinematics accelKin(currentPosition, currentVelocity, nextVelocity - currentVelocity);
// return accelKin.Predict(1.0);
// }
// Kinematics BehaviorPlanner::GetLaneKinematics(
// const Vehicle &ego,
// const vector<Vehicle> &others,
// size_t lane,
// double dt) const
// {
// double egoPos = ego.Position();
// double egoVel = ego.Velocity();
// double egoAcc = ego.Acceleration();
// size_t indexAhead, indexBehind;
// double timeAhead, timeBehind;
// bool haveAhead = TryGetVehicleAhead(ego, others, lane, indexAhead, timeAhead);
// bool haveBehind = TryGetVehicleBehind(ego, others, lane, indexBehind, timeBehind);
// double newAccel = 0;
// if (haveAhead && haveBehind && (timeAhead < 2) && (timeBehind < 2))
// {
// // boxed in, accelerate to match speed of vehicle ahead
// newAccel = (others[indexAhead].Velocity() - egoVel) / dt;
// cout << "boxed in" << endl;
// }
// else
// {
// // by default accelerate to reach target velocity
// double targetVelocity = _highwayParams.SpeedLimit - _drivingParams.SpeedLimitBuffer;
// double accelToTargetVelocity = (targetVelocity - egoVel) / dt;
// double accelToSafeDistance = numeric_limits<double>::max();
// // maintain safe distance behind vehicle ahead of us
// if (haveAhead && (timeAhead < 3))
// {
// const Vehicle &vehAhead = others[indexAhead];
// double vehPos = vehAhead.Position();
// double vehVel = vehAhead.Velocity();
// double vehAcc = vehAhead.Acceleration();
// double B = _drivingParams.FollowBuffer;
// accelToSafeDistance = ((vehPos + vehVel*dt + 0.5*vehAcc*dt*dt) - (egoPos + egoVel*dt) - B) * 2 / (dt*dt);
// cout << "maintain safe distance" << endl;
// }
// newAccel = min(accelToTargetVelocity, accelToSafeDistance);
// }
// // enforce acceleration & jerk limits
// double Amax = _drivingParams.AccelerationLimit;
// double Jmax = _drivingParams.JerkLimit;
// newAccel = clamp(newAccel, -Amax, Amax);
// //newAccel = clamp(newAccel, egoAcc - Jmax*dt, egoAcc + Jmax*dt);
// Kinematics newKin(egoPos, egoVel, newAccel);
// return newKin.Predict(dt);
// }
double BehaviorPlanner::GetLaneVelocity(
const Vehicle &ego,
const vector<Vehicle> &others,
size_t lane) const
{
size_t indexAhead, indexBehind;
double distAhead, timeAhead, distBehind, timeBehind;
bool haveAhead = TryGetVehicleAhead(ego, others, lane, indexAhead, distAhead, timeAhead);
bool haveBehind = TryGetVehicleBehind(ego, others, lane, indexBehind, distBehind, timeBehind);
double lane_velocity = _highwayParams.SpeedLimit - _drivingParams.SpeedLimitBuffer;
if (haveAhead && haveBehind && (timeAhead < 2) && (timeBehind < 2))
{
// boxed in, accelerate to match speed of vehicle ahead
lane_velocity = others[indexAhead].Velocity();
cout << "boxed in" << endl;
}
else if (haveAhead && (timeAhead < 3))
{
lane_velocity = min(lane_velocity, others[indexAhead].Velocity());
cout << "maintain safe distance" << endl;
}
return lane_velocity;
}
bool BehaviorPlanner::TryGetVehicleAhead(
const Vehicle &ego,
const vector<Vehicle> &others,
size_t lane,
size_t &index,
double &dist_ahead,
double &time_ahead) const
{
const bool LOOK_AHEAD = true;
if (!TryGetNearestVehicle(ego, others, lane, LOOK_AHEAD, index))
return false;
dist_ahead = DistanceBehind(ego, others[index]);
time_ahead = dist_ahead / ego.Velocity();
return true;
}
bool BehaviorPlanner::TryGetVehicleBehind(
const Vehicle &ego,
const vector<Vehicle> &others,
size_t lane,
size_t &index,
double &dist_behind,
double &time_behind) const
{
const bool LOOK_BEHIND = false;
if (!TryGetNearestVehicle(ego, others, lane, LOOK_BEHIND, index))
return false;
dist_behind = DistanceBehind(others[index], ego);
time_behind = dist_behind / others[index].Velocity();
return true;
}
bool BehaviorPlanner::TryGetNearestVehicle(
const Vehicle &ego,
const vector<Vehicle> &others,
size_t lane,
bool look_ahead,
size_t &index) const
{
double nearest_dist = numeric_limits<double>::max();
bool found = false;
for (size_t i=0; i < others.size(); i++)
{
const Vehicle &other = others[i];
if (GetLane(other) == lane)
{
double dist = look_ahead ? DistanceBehind(ego, other) : DistanceBehind(other, ego);
if (dist < nearest_dist)
{
found = true;
index = i;
nearest_dist = dist;
}
}
}
return found;
}
// double EgoVehicle::TrajectoryCost(
// const VehicleTrajectory &traj,
// const VehiclePredictions &predictions) const
// {
// return EfficiencyCost(traj[1].GetLongitudinalVelocity());
// }
// double EgoVehicle::EfficiencyCost(double velocity) const
// {
// const double SPEED_LIMIT = _highwayParams.SpeedLimit;
// const double BUFFER_VELOCITY = _drivingParams.SpeedLimitBuffer;
// const double TARGET_VELOCITY = SPEED_LIMIT - BUFFER_VELOCITY;
// const double STOP_COST = _drivingParams.StopCost;
// if (velocity < TARGET_VELOCITY)
// {
// return STOP_COST * ((TARGET_VELOCITY - velocity) / TARGET_VELOCITY);
// }
// else if (velocity < SPEED_LIMIT)
// {
// return (velocity - TARGET_VELOCITY) / BUFFER_VELOCITY;
// }
// return 1.0;
// }
// double EgoVehicle::TrajectoryCost(double intendedSpeed, double finalSpeed) const
// {
// double costIntended = SpeedCost(intendedSpeed);
// double costFinal = SpeedCost(finalSpeed);
// if (costIntended == 1.0 || costFinal == 1.0)
// return 1.0;
// return (costIntended + costFinal) / 2.0;
// }
// double BehaviorPlanner::TrajectoryCost(
// const Vehicle &ego,
// const Vehicle &next,
// const vector<Vehicle> &others,
// Behavior behavior) const
// {
// size_t intendedLane = ego.Lane();
// size_t finalLane = next.Lane();
// double dt = next.Time() - ego.Time();
// if (behavior == PrepareLaneChangeLeft || behavior == LaneChangeLeft) {
// intendedLane--;
// }
// else if (behavior == PrepareLaneChangeRight || behavior == LaneChangeRight) {
// intendedLane++;
// }
// double intendedSpeed = GetLaneKinematics(ego, others, intendedLane, dt).velocity;
// double finalSpeed = GetLaneKinematics(ego, others, finalLane, dt).velocity;
// double costIntended = SpeedCost(intendedSpeed);
// double costFinal = SpeedCost(finalSpeed);
// cout << BehaviorLabel(behavior) << endl;
// cout << " intended speed: " << intendedSpeed << ", cost: " << costIntended << endl;
// cout << " final speed: " << finalSpeed << ", cost: " << costFinal << endl;
// // if (costIntended == 1.0 || costFinal == 1.0)
// // return 1.0;
// //return (costIntended + costFinal) / 2.0;
// return (costIntended + costFinal);
// }
size_t BehaviorPlanner::IntendedLane(const Vehicle &ego, Behavior behavior) const
{
bool change_left = (behavior == PrepareLaneChangeLeft || behavior == LaneChangeLeft);
bool change_right = (behavior == PrepareLaneChangeRight || behavior == LaneChangeRight);
int lane_change_offs = change_left ? -1 : (change_right ? 1 : 0);
return _highwayParams.WhichLane(ego.LateralPosition()) + lane_change_offs;
}
size_t BehaviorPlanner::FinalLane(Trajectory traj) const
{
return _highwayParams.WhichLane(traj.goal_lateral_position);
}
double BehaviorPlanner::TrajectoryCost(
const Vehicle &ego,
const vector<Vehicle> &others,
Behavior behavior,
Trajectory traj) const
{
const double WEIGHT_TRAFFIC_AHEAD = 10.0;
const double WEIGHT_TRAFFIC_BEHIND = 10.0;
const double WEIGHT_INTENDED_SPEED = 1.0;
const double WEIGHT_FINAL_SPEED = 0.5;
double total_cost = 0.0;
double traffic_ahead_cost = TrafficAheadCost(ego, others, behavior, traj);
total_cost += WEIGHT_TRAFFIC_AHEAD * traffic_ahead_cost;
double traffic_behind_cost = TrafficBehindCost(ego, others, behavior, traj);
total_cost += WEIGHT_TRAFFIC_BEHIND * traffic_behind_cost;
double intended_speed_cost = IntendedLaneSpeedCost(ego, others, behavior, traj);
total_cost += WEIGHT_INTENDED_SPEED * intended_speed_cost;
double final_speed_cost = FinalLaneSpeedCost(ego, others, behavior, traj);
total_cost += WEIGHT_FINAL_SPEED * final_speed_cost;
cout << BehaviorLabel(behavior) << endl;
cout << " traffic ahead cost: " << traffic_ahead_cost << endl;
cout << " traffic behind cost: " << traffic_behind_cost << endl;
cout << " intended lane cost: " << intended_speed_cost << endl;
cout << " final lane cost: " << final_speed_cost << endl;
return total_cost;
}
double BehaviorPlanner::SpeedCost(double speed) const
{
const double SPEED_LIMIT = _highwayParams.SpeedLimit;
const double SPEED_BUFFER = _drivingParams.SpeedLimitBuffer;
const double TARGET_SPEED = SPEED_LIMIT - SPEED_BUFFER;
const double STOP_COST = _drivingParams.StopCost;
if (speed < TARGET_SPEED)
{
return STOP_COST * ((TARGET_SPEED - speed) / TARGET_SPEED);
}
else if (speed < SPEED_LIMIT)
{
return (speed - TARGET_SPEED) / SPEED_BUFFER;
}
return 1.0;
}
double BehaviorPlanner::IntendedLaneSpeedCost(
const Vehicle &ego,
const vector<Vehicle> &others,
Behavior behavior,
Trajectory traj) const
{
size_t intended_lane = IntendedLane(ego, behavior);
double intended_speed = GetLaneVelocity(ego, others, intended_lane);
return SpeedCost(intended_speed);
}
double BehaviorPlanner::FinalLaneSpeedCost(
const Vehicle &ego,
const vector<Vehicle> &others,
Behavior behavior,
Trajectory traj) const
{
size_t final_lane = FinalLane(traj);
double final_speed = GetLaneVelocity(ego, others, final_lane);
return SpeedCost(final_speed);
}
double BehaviorPlanner::TrafficAheadCost(
const Vehicle &ego,
const vector<Vehicle> &others,
Behavior behavior,
Trajectory traj) const
{
size_t final_lane = FinalLane(traj);
size_t index;
double dist_ahead, time_ahead;
if (TryGetVehicleAhead(ego, others, final_lane, index, dist_ahead, time_ahead))
{
time_ahead = dist_ahead / traj.goal_velocity;
if (time_ahead < 1)
return 1.0;
if (time_ahead < 3)
return 1.5 - 0.5*time_ahead;
}
return 0.0;
}
double BehaviorPlanner::TrafficBehindCost(
const Vehicle &ego,
const vector<Vehicle> &others,
Behavior behavior,
Trajectory traj) const
{
size_t final_lane = FinalLane(traj);
size_t index;
double dist_behind, time_behind;
if (TryGetVehicleBehind(ego, others, final_lane, index, dist_behind, time_behind))
{
if (time_behind < 1)
return 1.0;
if (time_behind < 3)
return 1.5 - 0.5*time_behind;
}
return 0.0;
}
| 33.415162 | 126 | 0.652766 | [
"vector"
] |
bbc30d49f60cfea00a85a8813c65c5bb12186d1a | 659 | cpp | C++ | Sid's Contests/LeetCode contests/Weekly Contest 254/Array With Elements Not Equal to Average of Neighbors.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 14 | 2021-08-22T18:21:14.000Z | 2022-03-08T12:04:23.000Z | Sid's Contests/LeetCode contests/Weekly Contest 254/Array With Elements Not Equal to Average of Neighbors.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 1 | 2021-10-17T18:47:17.000Z | 2021-10-17T18:47:17.000Z | Sid's Contests/LeetCode contests/Weekly Contest 254/Array With Elements Not Equal to Average of Neighbors.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 5 | 2021-09-01T08:21:12.000Z | 2022-03-09T12:13:39.000Z | class Solution {
public:
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
vector<int> rearrangeArray(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ind = 0, n = nums.size();
vector<int> res;
int l = 0, r = n-1;
while(l <= r)
{
if(ind%2 == 0)
{
res.push_back(nums[l++]);
ind++;
}
else
{
res.push_back(nums[r--]);
ind++;
}
}
return res;
}
};
| 23.535714 | 69 | 0.424886 | [
"vector"
] |
bbd3f9b11fb2551c18f4cdcff0bf96028343fb28 | 19,487 | cpp | C++ | src/ising/solver.cpp | dkitch/maxsat-ising | ef6fe68f73e23b6d5729786a77aa468c4250f9b8 | [
"MIT"
] | 13 | 2016-10-27T22:56:45.000Z | 2022-03-06T12:48:02.000Z | src/ising/solver.cpp | dkitch/maxsat-ising | ef6fe68f73e23b6d5729786a77aa468c4250f9b8 | [
"MIT"
] | null | null | null | src/ising/solver.cpp | dkitch/maxsat-ising | ef6fe68f73e23b6d5729786a77aa468c4250f9b8 | [
"MIT"
] | 2 | 2016-10-23T15:13:44.000Z | 2021-08-30T11:51:33.000Z | #include "solver.h"
using namespace std;
using namespace ::boost::tuples;
using namespace ::boost;
void run_solver(int max_sites,
map< set< tuple<int,int,int,int,int> >, double> &J,
map< set< tuple<int,int,int,int,int> >, double> &lowerboundclustertype,
map< set< tuple<int,int,int,int,int> >, double> &upperboundclustertype,
map< tuple<int,int,int,int>, int> &cellrepresentation,
double &lower_bound,
double &exact_lower_bound,
double &upper_bound,
map< tuple<int,int,int,int>, int> &unitcell,
tuple<int,int,int,int,int,int> &periodicity,
map< set< tuple<int,int,int,int,int> >, double> &J_for_proof,
std::string id,
double prec,
int num_loops,
bool basic_exact_mode,
bool pseudo_mode,
bool pseudo_mode_with_proof,
bool verbose,
bool very_verbose,
bool obscenely_verbose) {
if (!((basic_exact_mode && !pseudo_mode && !pseudo_mode_with_proof) ||
(!basic_exact_mode && pseudo_mode && pseudo_mode_with_proof) ||
(!basic_exact_mode && pseudo_mode && !pseudo_mode_with_proof))){
cout << "Invalid choice of solver mode! Exiting." << endl;
exit(1);
}
// If verbose, print back basic input
if (verbose){
cout << "(" << id <<") %%%%%%%%%%%%%%%%%%%% Solver %%%%%%%%%%%%%%%%%%%%%" << endl;
cout << "(" << id <<") -------------------- Input ----------------------" << endl;
if(basic_exact_mode){
cout << "Basic exact mode" << endl;
}else if (pseudo_mode && !pseudo_mode_with_proof){
cout << "Pseudo mode (no proof)" << endl;
}else if (pseudo_mode && pseudo_mode_with_proof){
cout << "Pseudo mode (with proof)" << endl;
}
cout << "Precision: " << prec << endl;
cout << "(" << id <<") J: " << endl;
printmapfromsets(J);
cout << "(" << id <<") Solver: " << endl;
cout << "(" << id <<") -------------------------------------------------" << endl;
}
// Convert J to integers
map< set< tuple<int,int,int,int,int> >, double> Ji;
map< set< tuple<int,int,int,int,int> >, double>::iterator Jit;
for (Jit = J.begin(); Jit != J.end(); ++Jit){
Ji[Jit->first] = (double)((long long)(Jit->second / prec));
}
// Calculate basic block size and dimension (in species)
map<int,int> components;
int x_range, y_range, z_range;
calculate_range_from_J(Ji, x_range, y_range, z_range, components);
// Solve optimization problem
if(verbose){
cout << "(" << id <<") Solving optimization problem ..." << endl;
}
corecode(components, x_range, y_range, z_range, max_sites, num_loops,
Ji,
lowerboundclustertype, upperboundclustertype, cellrepresentation,
lower_bound, upper_bound, unitcell, periodicity, J_for_proof,
id, pseudo_mode, pseudo_mode_with_proof, basic_exact_mode,
very_verbose, obscenely_verbose);
// If necessary, prove lower bound convergence
if (pseudo_mode_with_proof){
if(verbose){
cout << "(" << id <<") Proving correctness ..." << endl;
cout << "(" << id <<") J for proof: " << endl;
printmapfromsets(J_for_proof);
}
calculate_range_from_J(J_for_proof, x_range, y_range, z_range, components);
map< tuple<int, int, int, int>, int> tempspin;
map< tuple<int, int, int, int, int, int>,
map<set<tuple<int, int, int, int, int> >, double> > temp_clustertype_periodic;
double temp_LB_so_far = lower_bound;
get_lowerbound_sub(x_range, 0, y_range, 0, 0, z_range,
J_for_proof,
x_range, y_range, z_range, components,
tempspin,
exact_lower_bound,
temp_clustertype_periodic,
temp_LB_so_far, id,
false, false, true, obscenely_verbose);
}
upper_bound = upper_bound * prec;
lower_bound = lower_bound * prec;
exact_lower_bound = exact_lower_bound * prec;
// Output results
if (verbose){
cout << "(" << id <<") ------------------- Results --------------------" << endl;
if(basic_exact_mode){
cout << "(" << id <<") UB: " << upper_bound << "; LB: " << lower_bound << endl;
}else if(!pseudo_mode_with_proof){
cout << "(" << id <<") UB: " << upper_bound << "; Pseudo-LB: " << lower_bound << endl;
}else{
cout << "(" << id <<") UB: " << upper_bound << "; Pseudo-LB: " << lower_bound << "; Exact-LB: " << exact_lower_bound << endl;
}
cout << "(" << id <<") Correlations: ";
printmapfromsets(upperboundclustertype);
cout << "\n(" << id <<") Unit cell: ";
printblock(unitcell);
cout << "\n(" << id <<") Periodicity: " << periodicity << endl;
cout << "(" << id <<") --------------------- Done --------------------\n" << endl;
}
}
void corecode(map<int, int> component,
int x_range, int y_range, int z_range,
int max_sites,
int loopnumber,
map<set<tuple<int,int,int,int,int> >, double> &J,
map<set<tuple<int,int,int,int,int> >, double> &lowerboundclustertype,
map<set<tuple<int,int,int,int,int> >, double> &upperboundclustertype,
map<tuple<int,int,int,int>,int> &cellrepresentation,
double &lower_bound, double &upper_bound,
map<tuple<int,int,int,int>,int> &unitcell,
tuple<int,int,int,int,int,int> &periodicity,
map<set<tuple<int,int,int,int,int> >, double> &J_for_proof,
std::string id,
bool pseudo_mode,
bool pseudo_mode_with_proof,
bool basic_exact_mode,
bool very_verbose,
bool obscenely_verbose) {
map<tuple<int,int,int,int,int,int>, map<tuple<int,int,int,int>,int> > spin_periodic, spin_lowerbound;
map<tuple<int,int,int,int,int,int>, double > energy_periodic,energy_lowerbound;
int dimension;
double lowerbound_from_compat = -1e18;
double min_bound = -1e18, max_bound = 0;
set<tuple<int,int,int,int,int,int> > min_list, max_list;
int a0, a1, a2, a3, a4, a5;
set<tuple<int,int,int,int,int,int> > setoftupletemp;
map<tuple<int,int,int,int,int,int>, map<set<tuple<int,int,int,int,int> >, double> > clustertype_periodic;
map<tuple<int,int,int,int,int,int>, map<set<tuple<int,int,int,int,int> >, double> > clustertype_lowerbound;
if (!((basic_exact_mode && !pseudo_mode && !pseudo_mode_with_proof) ||
(!basic_exact_mode && pseudo_mode && pseudo_mode_with_proof) ||
(!basic_exact_mode && pseudo_mode && !pseudo_mode_with_proof))){
cout << "Invalid choice of solver mode! Exiting." << endl;
exit(1);
}
// Identify dimensionality of the problem
if (z_range == 1 && y_range == 1) {
dimension = 1;
if (very_verbose) { cout << "1D algorithm activated" << endl; }
}else if (z_range == 1){
dimension = 2;
if (very_verbose) { cout << "2D algorithm activated" << endl; }
}else{
dimension = 3;
if (very_verbose) { cout << "3D algorithm activated" << endl; }
}
// Obtain lower bound estimate on the energy
if (loopnumber > 0){
if (dimension == 1) {
a0=loopnumber;
a1=0;
a2=1;
a3=0;
a4=0;
a5=1;
}else if (dimension == 2) {
a0=loopnumber;
a1=0;
a2=loopnumber;
a3=0;
a4=0;
a5=1;
}else if (dimension == 3) {
a0=loopnumber;
a1=0;
a2=loopnumber;
a3=0;
a4=0;
a5=loopnumber;
}
// Attempt to solve lower bound problem
get_lowerbound(a0, a1, a2, a3, a4, a5, J, x_range, y_range, z_range,
component, spin_lowerbound[make_tuple(a0,a1,a2,a3,a4,a5)],
energy_lowerbound[make_tuple(a0,a1,a2,a3,a4,a5)],
clustertype_lowerbound, J_for_proof, id,
pseudo_mode, pseudo_mode_with_proof, basic_exact_mode,
obscenely_verbose);
findminmax(energy_lowerbound, min_bound, max_bound);
matchnumber(energy_lowerbound, max_bound, max_list);
lowerbound_from_compat=max_bound;
if(very_verbose){
cout << "******************************************************************************" << endl;
cout << "LB: " << endl;
printmap(energy_lowerbound);
cout << "LB solution: " << endl;
for (set<tuple<int,int,int,int,int,int> >::iterator ait=max_list.begin(); ait!=max_list.end(); ait++){
tuple<int,int,int,int,int,int> a;
a=*ait;
cout << "\n" << a;
printblock(spin_lowerbound[a]);
}
cout << "\nLB maximum is: " << max_bound << endl;
cout << "LB maximum list: ";
printvector(max_list);
cout << "\nAbsolute LB: " << lowerbound_from_compat << endl;
}
}
// Obtain upper bound estimate on the energy
if (max_sites > 0){
for (int alpha=1; alpha < max_sites+1; alpha++){
double dump1;
findminmax(energy_periodic, min_bound, dump1);
matchnumber(energy_periodic, min_bound, min_list);
if (min_bound <= lowerbound_from_compat+1) { break; }
if (dimension == 1) {
a0=alpha;
a1=0;
a2=1;
a3=0;
a4=0;
a5=1;
if (pseudo_mode) {
periodic(a0,a1,a2, a3,a4,a5,
J,
x_range,y_range,z_range, component,
spin_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
energy_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
clustertype_periodic, min_bound, id,
true, false, false,
obscenely_verbose);
}else if (basic_exact_mode){
periodic(a0,a1,a2, a3,a4,a5,
J,
x_range,y_range,z_range, component,
spin_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
energy_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
clustertype_periodic, min_bound, id,
false, true, false,
obscenely_verbose);
}
double dump1;
findminmax(energy_periodic, min_bound, dump1);
matchnumber(energy_periodic, min_bound, min_list);
if (very_verbose){
cout << "\nUB: " << min_bound << ", LB: " << lowerbound_from_compat << "; Periodicity: ";
printvector(min_list);
cout << endl;
}
}else if (dimension == 2) {
a3=0;
a4=0;
a5=1;
for (int a2 = 1; a2 < alpha+1; a2++){
if (alpha % a2 == 0) {
a0 = alpha/a2;
for (int a1=0; a1<a0; a1++) {
if (pseudo_mode) {
periodic(a0, a1, a2, a3, a4, a5,
J, x_range, y_range, z_range, component,
spin_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
energy_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
clustertype_periodic, min_bound, id,
true, false, false,
obscenely_verbose);
}else if (basic_exact_mode){
periodic(a0, a1, a2, a3, a4, a5,
J, x_range, y_range, z_range, component,
spin_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
energy_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
clustertype_periodic, min_bound, id,
false, true, false,
obscenely_verbose);
}
double dump1;
findminmax(energy_periodic, min_bound, dump1);
matchnumber(energy_periodic, min_bound, min_list);
if (very_verbose){
cout << "\nUB: " << min_bound << ", LB: " << lowerbound_from_compat << "; Periodicity: ";
printvector(min_list);
cout << endl;
}
}
}
}
}else if (dimension == 3){
for (int beta = 1; beta < alpha + 1; beta++) {
if (alpha % beta == 0) {
a0 = alpha/beta;
for (int gamma = 1; gamma < beta+1; gamma++){
if (beta % gamma == 0) {
a2 = beta/gamma;
a5 = gamma;
for (a4 = 0; a4 < a2; a4++) {
for (a3 = 0; a3 < a0; a3++) {
for (a1 = 0; a1 < a0; a1++) {
if (pseudo_mode) {
periodic(a0, a1, a2, a3, a4, a5,
J, x_range, y_range, z_range, component,
spin_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
energy_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
clustertype_periodic, min_bound, id,
true, false, false,
obscenely_verbose);
}
else if (basic_exact_mode){
periodic(a0, a1, a2, a3, a4, a5,
J, x_range, y_range, z_range, component,
spin_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
energy_periodic[make_tuple(a0,a1,a2,a3,a4,a5)],
clustertype_periodic, min_bound, id,
false, true, false,
obscenely_verbose);
}
double dump1;
findminmax(energy_periodic, min_bound, dump1);
matchnumber(energy_periodic, min_bound, min_list);
if (very_verbose){
cout << "\nUB: " << min_bound << ", LB: " << lowerbound_from_compat << "; Periodicity: ";
printvector(min_list);
cout << endl;
}
}
}
}
}
}
}
}
}
}
double dump1;
findminmax(energy_periodic, min_bound, dump1);
matchnumber(energy_periodic, min_bound, min_list);
if (very_verbose){
cout << "******************************************************************************" << endl;
cout << "UB: " << endl;
printmap(energy_lowerbound);
if (loopnumber > 0){
cout << "LB solution: " << endl;
for (set<tuple<int,int,int,int,int,int> >::iterator ait=max_list.begin(); ait!=max_list.end(); ait++){
tuple<int,int,int,int,int,int> a;
a = *ait;
cout << "\n" << a;
printblock(spin_lowerbound[a]);
}
}
cout << "UB solution: " << endl;
for (set<tuple<int,int,int,int,int,int> >::iterator ait=min_list.begin(); ait!=min_list.end(); ait++){
tuple<int,int,int,int,int,int> a;
a = *ait;
cout << "\n" << a;
printblock(spin_periodic[a]);
}
cout << "\nUB minimum is: " << min_bound << endl;
cout << "\nAbsolute LB: " << lowerbound_from_compat << endl;
cout << "UB minimum list: ";
printvector(min_list);
cout << "LB maximum list: ";
printvector(max_list);
cout << endl;
}
}
// Output final results
lower_bound = lowerbound_from_compat;
upper_bound = min_bound;
lowerboundclustertype = clustertype_lowerbound[*(max_list.begin())];
upperboundclustertype = clustertype_periodic[*(min_list.begin())];
periodicity = *(min_list.begin());
unitcell = spin_periodic[periodicity];
}
void calculate_range_from_J(map<set<tuple<int,int,int,int,int> >, double> &J,
int &x_range,int &y_range,int &z_range,
map<int, int>&component) {
int xmax=0;
int ymax=0;
int zmax=0;
for (map<set<tuple<int,int,int,int,int> >, double>::iterator it=J.begin(); it!=J.end(); it++) {
set<tuple<int,int,int,int,int> > tuple_set_temp=it->first;
for (set<tuple<int,int,int,int,int> >::iterator itv=tuple_set_temp.begin(); itv!=tuple_set_temp.end(); itv++) {
if (xmax<(*itv).get<0>()) {
xmax=(*itv).get<0>();
}
if (ymax<(*itv).get<1>()) {
ymax=(*itv).get<1>();
}
if (zmax<(*itv).get<2>()) {
zmax=(*itv).get<2>();
}
int location=(*itv).get<3>();
int elementtype=(*itv).get<4>();
if (component.count(location)==0) {
component[location]=elementtype+1;
}
else if (component[location]<elementtype+1)
{
component[location]=elementtype+1;
}
}
}
x_range=xmax;
y_range=ymax;
z_range=zmax;
}
| 43.400891 | 137 | 0.445169 | [
"3d"
] |
bbd6e5692c9fd3f874c14fb7b623006c1e90114c | 1,791 | cpp | C++ | iterative/Juez07/Source.cpp | albertopastormr/algorithms_eda | ecbd815dbbafb1e69ca74bd92cd94be0d7d9857d | [
"MIT"
] | null | null | null | iterative/Juez07/Source.cpp | albertopastormr/algorithms_eda | ecbd815dbbafb1e69ca74bd92cd94be0d7d9857d | [
"MIT"
] | null | null | null | iterative/Juez07/Source.cpp | albertopastormr/algorithms_eda | ecbd815dbbafb1e69ca74bd92cd94be0d7d9857d | [
"MIT"
] | 1 | 2018-11-02T13:52:28.000Z | 2018-11-02T13:52:28.000Z | // Alberto Pastor Moreno
// E46
// Coste Lineal
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
/*
method seqBlancos( v: array<string>) returns( ini : int, fin : int)
requires v != null && v.Length > 0
ensures sum(v[ini..fin+1]) == sumMaxima(v[..])
*/
struct tIntervalo
{
int ini, fin;
};
tIntervalo resolver(std::vector<std::string> const & v) {
tIntervalo sol;
sol.ini = 0;
sol.fin = -1;
int iniaux = 0, finaux = -1;
for (int x = 0; x < v.size(); x++)
{
if (v[x] == "FFFFFF")
{
finaux = x;
}
else
{
iniaux = x+1;
}
if (sol.fin - sol.ini < finaux - iniaux)
{
sol.fin = finaux;
sol.ini = iniaux;
}
}
return sol; // Sacar ambas posiciones con struct para imprimir fuera de resolver ?
}
// Resuelve un caso de prueba, leyendo de la entrada la
// configuración, y escribiendo la respuesta
bool resuelveCaso(bool endline) {
int numF, numC;
std::cin >> numF >> numC;
if (!std::cin)
return false;
if (endline)
{
std::cout << "\n";
}
for (int i = 0; i < numF;i++)
{
std::vector<std::string> v;
std::string elem;
for (int j = 0; j < numC; j++)
{
std::cin >> elem;
v.push_back(elem);
}
tIntervalo sol = resolver(v);
std::cout << sol.ini << " " << sol.fin << "\n";
}
return true;
}
int main() {
// Para la entrada por fichero.
// Comentar para acepta el reto
#ifndef DOMJUDGE
std::ifstream in("datos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt
#endif
bool endline = false;
while (resuelveCaso(endline))
{
endline = true;
}
// Para restablecer entrada. Comentar para acepta el reto
#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
} | 20.123596 | 92 | 0.621999 | [
"vector"
] |
bbd8352152c5626e0161e1afcd064639fea67ecd | 195 | cpp | C++ | c++/TC/SRM/570/Div2/500.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null | c++/TC/SRM/570/Div2/500.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null | c++/TC/SRM/570/Div2/500.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null |
#include <array>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
class {
static
static void test() {
}
};
int main() {
}
| 7.222222 | 22 | 0.507692 | [
"vector"
] |
bbdc6f3ffd83159ad98c5c730c4fa8f4d45a5da9 | 2,962 | cpp | C++ | tests/DataTests.cpp | hnord-vdx/wallet-core | 21b3db0240622234d05854263b9e125c1001e870 | [
"MIT"
] | 263 | 2019-02-14T22:45:57.000Z | 2019-08-07T14:47:58.000Z | tests/DataTests.cpp | hnord-vdx/wallet-core | 21b3db0240622234d05854263b9e125c1001e870 | [
"MIT"
] | 414 | 2019-02-16T21:19:32.000Z | 2019-08-07T19:09:45.000Z | tests/DataTests.cpp | hnord-vdx/wallet-core | 21b3db0240622234d05854263b9e125c1001e870 | [
"MIT"
] | 172 | 2019-02-18T03:36:55.000Z | 2019-08-07T08:48:05.000Z | // Copyright © 2017-2022 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "Data.h"
#include "HexCoding.h"
#include <gtest/gtest.h>
using namespace std;
using namespace TW;
TEST(DataTests, fromVector) {
const Data data = {1, 2, 3};
EXPECT_EQ(data.size(), 3);
EXPECT_EQ(data[1], 2);
EXPECT_EQ(hex(data), "010203");
}
TEST(DataTests, fromHex) {
const Data data = parse_hex("01020304");
EXPECT_EQ(data.size(), 4);
EXPECT_EQ(hex(data), "01020304");
}
TEST(DataTests, fromString) {
const Data data = TW::data(std::string("ABC"));
EXPECT_EQ(data.size(), 3);
EXPECT_EQ(hex(data), "414243");
}
TEST(DataTests, fromBytes) {
const std::vector<TW::byte> vec = {1, 2, 3};
const Data data = TW::data(vec.data(), vec.size());
EXPECT_EQ(data.size(), 3);
EXPECT_EQ(hex(data), "010203");
}
TEST(DataTests, padLeft) {
Data data = parse_hex("01020304");
pad_left(data, 10);
EXPECT_EQ(data.size(), 10);
EXPECT_EQ(hex(data), "00000000000001020304");
}
TEST(DataTests, append) {
Data data1 = parse_hex("01020304");
const Data data2 = parse_hex("aeaf");
append(data1, data2);
EXPECT_EQ(data1.size(), 6);
EXPECT_EQ(hex(data1), "01020304aeaf");
}
TEST(DataTests, appendByte) {
Data data1 = parse_hex("01020304");
append(data1, 5);
EXPECT_EQ(data1.size(), 5);
EXPECT_EQ(hex(data1), "0102030405");
}
TEST(DataTests, subData) {
const Data data = parse_hex("0102030405060708090a");
EXPECT_EQ(data.size(), 10);
EXPECT_EQ(hex(subData(data, 2, 3)), "030405");
EXPECT_EQ(hex(subData(data, 0, 10)), "0102030405060708090a");
EXPECT_EQ(hex(subData(data, 3, 1)), "04");
EXPECT_EQ(hex(subData(data, 3, 0)), "");
EXPECT_EQ(hex(subData(data, 200, 3)), ""); // index too big
EXPECT_EQ(hex(subData(data, 2, 300)), "030405060708090a"); // length too big
EXPECT_EQ(hex(subData(data, 200, 300)), ""); // index & length too big
EXPECT_EQ(hex(subData(data, 3)), "0405060708090a");
EXPECT_EQ(hex(subData(data, 0)), "0102030405060708090a");
EXPECT_EQ(hex(subData(data, 200)), ""); // index too big
}
TEST(DataTests, hasPrefix) {
const Data data = parse_hex("0102030405060708090a");
const Data prefix11 = parse_hex("010203");
EXPECT_TRUE(has_prefix(data, prefix11));
const Data prefix12 = parse_hex("01");
EXPECT_TRUE(has_prefix(data, prefix12));
const Data prefix13 = parse_hex("0102030405060708090a");
EXPECT_TRUE(has_prefix(data, prefix13));
const Data prefix21 = parse_hex("020304");
EXPECT_FALSE(has_prefix(data, prefix21));
const Data prefix22 = parse_hex("02");
EXPECT_FALSE(has_prefix(data, prefix22));
const Data prefix23 = parse_hex("bb");
EXPECT_FALSE(has_prefix(data, prefix23));
}
| 30.536082 | 80 | 0.662728 | [
"vector"
] |
bbf0318c4634f84c5bcdbe457f970fec229d4c04 | 3,028 | cpp | C++ | src/gripper/serial/fiveFingerSerialGripper.cpp | HSRobot/hiropV3 | 3f094035229708302aec976cfb252f7bcdb7cd3f | [
"BSD-3-Clause"
] | null | null | null | src/gripper/serial/fiveFingerSerialGripper.cpp | HSRobot/hiropV3 | 3f094035229708302aec976cfb252f7bcdb7cd3f | [
"BSD-3-Clause"
] | null | null | null | src/gripper/serial/fiveFingerSerialGripper.cpp | HSRobot/hiropV3 | 3f094035229708302aec976cfb252f7bcdb7cd3f | [
"BSD-3-Clause"
] | null | null | null | #include "fiveFingerSerialGripper.h"
fiveFingerSerialGripper::fiveFingerSerialGripper(){}
int fiveFingerSerialGripper::getForceVal(std::vector<int> &data)
{
unsigned char buffer[] = ARRAY_READ_FORCE_FIVEFINGER_GRIPPER;
int size_buffer = ARRAY_SIZE(buffer);
buffer[size_buffer-1] = getCheckNum(buffer,size_buffer);
ros_ser.write(buffer,size_buffer);
IDebug("Read getForceVal!!");
unsigned char read_buffer[20];
int *force = (int *)malloc(6);
ros_ser.flushInput();
int size_close_buffer = 20;
size_t t =ros_ser.read(read_buffer,size_close_buffer);
int size =static_cast<int>(t);
if(size != size_close_buffer){
IDebug(" Receive from size is not good\n");
return -1;
}
bytes2int(read_buffer,6,force);
data.clear();
data.resize(6);
for(int i = 0; i < 6; i++){
data[i] = (force[i]);
}
free(force);
return 0;
}
int fiveFingerSerialGripper::setMoveSeq(int index)
{
size_t size = 0;
{
unsigned char buffer[] = ARRAY_WRITE_MOVESEQID_FIVEFINGER_GRIPPER;
int size_buffer = ARRAY_SIZE(buffer);
//run id
buffer[size_buffer-2] = index;
//mask
buffer[size_buffer-1] = getCheckNum(buffer,size_buffer);
ros_ser.write(buffer,size_buffer);
IDebug("write setMoveSeq!!");
unsigned char read_buffer[9];
int size_close_buffer = ARRAY_SIZE(read_buffer);
size = ros_ser.read(read_buffer,size_close_buffer );
}
if(size != 9)
return -1;
/**********************************/
{
unsigned char buffer[] = ARRAY_RUN_MOVESEQID_FIVEFINGER_GRIPPER;
int size_buffer = ARRAY_SIZE(buffer);
buffer[size_buffer-1] = getCheckNum(buffer,size_buffer);
ros_ser.write(buffer,size_buffer);
IDebug("Read getForceVal!!");
unsigned char read_buffer[9];
int size_close_buffer = ARRAY_SIZE(read_buffer);
size = ros_ser.read(read_buffer,size_close_buffer );
}
if(size != 9)
return -2;
return 0;
}
int fiveFingerSerialGripper::openGripper()
{
return 0;
}
int fiveFingerSerialGripper::closeGripper()
{
return 0;
}
int fiveFingerSerialGripper::stopGripper()
{
return 0;
}
/*
for i in range(1,7):
if getdata[i*2+5]== 0xff and getdata[i*2+6]== 0xff:
actforce[i-1] = -1
else:
actforce[i-1] = getdata[i*2+5] + (getdata[i*2+6]<<8)
return actforce
*/
int fiveFingerSerialGripper::bytes2int(unsigned char * array, int lens,\
int * outArray)
{
for(int i = 0; i< lens ; i++)
{
if(array[(i+1)*2 + 5] ==0xFF && (array[ (i+1)*2 + 6] ==0xFF ))
outArray[i] = -1;
else
outArray[i] = (int)(array[(i+1)*2 + 5] + ((array[ (i+1)*2 + 6])<<8));
if(outArray[i] > 2000)
outArray[i] -=65535;
}
}
H_EXPORT_PLUGIN(fiveFingerSerialGripper, "fiveFingerSerialGripper", "1.0")
| 24.617886 | 81 | 0.593131 | [
"vector"
] |
bbf310adaa77b65e3b044e5a53acdf1118f81a83 | 7,586 | cc | C++ | test/gtest/ucp/ucp_test.cc | abouteiller/ucx | f4196de7b4be0a78412d548a025d46ec3163767a | [
"BSD-3-Clause"
] | null | null | null | test/gtest/ucp/ucp_test.cc | abouteiller/ucx | f4196de7b4be0a78412d548a025d46ec3163767a | [
"BSD-3-Clause"
] | null | null | null | test/gtest/ucp/ucp_test.cc | abouteiller/ucx | f4196de7b4be0a78412d548a025d46ec3163767a | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED.
* See file LICENSE for terms.
*/
#include "ucp_test.h"
#include <common/test_helpers.h>
extern "C" {
#include <ucs/arch/atomic.h>
}
std::string ucp_test::m_last_err_msg;
std::ostream& operator<<(std::ostream& os, const ucp_test_param& test_param)
{
std::vector<std::string>::const_iterator iter;
const std::vector<std::string>& transports = test_param.transports;
for (iter = transports.begin(); iter != transports.end(); ++iter) {
if (iter != transports.begin()) {
os << ",";
}
os << *iter;
}
return os;
}
ucp_test::ucp_test() {
ucs_status_t status;
status = ucp_config_read(NULL, NULL, &m_ucp_config);
ASSERT_UCS_OK(status);
}
ucp_test::~ucp_test() {
ucp_config_release(m_ucp_config);
}
void ucp_test::cleanup() {
/* disconnect before destroying the entities */
for (ucs::ptr_vector<entity>::const_iterator iter = entities().begin();
iter != entities().end(); ++iter)
{
(*iter)->disconnect();
}
m_entities.clear();
}
void ucp_test::init() {
test_base::init();
const ucp_test_param &test_param = GetParam();
create_entity();
if ("\\self" != test_param.transports.front()) {
create_entity();
}
}
ucp_test_base::entity* ucp_test::create_entity(bool add_in_front) {
entity *e = new entity(GetParam(), m_ucp_config);
if (add_in_front) {
m_entities.push_front(e);
} else {
m_entities.push_back(e);
}
return e;
}
ucp_params_t ucp_test::get_ctx_params() {
ucp_params_t params = { 0, 0, NULL, NULL };
return params;
}
void ucp_test::progress() const {
for (ucs::ptr_vector<entity>::const_iterator iter = entities().begin();
iter != entities().end(); ++iter)
{
(*iter)->progress();
}
}
void ucp_test::short_progress_loop() const {
for (unsigned i = 0; i < 100; ++i) {
progress();
usleep(100);
}
}
std::vector<ucp_test_param>
ucp_test::enum_test_params(const ucp_params_t& ctx_params,
const std::string& name,
const std::string& test_case_name,
...)
{
ucp_test_param test_param;
const char *tl_name;
va_list ap;
test_param.ctx_params = ctx_params;
va_start(ap, test_case_name);
tl_name = va_arg(ap, const char *);
while (tl_name != NULL) {
test_param.transports.push_back(tl_name);
tl_name = va_arg(ap, const char *);
}
va_end(ap);
if (check_test_param(name, test_case_name, test_param)) {
return std::vector<ucp_test_param>(1, test_param);
} else {
return std::vector<ucp_test_param>();
}
}
void ucp_test::set_ucp_config(ucp_config_t *config,
const ucp_test_param& test_param)
{
std::stringstream ss;
ss << test_param;
ucp_config_modify(config, "TLS", ss.str().c_str());
}
void ucp_test::modify_config(const std::string& name, const std::string& value)
{
ucs_status_t status;
status = ucp_config_modify(m_ucp_config, name.c_str(), value.c_str());
if (status == UCS_ERR_NO_ELEM) {
test_base::modify_config(name, value);
} else if (status != UCS_OK) {
UCS_TEST_ABORT("Couldn't modify ucp config parameter: " <<
name.c_str() << " to " << value.c_str() << ": " <<
ucs_status_string(status));
}
}
bool ucp_test::check_test_param(const std::string& name,
const std::string& test_case_name,
const ucp_test_param& test_param)
{
typedef std::map<std::string, bool> cache_t;
static cache_t cache;
if (test_param.transports.empty()) {
return false;
}
cache_t::iterator iter = cache.find(name);
if (iter != cache.end()) {
return iter->second;
}
ucs::handle<ucp_config_t*> config;
UCS_TEST_CREATE_HANDLE(ucp_config_t*, config, ucp_config_release,
ucp_config_read, NULL, NULL);
set_ucp_config(config, test_param);
ucp_context_h ucph;
ucs_status_t status;
{
disable_errors();
status = ucp_init(&test_param.ctx_params, config, &ucph);
restore_errors();
}
bool result;
if (status == UCS_OK) {
ucp_cleanup(ucph);
result = true;
} else if (status == UCS_ERR_NO_DEVICE) {
result = false;
} else {
UCS_TEST_ABORT("Failed to create context (" << test_case_name << "): "
<< ucs_status_string(status));
}
UCS_TEST_MESSAGE << "checking " << name << ": " << (result ? "yes" : "no");
cache[name] = result;
return result;
}
ucs_log_func_rc_t ucp_test::empty_log_handler(const char *file, unsigned line,
const char *function, ucs_log_level_t level,
const char *prefix, const char *message,
va_list ap)
{
if (level == UCS_LOG_LEVEL_ERROR) {
std::string msg;
msg.resize(256);
vsnprintf(&msg[0], msg.size() - 1, message, ap);
msg.resize(strlen(&msg[0]));
m_last_err_msg = msg;
level = UCS_LOG_LEVEL_DEBUG;
}
ucs_log_default_handler(file, line, function, level, prefix, message, ap);
return UCS_LOG_FUNC_RC_STOP;
}
void ucp_test::disable_errors()
{
ucs_log_push_handler((ucs_log_func_t)empty_log_handler);
}
void ucp_test::restore_errors()
{
ucs_log_pop_handler();
}
ucp_test_base::entity::entity(const ucp_test_param& test_param, ucp_config_t* ucp_config) {
ucp_test::set_ucp_config(ucp_config, test_param);
UCS_TEST_CREATE_HANDLE(ucp_context_h, m_ucph, ucp_cleanup, ucp_init,
&test_param.ctx_params, ucp_config);
UCS_TEST_CREATE_HANDLE(ucp_worker_h, m_worker, ucp_worker_destroy,
ucp_worker_create, m_ucph, UCS_THREAD_MODE_MULTI);
}
void ucp_test_base::entity::connect(const entity* other) {
ucs_status_t status;
ucp_address_t *address;
size_t address_length;
status = ucp_worker_get_address(other->worker(), &address, &address_length);
ASSERT_UCS_OK(status);
ucp_ep_h ep;
ucp_test::disable_errors();
status = ucp_ep_create(m_worker, address, &ep);
ucp_test::restore_errors();
if (status == UCS_ERR_UNREACHABLE) {
ucp_worker_release_address(other->worker(), address);
UCS_TEST_SKIP_R(ucp_test::m_last_err_msg);
}
ASSERT_UCS_OK(status);
m_ep.reset(ep, ucp_ep_destroy);
ucp_worker_release_address(other->worker(), address);
}
void ucp_test_base::entity::flush_worker() const {
ucs_status_t status = ucp_worker_flush(worker());
ASSERT_UCS_OK(status);
}
void ucp_test_base::entity::flush_ep() const {
ucs_status_t status = ucp_ep_flush(ep());
ASSERT_UCS_OK(status);
}
void ucp_test_base::entity::fence() const {
ucs_status_t status = ucp_worker_fence(worker());
ASSERT_UCS_OK(status);
}
void ucp_test_base::entity::disconnect() {
m_ep.reset();
}
void ucp_test_base::entity::destroy_worker() {
disconnect();
m_worker.reset();
}
ucp_ep_h ucp_test_base::entity::ep() const {
return m_ep;
}
ucp_worker_h ucp_test_base::entity::worker() const {
return m_worker;
}
ucp_context_h ucp_test_base::entity::ucph() const {
return m_ucph;
}
void ucp_test_base::entity::progress()
{
ucp_worker_progress(m_worker);
}
| 26.432056 | 91 | 0.621803 | [
"vector"
] |
bbfc53002a0fa51a1ddd813e09ec65529f112de7 | 5,918 | cpp | C++ | src/GaussianChannelFeatures.cpp | bobetocalo/bobetocalo_eccv18 | c82c13598836200f9deff751b89ab14345de69ab | [
"BSD-2-Clause"
] | 78 | 2018-10-10T12:20:48.000Z | 2021-09-16T16:33:58.000Z | src/GaussianChannelFeatures.cpp | bobetocalo/bobetocalo_eccv18 | c82c13598836200f9deff751b89ab14345de69ab | [
"BSD-2-Clause"
] | 4 | 2018-11-09T07:06:28.000Z | 2020-04-03T19:24:07.000Z | src/GaussianChannelFeatures.cpp | bobetocalo/bobetocalo_eccv18 | c82c13598836200f9deff751b89ab14345de69ab | [
"BSD-2-Clause"
] | 18 | 2018-10-25T10:51:52.000Z | 2021-06-01T12:35:44.000Z | /** ****************************************************************************
* @file GaussianChannelFeatures.cpp
* @brief Face detection and recognition framework
* @author Roberto Valle Fernandez
* @date 2015/06
* @copyright All rights reserved.
* Software developed by UPM PCR Group: http://www.dia.fi.upm.es/~pcr
******************************************************************************/
// ----------------------- INCLUDES --------------------------------------------
#include <GaussianChannelFeatures.hpp>
#include <NearestEncoding.hpp>
namespace upm {
const float BBOX_SCALE = 0.5f;
// -----------------------------------------------------------------------------
//
// Purpose and Method:
// Inputs:
// Outputs:
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------
GaussianChannelFeatures::GaussianChannelFeatures
(
const cv::Mat &shape,
const cv::Mat &label
)
{
_max_diameter = 0.20f;
_min_diameter = 0.05f;
_robust_shape = shape.clone();
_robust_label = label.clone();
_channel_sigmas = {0.0000000f, 0.0017813f, 0.0023753f, 0.0035633f, 0.0053446f, 0.0077206f, 0.0106900f, 0.0142533f};
_sampling_pattern = {
{0.667f,0.000f}, {0.333f,0.577f}, {-0.333f,0.577f}, {-0.667f,0.000f}, {-0.333f,-0.577f}, {0.333f,-0.577f},
{0.433f,0.250f}, {0.000f,0.500f}, {-0.433f,0.250f}, {-0.433f,-0.250f}, {0.000f,-0.500f}, {0.433f,-0.250f},
{0.361f,0.000f}, {0.180f,0.313f}, {-0.180f,0.313f}, {-0.361f,0.000f}, {-0.180f,-0.313f}, {0.180f,-0.313f},
{0.216f,0.125f}, {0.000f,0.250f}, {-0.216f,0.125f}, {-0.216f,-0.125f}, {0.000f,-0.250f}, {0.216f,-0.125f},
{0.167f,0.000f}, {0.083f,0.144f}, {-0.083f,0.144f}, {-0.167f,0.000f}, {-0.083f,-0.144f}, {0.083f,-0.144f},
{0.096f,0.055f}, {0.000f,0.111f}, {-0.096f,0.055f}, {-0.096f,-0.055f}, {0.000f,-0.111f}, {0.096f,-0.055f},
{0.083f,0.000f}, {0.042f,0.072f}, {-0.042f,0.072f}, {-0.083f,0.000f}, {-0.042f,-0.072f}, {0.042f,-0.072f},
{0.000f,0.000f}};
_channel_per_sampling = {
7, 7, 7, 7, 7, 7,
6, 6, 6, 6, 6, 6,
5, 5, 5, 5, 5, 5,
4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1,
0};
/// Generate pixel locations relative to robust shape
_encoder.reset(new NearestEncoding());
};
// -----------------------------------------------------------------------------
//
// Purpose and Method:
// Inputs:
// Outputs:
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------
cv::Rect_<float>
GaussianChannelFeatures::enlargeBbox
(
const cv::Rect_<float> &bbox
)
{
/// Enlarge bounding box
cv::Point2f shift(bbox.width*BBOX_SCALE, bbox.height*BBOX_SCALE);
cv::Rect_<float> enlarged_bbox = cv::Rect_<float>(bbox.x-shift.x, bbox.y-shift.y, bbox.width+(shift.x*2), bbox.height+(shift.y*2));
return enlarged_bbox;
};
// -----------------------------------------------------------------------------
//
// Purpose and Method:
// Inputs:
// Outputs:
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------
std::vector<cv::Mat>
GaussianChannelFeatures::generateChannels
(
const cv::Mat &img,
const cv::Rect_<float> &bbox
)
{
/// Crop face image
cv::Mat face_scaled, T = (cv::Mat_<float>(2,3) << 1, 0, -bbox.x, 0, 1, -bbox.y);
cv::warpAffine(img, face_scaled, T, bbox.size());
/// Several gaussian channel images
const unsigned int num_channels = static_cast<unsigned int>(_channel_sigmas.size());
std::vector<cv::Mat> img_channels(num_channels);
cv::cvtColor(face_scaled, img_channels[0], cv::COLOR_BGR2GRAY);
for (unsigned int j=1; j < num_channels; j++)
cv::GaussianBlur(img_channels[0], img_channels[j], cv::Size(), _channel_sigmas[j]*bbox.height);
return img_channels;
};
// -----------------------------------------------------------------------------
//
// Purpose and Method:
// Inputs:
// Outputs:
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------
cv::Mat
GaussianChannelFeatures::extractFeatures
(
const std::vector<cv::Mat> &img_channels,
const float face_height,
const cv::Mat &rigid,
const cv::Mat &tform,
const cv::Mat &shape,
float level
)
{
/// Compute features from a pixel coordinates difference using a pattern
cv::Mat CR = rigid.colRange(0,2).clone();
float diameter = ((1-level)*_max_diameter) + (level*_min_diameter);
std::vector<cv::Point2f> freak_pattern(_sampling_pattern);
for (cv::Point2f &point : freak_pattern)
point *= diameter;
std::vector<cv::Point2f> pixel_coordinates = _encoder->generatePixelSampling(_robust_shape, freak_pattern);
_encoder->setPixelSamplingEncoding(_robust_shape, _robust_label, pixel_coordinates);
std::vector<cv::Point2f> current_pixel_coordinates = _encoder->getProjectedPixelSampling(CR, tform, shape);
const unsigned int num_landmarks = static_cast<unsigned int>(shape.rows);
const unsigned int num_sampling = static_cast<unsigned int>(_channel_per_sampling.size());
cv::Mat features = cv::Mat(num_landmarks,num_sampling,CV_32FC1);
for (unsigned int i=0; i < num_landmarks; i++)
{
for (unsigned int j=0; j < num_sampling; j++)
{
int x = static_cast<int>(current_pixel_coordinates[(i*num_sampling)+j].x + 0.5f);
int y = static_cast<int>(current_pixel_coordinates[(i*num_sampling)+j].y + 0.5f);
x = x < 0 ? 0 : x;
y = y < 0 ? 0 : y;
unsigned int channel = _channel_per_sampling[j];
x = x > img_channels[channel].cols-1 ? img_channels[channel].cols-1 : x;
y = y > img_channels[channel].rows-1 ? img_channels[channel].rows-1 : y;
features.at<float>(i,j) = img_channels[channel].at<uchar>(y,x);
}
}
return features;
};
} // namespace upm
| 36.530864 | 133 | 0.561 | [
"shape",
"vector"
] |
010b2762b679a6da06810a431a79463e9128751d | 73,447 | cxx | C++ | printscan/ui/printui/traynot.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | printscan/ui/printui/traynot.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | printscan/ui/printui/traynot.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (C) Microsoft Corporation, 1995 - 1999
All rights reserved.
Module Name:
traynot.cxx
Abstract:
tray notifications and balloon help
Author:
Lazar Ivanov (LazarI) 25-Apr-2000
Revision History:
--*/
#include "precomp.hxx"
#pragma hdrstop
#include "prids.h"
#include "spllibex.hxx"
#include "persist.hxx"
#include "rtlmir.hxx"
////////////////////////////////////////////////////////
// debugging stuff
//
#if DBG
// #define DBG_TRAYNOTIFY DBG_INFO
#define DBG_TRAYNOTIFY DBG_NONE
#define DBG_PROCESSPRNNOTIFY DBG_NONE
#define DBG_JOBNOTIFY DBG_NONE
#define DBG_PRNNOTIFY DBG_NONE
#define DBG_TRAYUPDATE DBG_NONE
#define DBG_BALLOON DBG_NONE
#define DBG_NTFYICON DBG_NONE
#define DBG_MENUADJUST DBG_NONE
#define DBG_INITDONE DBG_NONE
#define DBG_JOBSTATUS DBG_NONE
#endif
#ifdef __cplusplus
extern "C" {
#endif
BOOL WINAPI PrintNotifyTray_Init();
BOOL WINAPI PrintNotifyTray_Exit();
BOOL WINAPI PrintNotifyTray_SelfShutdown();
} // extern "C"
//////////////////////////////////////////////
// CTrayNotify - tray notifications class
//
QITABLE_DECLARE(CTrayNotify)
class CTrayNotify: public CUnknownMT<QITABLE_GET(CTrayNotify)>, // MT impl. of IUnknown
public IFolderNotify,
public IPrinterChangeCallback,
public CSimpleWndSubclass<CTrayNotify>
{
public:
CTrayNotify();
~CTrayNotify();
//////////////////
// IUnknown
//
IMPLEMENT_IUNKNOWN()
void SetUser(LPCTSTR pszUser = NULL); // NULL means the current user
void Touch(); // resets the shutdown timer
void Resurrect(); // resurrects the tray after shutdown has been initiated
BOOL Initialize(); // initialize & start listening
BOOL Shutdown(); // stop listening & force shutdown
BOOL CanShutdown(); // check if shutdown criteria is met (SHUTDOWN_TIMEOUT sec. inactivity)
// implement CSimpleWndSubclass<...> - has to be public
LRESULT WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
///////////////////
// IFolderNotify
//
STDMETHODIMP_(BOOL) ProcessNotify(FOLDER_NOTIFY_TYPE NotifyType, LPCWSTR pszName, LPCWSTR pszNewName);
///////////////////////////
// IPrinterChangeCallback
//
STDMETHODIMP PrinterChange(ULONG_PTR uCookie, DWORD dwChange, const PRINTER_NOTIFY_INFO *pInfo);
private:
// internal stuff, enums/data types/methods/members
enum
{
// possible private messages coming to our special window
WM_PRINTTRAY_FIRST = WM_APP,
WM_PRINTTRAY_PRIVATE_MSG, // private msg (posted data by background threads)
WM_PRINTTRAY_REQUEST_SHUTDOWN, // request shutdown
WM_PRINTTRAY_ICON_NOTIFY, // message comming back from shell
};
enum
{
// possible update events (see _RequestUpdate), we don't really care now,
// but it is useful for future extensibility
UPDATE_REQUEST_JOB_ADD, // lParam = prnCookie
UPDATE_REQUEST_JOB_DELETE, // lParam = prnCookie
UPDATE_REQUEST_JOB_STATUS, // lParam = prnCookie
UPDATE_REQUEST_PRN_FIRST,
UPDATE_REQUEST_PRN_ADD, // lParam = prnCookie
UPDATE_REQUEST_PRN_DELETE, // lParam = 0, not used
UPDATE_REQUEST_PRN_STATUS, // lParam = prnCookie
UPDATE_REQUEST_PRN_RENAME, // lParam = prnCookie
};
enum
{
ENUM_MAX_RETRY = 5, // max attempts to call bFolderEnumPrinters/bFolderGetPrinter
ICON_ID = 1, // our icon ID
DEFAULT_BALLOON_TIMEOUT = 10000, // in miliseconds
JOB_ERROR_BITS = (JOB_STATUS_OFFLINE|JOB_STATUS_USER_INTERVENTION|JOB_STATUS_ERROR|JOB_STATUS_PAPEROUT),
JOB_IGNORE_BITS = (JOB_STATUS_DELETED|JOB_STATUS_PRINTED|JOB_STATUS_COMPLETE),
};
enum
{
SHUTDOWN_TIMER_ID = 100, // shutdown timer ID
//SHUTDOWN_TIMEOUT = 3*1000, // timeout to shutdown the tray code when the user
SHUTDOWN_TIMEOUT = 30*1000, // timeout to shutdown the tray code when the user
// is not printing - 1 min.
};
enum
{
// balloon IDs
BALLOON_ID_JOB_FAILED = 1, // balloon when a job failed to print
BALLOON_ID_JOB_PRINTED = 2, // balloon when a job printed
BALLOON_ID_PRN_CREATED = 3, // balloon when a local printer is created
};
enum
{
MAX_PRINTER_DISPLAYNAME = 48,
MAX_DOC_DISPLAYNAME = 32,
};
enum
{
// message types, see MsgInfo declaration below
msgTypePrnNotify = 100, // why not?
msgTypePrnCheckDelete,
msgTypeJobNotify,
msgTypeJobNotifyLost,
};
// job info
typedef struct
{
DWORD dwID; // job ID
DWORD dwStatus; // job status
TCHAR szDocName[255]; // document name
SYSTEMTIME timeSubmitted; // when submited
DWORD dwTotalPages; // Total number of pages
} JobInfo;
// define JobInfo adaptor class
class CJobInfoAdaptor: public Alg::CDefaultAdaptor<JobInfo, DWORD>
{
public:
static DWORD Key(const JobInfo &i) { return i.dwID; }
};
// CJobInfoArray definition
typedef CSortedArray<JobInfo, DWORD, CJobInfoAdaptor> CJobInfoArray;
// printer info
typedef struct
{
TCHAR szPrinter[kPrinterBufMax]; // the printer name
DWORD dwStatus; // printer status
CJobInfoArray *pUserJobs; // the jobs pending on this printer
CPrintNotify *pListener; // notifications listener
BOOL bUserInterventionReq; // this printer requires user intervention
} PrinterInfo;
// define PrinterInfo adaptor class
class CPrinterInfoAdaptor: public Alg::CDefaultAdaptor<PrinterInfo, LPCTSTR>
{
public:
static LPCTSTR Key(const PrinterInfo &i) { return i.szPrinter; }
static int Compare(LPCTSTR pszK1, LPCTSTR pszK2) { return lstrcmp(pszK1, pszK2); }
};
// CPrnInfoArray definition
typedef CSortedArray<PrinterInfo, LPCTSTR, CPrinterInfoAdaptor> CPrnInfoArray;
// balloon info
typedef struct
{
UINT uBalloonID; // balloon ID (what action to take when clicked)
LPCTSTR pszCaption; // balloon caption
LPCTSTR pszText; // balloon text
LPCTSTR pszSound; // canonical name of a special sound (can be NULL)
DWORD dwFlags; // flags (NIIF_INFO, NIIF_WARNING, NIIF_ERROR)
UINT uTimeout; // timeout
} BalloonInfo;
// private message info
typedef struct
{
int iType; // private message type (msgTypePrnNotifymsgTypeJobNotify, msgTypeJobNotifyLost)
FOLDER_NOTIFY_TYPE NotifyType; // printer notify type (kFolder* constants defined in winprtp.h)
TCHAR szPrinter[kPrinterBufMax]; // printer name
// job notification fields
struct
{
WORD Type; // PRINTER_NOTIFY_INFO_DATA.Type
WORD Field; // PRINTER_NOTIFY_INFO_DATA.Field
DWORD Id; // PRINTER_NOTIFY_INFO_DATA.Id
DWORD dwData; // PRINTER_NOTIFY_INFO_DATA.NotifyData.adwData[0]
} jn;
// auxiliary buffer
TCHAR szAuxName[kPrinterBufMax]; // PRINTER_NOTIFY_INFO_DATA.NotifyData.Data.pBuf or pszNewName
} MsgInfo;
// internal APIs
BOOL _InternalInit();
void _MsgLoop();
void _ThreadProc();
void _ProcessPrnNotify(FOLDER_NOTIFY_TYPE NotifyType, LPCWSTR pszName, LPCWSTR pszNewName);
BOOL _FindPrinter(LPCTSTR pszPrinter, int *pi) const;
BOOL _FindUserJob(DWORD dwID, const PrinterInfo &info, int *pi) const;
UINT _LastReservedMenuID() const;
void _AdjustMenuIDs(HMENU hMenu, UINT uIDFrom, int iAdjustment) const;
int _Insert(const FOLDER_PRINTER_DATA &data);
void _Delete(int iPos);
HRESULT _GetPrinter(LPCTSTR pszPrinter, LPBYTE *ppData, PDWORD pcReturned);
void _CheckToUpdateUserJobs(PrinterInfo &pi, const MsgInfo &msg);
void _CheckUserJobs(int *piUserJobs, BOOL *pbUserJobPrinting, BOOL *pbUserInterventionReq);
void _CheckToUpdateTray(BOOL bForceUpdate, const BalloonInfo *pBalloon, BOOL bForceDelete = FALSE);
LRESULT _ProcessUserMsg(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void _ShowMenu();
void _ShowPrnFolder() const;
void _ShowBalloon(UINT uBalloonID, LPCTSTR pszCaption, LPCTSTR pszText, LPCTSTR pszSound,
DWORD dwFlags = NIIF_INFO, UINT uTimeout = DEFAULT_BALLOON_TIMEOUT);
void _JobFailed(LPCTSTR pszPrinter, JobInfo &ji);
void _JobPrinted(LPCTSTR pszPrinter, JobInfo &ji);
BOOL _TimeToString(const SYSTEMTIME &time, TString *pTime) const;
void _DoRefresh(CPrintNotify *pListener);
void _PostPrivateMsg(const MsgInfo &msg);
void _RequestUpdate(int iEvent, LPCTSTR pszPrinter, LPCTSTR pszAux = NULL);
void _BalloonClicked(UINT uBalloonID) const;
BOOL _UpdateUserJob(PrinterInfo &pi, JobInfo &ji);
void _ShowAllActivePrinters() const;
void _AddPrinterToCtxMenu(HMENU hMenu, int i);
HRESULT _ProcessJobNotifications(LPCTSTR pszPrinter, DWORD dwChange,
const PRINTER_NOTIFY_INFO *pInfo, PrinterInfo *ppi = NULL);
void _ResetAll();
BOOL _IsFaxPrinter(const FOLDER_PRINTER_DATA &data);
HRESULT _CanNotify(LPCTSTR pszPrinterName, BOOL *pbCanNotify);
// msg loop thread proc
static DWORD WINAPI _ThreadProc_MsgLoop(LPVOID lpParameter);
// the callback called on refresh
static HRESULT WINAPI _RefreshCallback(
LPVOID lpCookie, ULONG_PTR uCookie, DWORD dwChange, const PRINTER_NOTIFY_INFO *pInfo);
// some inlines
int _EncodeMenuID(int i) const { return (i + _LastReservedMenuID() + 1); }
int _DecodeMenuID(int i) const { return (i - _LastReservedMenuID() - 1); }
// internal members
int m_cxSmIcon; // the icon size X
int m_cySmIcon; // the icon size Y
UINT m_uTrayIcon; // the current tray icon
int m_iUserJobs; // the user jobs (need to keep track of this to update the tooltip)
BOOL m_bInRefresh; // if we are in refresh
BOOL m_bIconShown; // if the icon is visible or not
UINT m_uBalloonID; // the ID of the last balloon shown up
UINT m_uBalloonsCount; // how many balloons has been currently displayed
CAutoHandleNT m_shEventReady; // event to sync Initialize & Shutdown
CAutoHandleNT m_shThread; // notifications thread listener
CAutoHandleIcon m_shIconShown; // the tray icon shown
CAutoHandleMenu m_shCtxMenu; // the context menu
HANDLE m_hFolder; // printer's folder cache
CFastHeap<MsgInfo> m_heapMsgCache; // messages cache
CPrnInfoArray m_arrWatchList; // printers holding documents for our (the current) user
TString m_strUser; // our (usually the current) user
TString m_strLastBalloonPrinter; // the printer name of the last balloon
DWORD m_dwLastTimeInactive; // the last time since the print icon has been inactive
BOOL m_bSelfShutdownInitiated; // is self-shutdown initiated?
};
// QueryInterface table
QITABLE_BEGIN(CTrayNotify)
QITABENT(CTrayNotify, IFolderNotify), // IID_IFolderNotify
QITABLE_END()
HRESULT CTrayNotify_CreateInstance(CTrayNotify **ppObj)
{
HRESULT hr = E_INVALIDARG;
if( ppObj )
{
*ppObj = new CTrayNotify;
hr = (*ppObj) ? S_OK : E_OUTOFMEMORY;
}
return hr;
}
/////////////////////////////
// globals & constants
//
#define gszTrayListenerClassName TEXT("PrintTray_Notify_WndClass")
static WORD g_JobFields[] =
{ // Job Fields we want notifications for
JOB_NOTIFY_FIELD_STATUS, // Status bits
JOB_NOTIFY_FIELD_NOTIFY_NAME, // Name of the user who should be notified
JOB_NOTIFY_FIELD_TOTAL_PAGES, // Total number of pages
};
static PRINTER_NOTIFY_OPTIONS_TYPE g_Notifications[2] =
{
{
JOB_NOTIFY_TYPE, // We want notifications on print jobs
0, 0, 0, // Reserved, must be zeros
sizeof(g_JobFields)/sizeof(g_JobFields[0]), // We specified 9 fields in the JobFields array
g_JobFields // Precisely which fields we want notifications for
}
};
static const UINT g_arrIcons[] = { 0, IDI_PRINTER, IDI_PRINTER_ERROR };
static const UINT g_arrReservedMenuIDs[] =
{
IDM_TRAYNOTIFY_DEFAULT,
IDM_TRAYNOTIFY_PRNFOLDER,
IDM_TRAYNOTIFY_REFRESH,
};
/////////////////////////////
// inlines
//
inline UINT CTrayNotify::_LastReservedMenuID() const
{
UINT uMax = 0;
for( int i=0; i<ARRAYSIZE(g_arrReservedMenuIDs); i++ )
{
if( g_arrReservedMenuIDs[i] > uMax )
{
uMax = g_arrReservedMenuIDs[i];
}
}
return uMax;
}
inline BOOL CTrayNotify::_FindPrinter(LPCTSTR pszPrinter, int *pi) const
{
return m_arrWatchList.FindItem(pszPrinter, pi);
}
inline BOOL CTrayNotify::_FindUserJob(DWORD dwID, const PrinterInfo &info, int *pi) const
{
return info.pUserJobs->FindItem(dwID, pi);
}
/////////////////////////////
// CTrayNotify
//
CTrayNotify::CTrayNotify()
: m_hFolder(NULL),
m_cxSmIcon(0),
m_cySmIcon(0),
m_uTrayIcon(g_arrIcons[0]),
m_iUserJobs(0),
m_bInRefresh(FALSE),
m_bIconShown(FALSE),
m_uBalloonID(0),
m_uBalloonsCount(0),
m_dwLastTimeInactive(GetTickCount()),
m_bSelfShutdownInitiated(FALSE)
{
// nothing special
DBGMSG(DBG_TRAYNOTIFY, ("TRAYNOTIFY: CTrayNotify::CTrayNotify()\n"));
}
CTrayNotify::~CTrayNotify()
{
ASSERT(FALSE == IsAttached());
ASSERT(NULL == m_hFolder);
ASSERT(0 == m_arrWatchList.Count());
DBGMSG(DBG_TRAYNOTIFY, ("TRAYNOTIFY: CTrayNotify::~CTrayNotify()\n"));
}
void CTrayNotify::SetUser(LPCTSTR pszUser)
{
TCHAR szUserName[UNLEN + 1];
szUserName[0] = 0;
if( NULL == pszUser || 0 == pszUser[0] )
{
// set the current user
DWORD dwSize = COUNTOF(szUserName);
if( GetUserName(szUserName, &dwSize) )
{
pszUser = szUserName;
}
}
m_strUser.bUpdate(pszUser);
}
void CTrayNotify::Touch()
{
m_dwLastTimeInactive = GetTickCount();
}
void CTrayNotify::Resurrect()
{
if( m_bSelfShutdownInitiated )
{
// restart the shutdown timer & reset the state
m_bSelfShutdownInitiated = FALSE;
SetTimer(m_hwnd, SHUTDOWN_TIMER_ID, SHUTDOWN_TIMEOUT, NULL);
}
}
BOOL CTrayNotify::Initialize()
{
BOOL bReturn = FALSE;
if( 0 == m_strUser.uLen() )
{
// assume listening for the currently logged on user
SetUser(NULL);
}
m_shEventReady = CreateEvent(NULL, FALSE, FALSE, NULL);
if( m_shEventReady )
{
DWORD dwThreadId;
m_shThread = TSafeThread::Create(NULL, 0, (LPTHREAD_START_ROUTINE)_ThreadProc_MsgLoop, this, 0, &dwThreadId);
if( m_shThread )
{
// wait the background thread to kick off
WaitForSingleObject(m_shEventReady, INFINITE);
if( IsAttached() )
{
// the message loop has started successfully, request full refresh
m_shEventReady = NULL;
// request an initial refresh
MsgInfo msg = { msgTypePrnNotify, kFolderUpdateAll };
_PostPrivateMsg(msg);
// we are fine here
bReturn = TRUE;
}
}
}
return bReturn;
}
BOOL CTrayNotify::Shutdown()
{
if( IsAttached() )
{
PostMessage(m_hwnd, WM_PRINTTRAY_REQUEST_SHUTDOWN, 0, 0);
// wait the background thread to cleanup
WaitForSingleObject(m_shThread, INFINITE);
return !IsAttached();
}
return FALSE;
}
BOOL CTrayNotify::CanShutdown()
{
return ( !m_bIconShown &&
(GetTickCount() > m_dwLastTimeInactive) &&
(GetTickCount() - m_dwLastTimeInactive) > SHUTDOWN_TIMEOUT );
}
// private worker proc to shutdown the tray
static DWORD WINAPI ShutdownTray_WorkerProc(LPVOID lpParameter)
{
// shutdown the tray code.
PrintNotifyTray_SelfShutdown();
return 0;
}
// implement CSimpleWndSubclass<...>
LRESULT CTrayNotify::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch( uMsg )
{
case WM_TIMER:
{
switch( wParam )
{
case SHUTDOWN_TIMER_ID:
{
if( CanShutdown() && !m_bSelfShutdownInitiated )
{
// the tray icon has been inactive for more than SHUTDOWN_TIMEOUT
// initiate shutdown
if( SHQueueUserWorkItem(reinterpret_cast<LPTHREAD_START_ROUTINE>(ShutdownTray_WorkerProc),
NULL, 0, 0, NULL, "printui.dll", 0) )
{
m_bSelfShutdownInitiated = TRUE;
KillTimer(hwnd, SHUTDOWN_TIMER_ID);
}
}
}
break;
default:
break;
}
}
break;
case WM_PRINTTRAY_REQUEST_SHUTDOWN:
{
// unregister the folder notifications
ASSERT(m_hFolder);
UnregisterPrintNotify(NULL, this, &m_hFolder);
m_hFolder = NULL;
// reset all listeners
_ResetAll();
// force to delete the tray icon
_CheckToUpdateTray(TRUE, NULL, TRUE);
// detach from the window
VERIFY(Detach());
// our object is now detached - destroy the window
// and post a quit msg to terminate the thread.
DestroyWindow(hwnd);
PostQuitMessage(0);
return 0;
}
break;
default:
if( m_hFolder )
{
// do not process user msgs if shutdown is in progress
_ProcessUserMsg(hwnd, uMsg, wParam, lParam);
}
else
{
//
// This should never happen, but we must check and
// free the msg instead of causing a leak.
//
if( WM_PRINTTRAY_PRIVATE_MSG == uMsg )
{
VERIFY(SUCCEEDED(m_heapMsgCache.Free(reinterpret_cast<HANDLE>(wParam))));
}
}
break;
}
// allways call the default processing
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
///////////////////
// IFolderNotify
//
STDMETHODIMP_(BOOL) CTrayNotify::ProcessNotify(FOLDER_NOTIFY_TYPE NotifyType, LPCWSTR pszName, LPCWSTR pszNewName)
{
// !IMPORTANT!
// this is a callback from the background threads, so
// we've got to be very carefull about what we are doing here.
// the easiest way to syncronize is to quickly pass a private
// message with the notification data into the foreground thread.
MsgInfo msg = { msgTypePrnNotify, NotifyType };
if( pszName )
{
lstrcpyn(msg.szPrinter, pszName, COUNTOF(msg.szPrinter));
}
if( pszNewName )
{
// this is not NULL only for kFolderRename
lstrcpyn(msg.szAuxName, pszNewName, COUNTOF(msg.szAuxName));
}
// post a private message here...
_PostPrivateMsg(msg);
return TRUE;
}
///////////////////////////
// IPrinterChangeCallback
//
STDMETHODIMP CTrayNotify::PrinterChange(ULONG_PTR uCookie, DWORD dwChange, const PRINTER_NOTIFY_INFO *pInfo)
{
// !IMPORTANT!
// this is a callback from the background threads, so
// we've got to be very carefull about what we are doing here.
// the easiest way to syncronize is to quickly pass a private
// message with the notification data into the foreground thread.
CPrintNotify *pListener = reinterpret_cast<CPrintNotify*>(uCookie);
return (pListener ? _ProcessJobNotifications(pListener->GetPrinter(), dwChange, pInfo, NULL) : E_INVALIDARG);
}
//////////////////////////////////
// private stuff _*
//
BOOL CTrayNotify::_InternalInit()
{
BOOL bReturn = SUCCEEDED(m_arrWatchList.Create());
if( bReturn )
{
WNDCLASS WndClass;
WndClass.style = 0L;
WndClass.lpfnWndProc = ::DefWindowProc;
WndClass.cbClsExtra = 0;
WndClass.cbWndExtra = 0;
WndClass.hInstance = 0;
WndClass.hIcon = NULL;
WndClass.hCursor = NULL;
WndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
WndClass.lpszMenuName = NULL;
WndClass.lpszClassName = gszTrayListenerClassName;
if( RegisterClass(&WndClass) ||
ERROR_CLASS_ALREADY_EXISTS == GetLastError() )
{
// create the worker window
HWND hwnd = CreateWindowEx(
bIsBiDiLocalizedSystem() ? kExStyleRTLMirrorWnd : 0,
gszTrayListenerClassName, NULL,
WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, NULL, NULL, 0, NULL);
if( hwnd )
{
Attach(hwnd);
}
}
if( IsAttached() )
{
// register for print notifications in the printer's folder cache
if( FAILED(RegisterPrintNotify(NULL, this, &m_hFolder, NULL)) )
{
// it will detach automatically
DestroyWindow(m_hwnd);
}
else
{
// initialize a timer to shutdown the listening thread if there
// is no activity for more than SHUTDOWN_TIMEOUT
SetTimer(m_hwnd, SHUTDOWN_TIMER_ID, SHUTDOWN_TIMEOUT, NULL);
}
}
}
return bReturn;
}
void CTrayNotify::_MsgLoop()
{
// spin the msg loop here
MSG msg;
ASSERT(m_hwnd);
while( GetMessage(&msg, NULL, 0, 0) )
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
void CTrayNotify::_ThreadProc()
{
AddRef();
_InternalInit();
if( m_shEventReady )
{
// notify the foreground thread we are about to start the msg loop
SetEvent(m_shEventReady);
}
if( IsAttached() )
{
// spin a standard windows msg loop here
_MsgLoop();
}
Release();
}
void CTrayNotify::_ProcessPrnNotify(FOLDER_NOTIFY_TYPE NotifyType, LPCWSTR pszName, LPCWSTR pszNewName)
{
DBGMSG(DBG_PROCESSPRNNOTIFY, ("PROCESSPRNNOTIFY: event has arrived, NotifyType=%d\n", NotifyType));
switch( NotifyType )
{
case kFolderUpdate:
case kFolderAttributes:
case kFolderCreate:
case kFolderUpdateAll:
{
CAutoPtrArray<BYTE> spBuffer;
DWORD i, cReturned = 0;
if( kFolderUpdateAll == NotifyType )
{
// reset all listeners...
_ResetAll();
// hide the icon, as this may take some time...
_CheckToUpdateTray(FALSE, NULL);
}
if( SUCCEEDED(_GetPrinter(kFolderUpdateAll == NotifyType ?
NULL : pszName, &spBuffer, &cReturned)) )
{
// walk through the printers to see if we need to add/delete/update printer(s) to our watch list.
PFOLDER_PRINTER_DATA pPrinters = spBuffer.GetPtrAs<PFOLDER_PRINTER_DATA>();
DBGMSG(DBG_PROCESSPRNNOTIFY, ("PROCESSPRNNOTIFY: create/update event, Count=%d\n", cReturned));
for( i=0; i<cReturned; i++ )
{
DBGMSG(DBG_PROCESSPRNNOTIFY, ("PROCESSPRNNOTIFY: process printer: "TSTR", Jobs=%d\n",
DBGSTR(pPrinters[i].pName), pPrinters[i].cJobs));
// important!: we can't watch printers in pending deletion state because once the printer is
// pending deletion it goes away without prior notification (when there is no jobs to print)
int iPos;
if( _FindPrinter(pPrinters[i].pName, &iPos) )
{
//
// we don't want to delete the printer from the watch list when jobs count goes
// to zero (0 == pPrinters[i].cJobs) because we rely on job notifications to show
// balloons and sometimes the job notifications come AFTER the printer notifications
//
// we handle this by posting msgTypePrnCheckDelete when job gets deleted
// so we can monitor the printer when there are no more user jobs in the queue and
// then we stop watching the printer. don't change this behaviour unless you want
// many things broken.
//
// printer found in the watch list
if( PRINTER_STATUS_PENDING_DELETION & pPrinters[i].Status )
{
// no jobs or in pending deletion state - just delete.
DBGMSG(DBG_PROCESSPRNNOTIFY, ("PROCESSPRNNOTIFY:[delete] watched printer with no jobs, pszPrinter="TSTR"\n",
DBGSTR(pPrinters[i].pName)));
_Delete(iPos);
_RequestUpdate(UPDATE_REQUEST_PRN_DELETE, pPrinters[i].pName);
}
else
{
if( m_arrWatchList[iPos].dwStatus != pPrinters[i].Status )
{
// update status
DBGMSG(DBG_PROCESSPRNNOTIFY, ("PROCESSPRNNOTIFY:[update] watched printer with jobs, pszPrinter="TSTR"\n",
DBGSTR(pPrinters[i].pName)));
m_arrWatchList[iPos].dwStatus = pPrinters[i].Status;
_RequestUpdate(UPDATE_REQUEST_PRN_STATUS, pPrinters[i].pName);
}
}
}
else
{
// printer not found in the watch list
if( pPrinters[i].cJobs && !(PRINTER_STATUS_PENDING_DELETION & pPrinters[i].Status) && !_IsFaxPrinter(pPrinters[i]) )
{
// start listening on this printer
DBGMSG(DBG_PROCESSPRNNOTIFY, ("PROCESSPRNNOTIFY:[insert] non-watched printer with jobs, pszPrinter="TSTR"\n",
DBGSTR(pPrinters[i].pName)));
iPos = _Insert(pPrinters[i]);
if( -1 != iPos )
{
_RequestUpdate(UPDATE_REQUEST_PRN_ADD, pPrinters[i].pName);
}
}
}
}
}
}
break;
case kFolderDelete:
case kFolderRename:
{
int iPos;
if( _FindPrinter(pszName, &iPos) )
{
// ranaming is a bit tricky. we need to delete & reinsert the item
// to keep the array sorted & then update the context menu if necessary
DBGMSG(DBG_PROCESSPRNNOTIFY, ("PROCESSPRNNOTIFY:[delete] watched printer deleted, pszPrinter="TSTR"\n",
DBGSTR(pszName)));
// first delete the printer which got renamed or deleted
_Delete(iPos);
_RequestUpdate(UPDATE_REQUEST_PRN_DELETE, pszName);
if( kFolderRename == NotifyType )
{
// if rename, request update, so this printer can be re-added with
// the new name.
MsgInfo msg = { msgTypePrnNotify, kFolderUpdate };
lstrcpyn(msg.szPrinter, pszNewName, COUNTOF(msg.szPrinter));
_PostPrivateMsg(msg);
}
}
}
break;
default:
break;
}
}
void CTrayNotify::_AdjustMenuIDs(HMENU hMenu, UINT uIDFrom, int iAdjustment) const
{
MENUITEMINFO mii = { sizeof(mii), MIIM_ID, 0 };
int i, iCount = GetMenuItemCount(hMenu);
for( i=0; i<iCount; i++ )
{
if( GetMenuItemInfo(hMenu, i, TRUE, &mii) && mii.wID >= uIDFrom )
{
DBGMSG(DBG_MENUADJUST, ("MENUADJUST: %d -> %d\n", mii.wID,
static_cast<UINT>(static_cast<int>(mii.wID) + iAdjustment)));
// adjust the menu item ID
mii.wID = static_cast<UINT>(static_cast<int>(mii.wID) + iAdjustment);
ASSERT(_DecodeMenuID(mii.wID) < m_arrWatchList.Count());
// update menu item here
SetMenuItemInfo(hMenu, i, TRUE, &mii);
}
}
}
int CTrayNotify::_Insert(const FOLDER_PRINTER_DATA &data)
{
CAutoPtr<CJobInfoArray> spUserJobs = new CJobInfoArray;
CAutoPtr<CPrintNotify> spListener = new CPrintNotify(this, COUNTOF(g_Notifications), g_Notifications, PRINTER_CHANGE_JOB);
int iPos = -1;
if( spUserJobs && SUCCEEDED(spUserJobs->Create()) &&
spListener && SUCCEEDED(spListener->Initialize(data.pName)) )
{
PrinterInfo infoPrn = {0};
infoPrn.pListener = spListener;
infoPrn.pUserJobs = spUserJobs;
lstrcpyn(infoPrn.szPrinter, data.pName, COUNTOF(infoPrn.szPrinter));
infoPrn.pListener->SetCookie(reinterpret_cast<ULONG_PTR>(infoPrn.pListener));
ASSERT(!m_arrWatchList.FindItem(infoPrn.szPrinter, &iPos));
iPos = m_arrWatchList.SortedInsert(infoPrn);
if( -1 != iPos )
{
if( m_shCtxMenu )
{
DBGMSG(DBG_MENUADJUST, ("MENUADJUST: insert at pos: %d, Count=%d\n", iPos, m_arrWatchList.Count()));
// if the context menu is opened then adjust the IDs
_AdjustMenuIDs(m_shCtxMenu, _EncodeMenuID(iPos), 1);
}
// start listen on this printer
DBGMSG(DBG_PRNNOTIFY, ("PRNNOTIFY: start listen printer: "TSTR"\n", DBGSTR(data.pName)));
// they are hooked up already, detach from the smart pointers
spListener.Detach();
spUserJobs.Detach();
// do an initial refresh and start listen
_DoRefresh(infoPrn.pListener);
infoPrn.pListener->StartListen();
}
}
return iPos;
}
void CTrayNotify::_Delete(int iPos)
{
// stop listen on this printer
m_arrWatchList[iPos].pListener->StopListen();
DBGMSG(DBG_PRNNOTIFY, ("PRNNOTIFY: stop listen printer: "TSTR"\n", DBGSTR(m_arrWatchList[iPos].szPrinter)));
delete m_arrWatchList[iPos].pListener;
delete m_arrWatchList[iPos].pUserJobs;
m_arrWatchList.Delete(iPos);
DBGMSG(DBG_MENUADJUST, ("MENUADJUST: delete at pos: %d, Count=%d\n", iPos, m_arrWatchList.Count()));
// fix the context menu
if( m_shCtxMenu )
{
MENUITEMINFO mii = { sizeof(mii), MIIM_ID, 0 };
if( GetMenuItemInfo(m_shCtxMenu, _EncodeMenuID(iPos), FALSE, &mii) )
{
// make sure this menu item is deleted
VERIFY(DeleteMenu(m_shCtxMenu, _EncodeMenuID(iPos), MF_BYCOMMAND));
}
// if the context menu is opened then adjust the IDs
_AdjustMenuIDs(m_shCtxMenu, _EncodeMenuID(iPos), -1);
}
}
HRESULT CTrayNotify::_GetPrinter(LPCTSTR pszPrinter, LPBYTE *ppData, PDWORD pcReturned)
{
ASSERT(ppData);
ASSERT(pcReturned);
HRESULT hr = E_OUTOFMEMORY;
int iTry = -1;
DWORD cbNeeded = 0;
DWORD cReturned = 0;
CAutoPtrArray<BYTE> pData;
BOOL bStatus = FALSE;
for( ;; )
{
if( iTry++ >= ENUM_MAX_RETRY )
{
// max retry count reached. this is also
// considered out of memory case
pData = NULL;
break;
}
// call bFolderEnumPrinters/bFolderGetPrinter...
bStatus = pszPrinter ?
bFolderGetPrinter(m_hFolder, pszPrinter, pData.GetPtrAs<PFOLDER_PRINTER_DATA>(), cbNeeded, &cbNeeded) :
bFolderEnumPrinters(m_hFolder, pData.GetPtrAs<PFOLDER_PRINTER_DATA>(), cbNeeded, &cbNeeded, pcReturned);
if( !bStatus && ERROR_INSUFFICIENT_BUFFER == GetLastError() && cbNeeded )
{
// buffer too small case
pData = new BYTE[cbNeeded];
if( pData )
{
continue;
}
else
{
SetLastError(ERROR_OUTOFMEMORY);
break;
}
}
break;
}
// setup the error code properly
hr = bStatus ? S_OK : GetLastError() != ERROR_SUCCESS ? HRESULT_FROM_WIN32(GetLastError()) :
!pData ? E_OUTOFMEMORY : E_FAIL;
if( SUCCEEDED(hr) )
{
*ppData = pData.Detach();
if( pszPrinter )
{
*pcReturned = 1;
}
}
return hr;
}
void CTrayNotify::_CheckToUpdateUserJobs(PrinterInfo &pi, const MsgInfo &msg)
{
int iPos = -1;
BOOL bJobFound = _FindUserJob(msg.jn.Id, pi, &iPos);
// process DBG_JOBNOTIFY
DBGMSG(DBG_JOBNOTIFY, ("JOBNOTIFY: pszPrinter="TSTR", szAuxName="TSTR", Field: %d, dwData: %d\n",
DBGSTR(pi.szPrinter), DBGSTR(msg.szAuxName), msg.jn.Field, msg.jn.dwData));
if( JOB_NOTIFY_FIELD_NOTIFY_NAME == msg.jn.Field )
{
// process JOB_NOTIFY_FIELD_NOTIFY_NAME here
DBGMSG(DBG_JOBNOTIFY, ("JOBNOTIFY: JOB_NOTIFY_FIELD_NOTIFY_NAME, pszPrinter="TSTR"\n",
DBGSTR(pi.szPrinter)));
if( 0 == lstrcmp(msg.szAuxName, m_strUser) )
{
// a user job - check to insert
if( !bJobFound )
{
JobInfo ji = {msg.jn.Id};
if( _UpdateUserJob(pi, ji) && -1 != pi.pUserJobs->SortedInsert(ji) )
{
_RequestUpdate(UPDATE_REQUEST_JOB_ADD, pi.szPrinter);
DBGMSG(DBG_JOBNOTIFY, ("JOBNOTIFY: job added, JobID=%d, pszPrinter="TSTR"\n",
msg.jn.Id, DBGSTR(pi.szPrinter)));
}
}
}
else
{
// not a user job - check to delete
if( bJobFound )
{
DBGMSG(DBG_JOBNOTIFY, ("JOBNOTIFY: job deleted, JobID=%d, pszPrinter="TSTR"\n",
pi.pUserJobs->operator[](iPos).dwID, DBGSTR(pi.szPrinter)));
pi.pUserJobs->Delete(iPos);
_RequestUpdate(UPDATE_REQUEST_JOB_DELETE, pi.szPrinter);
}
}
}
if( bJobFound && JOB_NOTIFY_FIELD_STATUS == msg.jn.Field )
{
// process JOB_NOTIFY_FIELD_STATUS here
DBGMSG(DBG_JOBNOTIFY, ("JOBNOTIFY: JOB_NOTIFY_FIELD_STATUS, Status=%x, pszPrinter="TSTR"\n",
msg.jn.dwData, DBGSTR(pi.szPrinter)));
// update the job status bits here, by saving the old status first
JobInfo &ji = pi.pUserJobs->operator[](iPos);
DWORD dwOldJobStatus = ji.dwStatus;
ji.dwStatus = msg.jn.dwData;
do
{
// dump the job status
DBGMSG(DBG_JOBSTATUS, ("JOBSTATUS: old status=%x, new status=%x\n",
dwOldJobStatus, ji.dwStatus));
if( ji.dwStatus & JOB_STATUS_DELETED )
{
// the job status has the JOB_STATUS_DELETED bit up. delete the job.
DBGMSG(DBG_JOBNOTIFY, ("JOBNOTIFY: job deleted, JobID=%x, pszPrinter="TSTR"\n",
pi.pUserJobs->operator[](iPos).dwID, DBGSTR(pi.szPrinter)));
pi.pUserJobs->Delete(iPos);
_RequestUpdate(UPDATE_REQUEST_JOB_DELETE, pi.szPrinter);
break; // skip everything
}
if( FALSE == m_bInRefresh && (0 == (dwOldJobStatus & JOB_STATUS_PRINTED)) &&
(JOB_STATUS_PRINTED & ji.dwStatus) && (0 == (ji.dwStatus & JOB_ERROR_BITS)) )
{
// JOB_STATUS_PRINTED bit is up, the previous status nas no JOB_STATUS_PRINTED bit up
// and there are no error bits up - consider the job had just printed successfully.
DBGMSG(DBG_JOBNOTIFY, ("JOBNOTIFY: job completed with sucesss, JobID=%x, pszPrinter="TSTR"\n",
pi.pUserJobs->operator[](iPos).dwID, DBGSTR(pi.szPrinter)));
_JobPrinted(pi.szPrinter, ji);
}
if( FALSE == m_bInRefresh && (0 == (dwOldJobStatus & JOB_ERROR_BITS)) &&
(ji.dwStatus & JOB_ERROR_BITS) )
{
// if the job goes from non-error state into an error state
// then we assume the job has failed or a user intervention is
// required. in both cases we show the job-failed balloon.
DBGMSG(DBG_JOBNOTIFY, ("JOBNOTIFY: job failed to print, JobID=%x, pszPrinter="TSTR"\n",
pi.pUserJobs->operator[](iPos).dwID, DBGSTR(pi.szPrinter)));
_JobFailed(pi.szPrinter, ji);
}
// just check to update the job status
if( dwOldJobStatus != ji.dwStatus )
{
ji.dwStatus = msg.jn.dwData;
_RequestUpdate(UPDATE_REQUEST_JOB_STATUS, pi.szPrinter);
DBGMSG(DBG_JOBNOTIFY, ("JOBNOTIFY: status updated, Status=%x, pszPrinter="TSTR"\n",
ji.dwStatus, DBGSTR(pi.szPrinter)));
}
}
while( FALSE );
}
if( bJobFound && JOB_NOTIFY_FIELD_TOTAL_PAGES == msg.jn.Field &&
pi.pUserJobs->operator[](iPos).dwTotalPages != msg.jn.dwData )
{
// save the number of total pages, so we can display this info
// later in the balloon when the job completes successfully.
pi.pUserJobs->operator[](iPos).dwTotalPages = msg.jn.dwData;
DBGMSG(DBG_JOBNOTIFY, ("JOBNOTIFY: total pages updated, TotalPages=%x, pszPrinter="TSTR"\n",
pi.pUserJobs->operator[](iPos).dwTotalPages, DBGSTR(pi.szPrinter)));
}
}
void CTrayNotify::_CheckUserJobs(int *piUserJobs, BOOL *pbUserJobPrinting, BOOL *pbUserInterventionReq)
{
ASSERT(piUserJobs);
ASSERT(pbUserJobPrinting);
ASSERT(pbUserInterventionReq);
*piUserJobs = 0;
*pbUserJobPrinting = *pbUserInterventionReq = FALSE;
// walk through the watch list to see...
int i, iCount = m_arrWatchList.Count();
for( i=0; i<iCount; i++ )
{
m_arrWatchList[i].bUserInterventionReq = FALSE;
CJobInfoArray &arrJobs = *m_arrWatchList[i].pUserJobs;
int j, iJobCount = arrJobs.Count();
for( j=0; j<iJobCount; j++ )
{
DWORD dwStatus = arrJobs[j].dwStatus;
if( 0 == (dwStatus & JOB_IGNORE_BITS) )
{
(*piUserJobs)++;
}
if( dwStatus & JOB_ERROR_BITS )
{
// these job status bits are considered an error
*pbUserInterventionReq = m_arrWatchList[i].bUserInterventionReq = TRUE;
}
if( dwStatus & JOB_STATUS_PRINTING )
{
// check if the job is printing now
*pbUserJobPrinting = TRUE;
}
}
}
}
void CTrayNotify::_CheckToUpdateTray(BOOL bForceUpdate, const BalloonInfo *pBalloon, BOOL bForceDelete)
{
int iUserJobs;
BOOL bUserJobPrinting, bUserInterventionReq;
_CheckUserJobs(&iUserJobs, &bUserJobPrinting, &bUserInterventionReq);
DBGMSG(DBG_TRAYUPDATE, ("TRAYUPDATE: _CheckToUpdateTray called, "
"iUserJobs=%d, bUserJobPrinting=%d, bUserInterventionReq=%d\n",
iUserJobs, bUserJobPrinting, bUserInterventionReq));
UINT uTrayIcon = g_arrIcons[ ((iUserJobs != 0) || bUserJobPrinting || (0 != m_uBalloonID) || (0 != m_uBalloonsCount)) + bUserInterventionReq ];
NOTIFYICONDATA nid = { sizeof(nid), m_hwnd, ICON_ID, NIF_MESSAGE, WM_PRINTTRAY_ICON_NOTIFY, NULL };
// check to delete first
if( bForceDelete || (uTrayIcon == g_arrIcons[0] && m_uTrayIcon != g_arrIcons[0]) )
{
if( m_bIconShown )
{
Shell_NotifyIcon(NIM_DELETE, &nid);
// reset the shutdown timer
Touch();
DBGMSG(DBG_NTFYICON, ("NTFYICON: icon deleted.\n"));
}
m_uTrayIcon = g_arrIcons[0];
m_cxSmIcon = m_cySmIcon = m_iUserJobs = 0;
m_bIconShown = FALSE;
}
else
{
// check to add/modify the icon
if( uTrayIcon != g_arrIcons[0] )
{
BOOL bPlayBalloonSound = FALSE;
BOOL bBalloonRequested = FALSE;
DWORD dwMsg = (m_uTrayIcon == g_arrIcons[0]) ? NIM_ADD : NIM_MODIFY;
int cxSmIcon = GetSystemMetrics(SM_CXSMICON);
int cySmIcon = GetSystemMetrics(SM_CYSMICON);
// check to sync the icon
if( uTrayIcon != m_uTrayIcon || cxSmIcon != m_cxSmIcon || m_cySmIcon != cySmIcon )
{
m_cxSmIcon = cxSmIcon;
m_cySmIcon = cySmIcon;
m_uTrayIcon = uTrayIcon;
m_shIconShown = (HICON)LoadImage(ghInst, MAKEINTRESOURCE(m_uTrayIcon), IMAGE_ICON, m_cxSmIcon, m_cySmIcon, 0);
nid.uFlags |= NIF_ICON;
nid.hIcon = m_shIconShown;
}
// check to sync the tip (if the ctx menu is not open)
if( bForceUpdate || m_iUserJobs != iUserJobs )
{
TString strTemplate, strTooltip;
m_iUserJobs = iUserJobs;
if( strTemplate.bLoadString(ghInst, IDS_TOOLTIP_TRAY) &&
strTooltip.bFormat(strTemplate, m_iUserJobs, static_cast<LPCTSTR>(m_strUser)) )
{
nid.uFlags |= NIF_TIP;
if( m_shCtxMenu )
{
// clear the tip
nid.szTip[0] = 0;
}
else
{
// update the tip
lstrcpyn(nid.szTip, strTooltip, COUNTOF(nid.szTip));
}
}
}
// check to sync the balloon (if the ctx menu is not open)
if( bForceUpdate || pBalloon )
{
nid.uFlags |= NIF_INFO;
if( m_shCtxMenu || NULL == pBalloon )
{
// hide the ballon
nid.szInfoTitle[0] = 0;
nid.szInfo[0] = 0;
}
else
{
// show up the balloon
nid.dwInfoFlags = pBalloon->dwFlags;
nid.uTimeout = pBalloon->uTimeout;
lstrcpyn(nid.szInfoTitle, pBalloon->pszCaption, COUNTOF(nid.szInfoTitle));
lstrcpyn(nid.szInfo, pBalloon->pszText, COUNTOF(nid.szInfo));
if( pBalloon->pszSound && pBalloon->pszSound[0] )
{
nid.dwInfoFlags |= NIIF_NOSOUND;
bPlayBalloonSound = TRUE;
}
bBalloonRequested = TRUE;
}
}
if( bForceUpdate || !m_bIconShown || nid.uFlags != NIF_MESSAGE )
{
// sync icon data
Shell_NotifyIcon(dwMsg, &nid);
if( bPlayBalloonSound )
{
PlaySound(pBalloon->pszSound, NULL,
SND_ALIAS | SND_APPLICATION | SND_ASYNC | SND_NODEFAULT | SND_NOSTOP);
}
if( bBalloonRequested )
{
m_uBalloonsCount++;
}
if( NIM_ADD == dwMsg )
{
DBGMSG(DBG_NTFYICON, ("NTFYICON: icon added.\n"));
}
else
{
DBGMSG(DBG_NTFYICON, ("NTFYICON: icon modified.\n"));
}
if( NIM_ADD == dwMsg )
{
// make sure we use the correct version
nid.uVersion = NOTIFYICON_VERSION;
Shell_NotifyIcon(NIM_SETVERSION, &nid);
DBGMSG(DBG_NTFYICON, ("NTFYICON: icon set version.\n"));
}
}
m_bIconShown = TRUE;
}
}
}
void CTrayNotify::_ShowMenu()
{
// no need to synchronize as m_arrWatchList size can be
// changed only in the message loop
int i, iCount = m_arrWatchList.Count();
if( iCount )
{
// when loaded from the resource, the context menu contains only one
if( m_shCtxMenu )
{
EndMenu();
}
// command - "Open Active Printers" corresponding to IDM_TRAYNOTIFY_DEFAULT
m_shCtxMenu = ShellServices::LoadPopupMenu(ghInst, POPUP_TRAYNOTIFY_PRINTERS);
if( m_shCtxMenu )
{
// build the context menu here
InsertMenu(m_shCtxMenu, (UINT)-1, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
for( i=0; i<iCount; i++ )
{
if( m_arrWatchList[i].pUserJobs->Count() )
{
_AddPrinterToCtxMenu(m_shCtxMenu, i);
}
}
// show up the context menu
if( GetMenuItemCount(m_shCtxMenu) )
{
POINT pt;
GetCursorPos(&pt);
SetMenuDefaultItem(m_shCtxMenu, IDM_TRAYNOTIFY_DEFAULT, MF_BYCOMMAND);
SetForegroundWindow(m_hwnd);
// now after m_shCtxMenu is not NULL, disable the tooltips,
// while the menu is open
_CheckToUpdateTray(TRUE, NULL);
// show up the context menu here...
// popup menus follows it's window owner when it comes to mirroring,
// so we should pass a an owner window which is mirrored.
int idCmd = TrackPopupMenu(m_shCtxMenu,
TPM_NONOTIFY|TPM_RETURNCMD|TPM_RIGHTBUTTON|TPM_HORNEGANIMATION,
pt.x, pt.y, 0, m_hwnd, NULL);
if( idCmd != 0 )
{
switch(idCmd)
{
case IDM_TRAYNOTIFY_DEFAULT:
{
// open the queues of all active printers
_ShowAllActivePrinters();
}
break;
case IDM_TRAYNOTIFY_PRNFOLDER:
{
// open the printer's folder
_ShowPrnFolder();
}
break;
case IDM_TRAYNOTIFY_REFRESH:
{
// just refresh the whole thing...
MsgInfo msg = { msgTypePrnNotify, kFolderUpdateAll };
_PostPrivateMsg(msg);
}
break;
default:
{
// open the selected printer
vQueueCreate(NULL, m_arrWatchList[_DecodeMenuID(idCmd)].szPrinter,
SW_SHOWNORMAL, static_cast<LPARAM>(FALSE));
}
break;
}
}
}
}
// destroy the menu
m_shCtxMenu = NULL;
// re-enable the tooltips after the menu is closed
_CheckToUpdateTray(TRUE, NULL);
}
}
void CTrayNotify::_ShowPrnFolder() const
{
// find the printer's folder PIDL
CAutoPtrPIDL pidlPrinters;
HRESULT hr = SHGetSpecialFolderLocation(NULL, CSIDL_PRINTERS, &pidlPrinters);
if( SUCCEEDED(hr) )
{
// invoke ShellExecuteEx on that PIDL
SHELLEXECUTEINFO seInfo;
memset(&seInfo, 0, sizeof(seInfo));
seInfo.cbSize = sizeof(seInfo);
seInfo.fMask = SEE_MASK_IDLIST;
seInfo.hwnd = m_hwnd;
seInfo.nShow = SW_SHOWDEFAULT;
seInfo.lpIDList = pidlPrinters;
ShellExecuteEx(&seInfo);
}
}
void CTrayNotify::_ShowBalloon(
UINT uBalloonID,
LPCTSTR pszCaption,
LPCTSTR pszText,
LPCTSTR pszSound,
DWORD dwFlags,
UINT uTimeout)
{
// just show up the balloon...
m_uBalloonID = uBalloonID;
BalloonInfo bi = {m_uBalloonID, pszCaption, pszText, pszSound, dwFlags, uTimeout};
_CheckToUpdateTray(FALSE, &bi);
}
void CTrayNotify::_JobFailed(LPCTSTR pszPrinter, JobInfo &ji)
{
ASSERT(pszPrinter);
// since the baloon text length is limited to 255 characters we need to abbreviate the printer name
// and the document name if they are too long by adding ellipses at the end.
TString strPrinter, strDocName;
if( SUCCEEDED(AbbreviateText(pszPrinter, MAX_PRINTER_DISPLAYNAME, &strPrinter)) &&
SUCCEEDED(AbbreviateText(ji.szDocName, MAX_DOC_DISPLAYNAME, &strDocName)) )
{
TString strTimeSubmitted, strTemplate, strTitle, strText;
TStatusB bStatus;
bStatus DBGCHK = (ji.dwStatus & JOB_STATUS_PAPEROUT) ?
strTitle.bLoadString(ghInst, IDS_BALLOON_TITLE_JOB_FAILED_OOP) :
strTitle.bLoadString(ghInst, IDS_BALLOON_TITLE_JOB_FAILED);
if( bStatus &&
_TimeToString(ji.timeSubmitted, &strTimeSubmitted) &&
strTemplate.bLoadString(ghInst, IDS_BALLOON_TEXT_JOB_FAILED) &&
strText.bFormat(strTemplate,
static_cast<LPCTSTR>(strDocName),
static_cast<LPCTSTR>(strPrinter),
static_cast<LPCTSTR>(strTimeSubmitted)) )
{
_ShowBalloon(BALLOON_ID_JOB_FAILED, strTitle, strText, NULL, NIIF_WARNING);
m_strLastBalloonPrinter.bUpdate(pszPrinter);
}
}
}
void CTrayNotify::_JobPrinted(LPCTSTR pszPrinter, JobInfo &ji)
{
ASSERT(pszPrinter);
// since the baloon text length is limited to 255 characters we need to abbreviate the printer name
// and the document name if they are too long, by adding ellipses at the end.
TString strPrinter, strDocName;
if( SUCCEEDED(AbbreviateText(pszPrinter, MAX_PRINTER_DISPLAYNAME, &strPrinter)) &&
SUCCEEDED(AbbreviateText(ji.szDocName, MAX_DOC_DISPLAYNAME, &strDocName)) )
{
BOOL bCanNotify;
TString strTimeSubmitted, strTemplate, strTitle, strText;
// total pages can be zero when a downlevel document is printed (directly to the port) in
// this case StartDoc/EndDoc are not called and the spooler doesn't know the total pages of
// the document. in this case just display the balloon without total pages info.
UINT uTextID = ji.dwTotalPages ? IDS_BALLOON_TEXT_JOB_PRINTED : IDS_BALLOON_TEXT_JOB_PRINTED_NOPAGES;
if( SUCCEEDED(_CanNotify(pszPrinter, &bCanNotify)) && bCanNotify &&
_TimeToString(ji.timeSubmitted, &strTimeSubmitted) &&
strTitle.bLoadString(ghInst, IDS_BALLOON_TITLE_JOB_PRINTED) &&
strTemplate.bLoadString(ghInst, uTextID) &&
strText.bFormat(strTemplate,
static_cast<LPCTSTR>(strDocName),
static_cast<LPCTSTR>(strPrinter),
static_cast<LPCTSTR>(strTimeSubmitted),
ji.dwTotalPages) )
{
_ShowBalloon(BALLOON_ID_JOB_PRINTED, strTitle, strText, gszBalloonSoundPrintComplete, NIIF_INFO);
m_strLastBalloonPrinter.bUpdate(pszPrinter);
}
}
}
BOOL CTrayNotify::_TimeToString(const SYSTEMTIME &time, TString *pTime) const
{
ASSERT(pTime);
BOOL bReturn = FALSE;
TCHAR szText[255];
SYSTEMTIME timeLocal;
if( SystemTimeToTzSpecificLocalTime(NULL, const_cast<LPSYSTEMTIME>(&time), &timeLocal) &&
GetTimeFormat(LOCALE_USER_DEFAULT, 0, &timeLocal, NULL, szText, COUNTOF(szText)) )
{
pTime->bCat(szText);
pTime->bCat(TEXT(" "));
if( GetDateFormat(LOCALE_USER_DEFAULT, 0, &timeLocal, NULL, szText, COUNTOF(szText)) )
{
pTime->bCat(szText);
bReturn = TRUE;
}
}
return bReturn;
}
void CTrayNotify::_DoRefresh(CPrintNotify *pListener)
{
m_bInRefresh = TRUE;
pListener->Refresh(this, _RefreshCallback);
m_bInRefresh = FALSE;
// check to update the tray
_CheckToUpdateTray(FALSE, NULL);
}
void CTrayNotify::_PostPrivateMsg(const MsgInfo &msg)
{
HANDLE hItem;
if( SUCCEEDED(m_heapMsgCache.Alloc(msg, &hItem)) )
{
// request a balloon to show up...
if (!PostMessage(m_hwnd, WM_PRINTTRAY_PRIVATE_MSG, reinterpret_cast<LPARAM>(hItem), 0))
{
VERIFY(SUCCEEDED(m_heapMsgCache.Free(hItem)));
}
}
}
void CTrayNotify::_RequestUpdate(int iEvent, LPCTSTR pszPrinter, LPCTSTR pszAux)
{
// check to update the context menu if shown
int i = -1;
switch( iEvent )
{
case UPDATE_REQUEST_JOB_ADD:
{
// check to add to the context menu
MENUITEMINFO mii = { sizeof(mii), MIIM_ID, 0 };
if( m_shCtxMenu && _FindPrinter(pszPrinter, &i) && 0 != m_arrWatchList[i].pUserJobs->Count() &&
FALSE == GetMenuItemInfo(m_shCtxMenu, _EncodeMenuID(i), FALSE, &mii) )
{
// add this printer to the context menu
_AddPrinterToCtxMenu(m_shCtxMenu, i);
}
}
break;
case UPDATE_REQUEST_JOB_DELETE:
{
// check this printer to be deleted later
MsgInfo msg = { msgTypePrnCheckDelete, kFolderNone };
lstrcpyn(msg.szPrinter, pszPrinter, COUNTOF(msg.szPrinter));
_PostPrivateMsg(msg);
// check to delete from the context menu
MENUITEMINFO mii = { sizeof(mii), MIIM_ID, 0 };
if( m_shCtxMenu && _FindPrinter(pszPrinter, &i) && 0 == m_arrWatchList[i].pUserJobs->Count() &&
TRUE == GetMenuItemInfo(m_shCtxMenu, _EncodeMenuID(i), FALSE, &mii) )
{
// delete this printer from the context menu
VERIFY(DeleteMenu(m_shCtxMenu, _EncodeMenuID(i), MF_BYCOMMAND));
}
}
break;
default:
break;
}
// check to update tray if not in refresh
if( !m_bInRefresh )
{
_CheckToUpdateTray(FALSE, NULL);
}
}
void CTrayNotify::_BalloonClicked(UINT uBalloonID) const
{
switch( uBalloonID )
{
case BALLOON_ID_JOB_FAILED:
vQueueCreate(NULL, m_strLastBalloonPrinter, SW_SHOWNORMAL, static_cast<LPARAM>(FALSE));
break;
case BALLOON_ID_JOB_PRINTED:
// do nothing
break;
case BALLOON_ID_PRN_CREATED:
_ShowPrnFolder();
break;
default:
ASSERT(FALSE);
break;
}
}
BOOL CTrayNotify::_UpdateUserJob(PrinterInfo &pi, JobInfo &ji)
{
// get job info at level 1
BOOL bReturn = FALSE;
DWORD cbJob = 0;
CAutoPtrSpl<JOB_INFO_2> spJob;
if( VDataRefresh::bGetJob(pi.pListener->GetPrinterHandle(), ji.dwID, 2, spJob.GetPPV(), &cbJob) )
{
// the only thing we care about is the document name & job status
ji.dwStatus = spJob->Status;
lstrcpyn(ji.szDocName, spJob->pDocument, COUNTOF(ji.szDocName));
ji.timeSubmitted = spJob->Submitted;
ji.dwTotalPages = spJob->TotalPages;
bReturn = TRUE;
}
return bReturn;
}
void CTrayNotify::_ShowAllActivePrinters() const
{
HRESULT hr = S_OK;
int i, iCount;
PrinterInfo pi = {0};
CPrnInfoArray arrActivePrinters;
hr = arrActivePrinters.Create();
if (SUCCEEDED(hr))
{
for (i=0, iCount = m_arrWatchList.Count(); i<iCount; i++)
{
if (m_arrWatchList[i].pUserJobs->Count())
{
lstrcpyn(pi.szPrinter, m_arrWatchList[i].szPrinter, COUNTOF(pi.szPrinter));
//
// Ignore failures... SortedInsert can return -1 in case
// of lack of memory, but we can just safely ignore this.
// The worst case will be that some of the printer queues
// won't be opened.
//
hr = (-1 == arrActivePrinters.SortedInsert(pi) ? E_OUTOFMEMORY : S_OK);
}
}
//
// Open the queues of all active printers.
//
for (i=0, iCount = arrActivePrinters.Count(); i<iCount; i++)
{
vQueueCreate(NULL, arrActivePrinters[i].szPrinter, SW_SHOWNORMAL, static_cast<LPARAM>(FALSE));
}
}
}
void CTrayNotify::_AddPrinterToCtxMenu(HMENU hMenu, int i)
{
// build the context menu here
TString strPrinter;
MENUITEMINFO mii = { sizeof(mii), MIIM_TYPE|MIIM_ID, MF_STRING };
if( m_arrWatchList[i].bUserInterventionReq )
{
// this printer is in error state, add an (error) suffix
TString strTemplate;
strTemplate.bLoadString(ghInst, IDS_TRAY_TEXT_ERROR);
strPrinter.bFormat(strTemplate, m_arrWatchList[i].szPrinter);
}
else
{
strPrinter.bUpdate(m_arrWatchList[i].szPrinter);
}
mii.wID = _EncodeMenuID(i);
mii.dwTypeData = const_cast<LPTSTR>(static_cast<LPCTSTR>(strPrinter));
mii.cch = lstrlen(mii.dwTypeData);
InsertMenuItem(hMenu, (UINT)-1, MF_BYPOSITION, &mii);
}
HRESULT CTrayNotify::_ProcessJobNotifications(LPCTSTR pszPrinter, DWORD dwChange,
const PRINTER_NOTIFY_INFO *pInfo, PrinterInfo *ppi)
{
if( pInfo && (PRINTER_NOTIFY_INFO_DISCARDED & pInfo->Flags) )
{
MsgInfo msg = { msgTypeJobNotifyLost, kFolderNone };
lstrcpyn(msg.szPrinter, pszPrinter, COUNTOF(msg.szPrinter));
if( ppi )
{
// called from the foreground thread: sync processing
_CheckToUpdateUserJobs(*ppi, msg);
}
else
{
// called from the background threads: async processing
_PostPrivateMsg(msg);
}
}
else
{
// regular job notifications have arrived
if( pInfo && pInfo->Count )
{
MsgInfo msg = { msgTypeJobNotify, kFolderNone };
lstrcpyn(msg.szPrinter, pszPrinter, COUNTOF(msg.szPrinter));
for( DWORD i=0; i<pInfo->Count; i++ )
{
if( JOB_NOTIFY_TYPE != pInfo->aData[i].Type )
{
// we only care about job notifications here
continue;
}
msg.jn.Type = pInfo->aData[i].Type;
msg.jn.Field = pInfo->aData[i].Field;
msg.jn.Id = pInfo->aData[i].Id;
msg.jn.dwData = pInfo->aData[i].NotifyData.adwData[0];
if( JOB_NOTIFY_FIELD_NOTIFY_NAME == pInfo->aData[i].Field )
{
// need to copy pBuf into the aux buffer (szAuxName)
lstrcpyn(msg.szAuxName, reinterpret_cast<LPCTSTR>(pInfo->aData[i].NotifyData.Data.pBuf),
COUNTOF(msg.szAuxName));
}
if( ppi )
{
// called from the foreground thread: sync processing
_CheckToUpdateUserJobs(*ppi, msg);
}
else
{
// called from the background threads: async processing
_PostPrivateMsg(msg);
}
}
}
}
return S_OK;
}
void CTrayNotify::_ResetAll()
{
// close the context menu
m_shCtxMenu = NULL;
// cleanup the watch list (unregister all job notifications listeners)
while( m_arrWatchList.Count() )
{
_Delete(0);
}
// flush the message queue here...
MSG msg;
while( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )
{
if( WM_PRINTTRAY_PRIVATE_MSG == msg.message )
{
// just free up the private message
VERIFY(SUCCEEDED(m_heapMsgCache.Free(reinterpret_cast<HANDLE>(msg.wParam))));
}
}
// update the tray
_CheckToUpdateTray(FALSE, NULL);
}
BOOL CTrayNotify::_IsFaxPrinter(const FOLDER_PRINTER_DATA &data)
{
return ((0 == lstrcmp(data.pDriverName, FAX_DRIVER_NAME)) ||
(data.Attributes & PRINTER_ATTRIBUTE_FAX));
}
HRESULT CTrayNotify::_CanNotify(LPCTSTR pszPrinterName, BOOL *pbCanNotify)
{
HRESULT hr = E_INVALIDARG;
BOOL bIsNetworkPrinter;
LPCTSTR pszServer;
LPCTSTR pszPrinter;
TCHAR szScratch[kStrMax+kPrinterBufMax];
UINT nSize = COUNTOF(szScratch);
if( pszPrinterName && *pszPrinterName && pbCanNotify )
{
//
// Split the printer name into its components.
//
vPrinterSplitFullName(szScratch, ARRAYSIZE(szScratch), pszPrinterName, &pszServer, &pszPrinter);
bIsNetworkPrinter = bIsRemote(pszServer);
// set default value
*pbCanNotify = bIsNetworkPrinter ? TRUE : FALSE;
TPersist NotifyUser(gszPrinterPositions, TPersist::kCreate|TPersist::kRead);
if( NotifyUser.bValid() )
{
if( NotifyUser.bRead(bIsNetworkPrinter ? gszNetworkPrintNotification : gszLocalPrintNotification, *pbCanNotify) )
{
hr = S_OK;
}
else
{
hr = CreateHRFromWin32();
}
}
else
{
hr = CreateHRFromWin32();
}
}
return hr;
}
LRESULT CTrayNotify::_ProcessUserMsg(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch( uMsg )
{
case WM_PRINTTRAY_PRIVATE_MSG:
{
MsgInfo *pmsg = NULL;
HANDLE hItem = reinterpret_cast<HANDLE>(wParam);
VERIFY(SUCCEEDED(m_heapMsgCache.GetItem(hItem, &pmsg)));
switch( pmsg->iType )
{
case msgTypePrnNotify:
{
_ProcessPrnNotify(pmsg->NotifyType, pmsg->szPrinter, pmsg->szAuxName);
}
break;
case msgTypePrnCheckDelete:
{
int iPos = -1;
if( _FindPrinter(pmsg->szPrinter, &iPos) && 0 == m_arrWatchList[iPos].pUserJobs->Count() )
{
// this printer has no active user jobs, so delete it.
_Delete(iPos);
_RequestUpdate(UPDATE_REQUEST_PRN_DELETE, pmsg->szPrinter);
}
}
break;
case msgTypeJobNotify:
{
int iPos = -1;
if( _FindPrinter(pmsg->szPrinter, &iPos) )
{
_CheckToUpdateUserJobs(m_arrWatchList[iPos], *pmsg);
}
}
break;
case msgTypeJobNotifyLost:
{
int iPos = -1;
if( _FindPrinter(pmsg->szPrinter, &iPos) )
{
PrinterInfo &pi = m_arrWatchList[iPos];
// do a full refresh here
pi.dwStatus = 0;
pi.pUserJobs->DeleteAll();
_RequestUpdate(UPDATE_REQUEST_JOB_DELETE, pi.szPrinter);
// update all
_DoRefresh(m_arrWatchList[iPos].pListener);
}
}
break;
default:
ASSERT(FALSE);
break;
}
// free up the message
VERIFY(SUCCEEDED(m_heapMsgCache.Free(hItem)));
}
break;
case WM_PRINTTRAY_ICON_NOTIFY:
{
// the real uMsg is in lParam
switch( lParam )
{
case WM_CONTEXTMENU:
_ShowMenu();
break;
case WM_LBUTTONDBLCLK:
_ShowAllActivePrinters();
break;
case NIN_BALLOONUSERCLICK:
case NIN_BALLOONTIMEOUT:
{
m_uBalloonsCount--;
if( NIN_BALLOONUSERCLICK == lParam && m_uBalloonID )
{
_BalloonClicked(m_uBalloonID);
}
if( 0 == m_uBalloonsCount )
{
m_uBalloonID = 0;
m_strLastBalloonPrinter.bUpdate(NULL);
_CheckToUpdateTray(FALSE, NULL);
}
}
break;
default:
break;
}
}
break;
case WM_WININICHANGE:
{
// check to re-do the icon
_CheckToUpdateTray(FALSE, NULL);
}
break;
default:
break;
}
return 0;
}
DWORD WINAPI CTrayNotify::_ThreadProc_MsgLoop(LPVOID lpParameter)
{
CTrayNotify *pFolderNotify = (CTrayNotify *)lpParameter;
if( pFolderNotify )
{
pFolderNotify->_ThreadProc();
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
// the callback called on refresh
HRESULT WINAPI CTrayNotify::_RefreshCallback(
LPVOID lpCookie, ULONG_PTR uCookie, DWORD dwChange, const PRINTER_NOTIFY_INFO *pInfo)
{
int iPos;
HRESULT hr = E_INVALIDARG;
CTrayNotify *pThis = reinterpret_cast<CTrayNotify*>(lpCookie);
CPrintNotify *pListener = reinterpret_cast<CPrintNotify*>(uCookie);
if( pThis && pListener && pThis->_FindPrinter(pListener->GetPrinter(), &iPos) )
{
hr = pThis->_ProcessJobNotifications(
pListener->GetPrinter(), dwChange, pInfo, &pThis->m_arrWatchList[iPos]);
}
return hr;
}
//////////////////////////////////
// global & exported functions
//
static CTrayNotify *gpTrayNotify = NULL;
extern "C" {
BOOL WINAPI PrintNotifyTray_Init()
{
ASSERT(gpTrayLock);
// synchonize this with gpTrayLock
CCSLock::Locker lock(*gpTrayLock);
BOOL bReturn = FALSE;
if( NULL == gpTrayNotify )
{
if( SUCCEEDED(CTrayNotify_CreateInstance(&gpTrayNotify)) )
{
bReturn = gpTrayNotify->Initialize();
if( !bReturn )
{
gpTrayNotify->Release();
gpTrayNotify = NULL;
}
else
{
DBGMSG(DBG_INITDONE, ("INITDONE: PrintTray - start listen! \n"));
}
}
}
else
{
// reset the shutdown timer
gpTrayNotify->Touch();
}
return bReturn;
}
BOOL WINAPI PrintNotifyTray_Exit()
{
ASSERT(gpTrayLock);
// synchonize this with gpTrayLock
CCSLock::Locker lock(*gpTrayLock);
BOOL bReturn = FALSE;
if( gpTrayNotify )
{
bReturn = gpTrayNotify->Shutdown();
gpTrayNotify->Release();
gpTrayNotify = NULL;
DBGMSG(DBG_INITDONE, ("INITDONE: PrintTray - stop listen! \n"));
}
return bReturn;
}
BOOL WINAPI PrintNotifyTray_SelfShutdown()
{
ASSERT(gpTrayLock);
BOOL bReturn = FALSE;
CTrayNotify *pTrayNotify = NULL;
{
// synchonize this with gpTrayLock
CCSLock::Locker lock(*gpTrayLock);
if( gpTrayNotify )
{
if( gpTrayNotify->CanShutdown() )
{
// mark for deletion and continue to exit the CS
pTrayNotify = gpTrayNotify;
gpTrayNotify = NULL;
DBGMSG(DBG_INITDONE, ("INITDONE: PrintTray - stop listen! \n"));
}
else
{
// restart the shutdown timer
gpTrayNotify->Resurrect();
}
}
}
if( pTrayNotify )
{
// marked for shutdown & release - shutdown without holding the CS
bReturn = pTrayNotify->Shutdown();
pTrayNotify->Release();
}
return bReturn;
}
} // extern "C"
| 35.008103 | 148 | 0.530083 | [
"object"
] |
011d62716e19f86f0f23ee9e35e90a21b4b8ee48 | 3,662 | hpp | C++ | include/SystemManager/SystemManager.hpp | cristianglezm/AntFarm | df7551621ad6eda6dae43a2ede56222500be1ae1 | [
"Apache-2.0"
] | null | null | null | include/SystemManager/SystemManager.hpp | cristianglezm/AntFarm | df7551621ad6eda6dae43a2ede56222500be1ae1 | [
"Apache-2.0"
] | 1 | 2016-03-13T10:55:21.000Z | 2016-03-13T10:55:21.000Z | include/SystemManager/SystemManager.hpp | cristianglezm/AntFarm | df7551621ad6eda6dae43a2ede56222500be1ae1 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////
// Copyright 2014 Cristian Glez <Cristian.glez.m@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////
#ifndef SYSTEM_MANAGER_HPP
#define SYSTEM_MANAGER_HPP
#include <unordered_map>
#include <memory>
#include <Systems/System.hpp>
#include <SFML/System/Time.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
namespace ant{
/**
* @brief Clase contenedor para los systemas.
* @author Cristian Glez <Cristian.glez.m@gmail.com>
* @version 0.1
*/
class SystemManager final{
public:
/**
* @brief Contenedor usado por la clase.
*/
using container = std::unordered_map<std::string,std::shared_ptr<System>>;
/**
* @brief Añade un sistema al manager.
* @param s std::shared_ptr<System>
* @return bool
*/
bool addSystem(std::shared_ptr<System> s);
/**
* @brief Devuelve el sistema con el nombre especificado.
* @param name std::string nombre del sistema.
* @return std::shared_ptr<System>
*/
std::shared_ptr<System> getSystem(const std::string& name);
/**
* @brief Setter para poner el contenedor con todos los sistemas.
* @param systems container
*/
void setSystems(container systems);
/**
* @brief Getter para obtener el contenedor de los sistemas.
* @return SystemManager::container
*/
inline SystemManager::container& getSystems(){ return systems; }
/**
* @brief Elimina el sistema del manager.
* @param name std::string nombre del sistema.
*/
void removeSystem(const std::string& name);
/**
* @brief Establece el mismo EntityManager a todos los sistemas que esten agregados.
* @param entityManager std::shared_ptr<EntityManager>
*/
void setEntityManager(std::shared_ptr<EntityManager> entityManager);
/**
* @brief Establece la misma EventQueue a todos los sistemas que esten agregados.
* @param eventQueue std::shared_ptr<EventQueue>
*/
void setEventQueue(std::shared_ptr<EventQueue> eventQueue);
/**
* @brief Hace que todos los sistemas apliquen sus actualizaciones a sus EntityManager.
* @param dt sf::Time delta time
*/
void update(const sf::Time& dt);
/**
* @brief Hace que todos los sistemas renderizen a las Entidades que tengan que ser renderizadas.
*
* Este metodo necesita ir entre sf::RenderWindow::clear() y sf::RenderWindow::display()
*
* @param win sf::RenderWindow &
*/
void render(sf::RenderWindow& win);
private:
container systems;
};
}
#endif // SYSTEM_MANAGER_HPP
| 39.376344 | 109 | 0.57018 | [
"render"
] |
0123f8411324d2e796a9b2ee3bf1e3508ec19f24 | 9,783 | cpp | C++ | VSDataReduction/VSNSpaceCutsCalc.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | 1 | 2018-04-17T14:03:36.000Z | 2018-04-17T14:03:36.000Z | VSDataReduction/VSNSpaceCutsCalc.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | VSDataReduction/VSNSpaceCutsCalc.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | //-*-mode:c++; mode:font-lock;-*-
/*! \file VSNSpaceCutsCalc.cpp
Calculate whether event is in the array and scope filter volume
\author Stephen Fegan \n
UCLA \n
sfegan@astro.ucla.edu \n
\version 1.0
\date 05/09/2007
$Id: VSNSpaceCutsCalc.cpp,v 3.14 2009/10/08 05:26:34 matthew Exp $
*/
#include<VSNSpaceCutsCalc.hpp>
#include<VSNSpaceOctaveH5IO.hpp>
#include<VSFileUtility.hpp>
using namespace VERITAS;
// ============================================================================
// VSNSpaceFilterDatum<VSEventArrayDatum>
// ============================================================================
VSNSpaceFilterDatum<VSEventArrayDatum>::
VSNSpaceFilterDatum(const VSNSpace::Volume& vol):
m_volume(vol), m_array_datums(), m_scope_datums(), m_is_scope_datum(),
m_ndatum(0)
{
for(std::vector<VSNSpace::Axis>::const_iterator itr =
m_volume.space().axes.begin();
itr != m_volume.space().axes.end(); ++itr)
{
std::string scope_index =
VSH5DatumElementParser::getIndex(itr->name);
if(scope_index == "")
{
m_array_datums.push_back(VSH5DatumElement<VSEventArrayDatum>::
createDatumElement(itr->name));
m_is_scope_datum.push_back(false);
}
else
{
m_scope_datums.push_back(VSH5DatumElement<VSEventScopeDatum>::
createDatumElement(itr->name));
m_is_scope_datum.push_back(true);
}
m_ndatum++;
}
}
VSNSpaceFilterDatum<VSEventArrayDatum>::~VSNSpaceFilterDatum()
{
for(std::vector<VSH5DatumElement<VSEventArrayDatum>*>::iterator
itr = m_array_datums.begin(); itr != m_array_datums.end(); ++itr)
delete (*itr);
for(std::vector<VSH5DatumElement<VSEventScopeDatum>*>::iterator
itr = m_scope_datums.begin(); itr != m_scope_datums.end(); ++itr)
delete (*itr);
}
bool VSNSpaceFilterDatum<VSEventArrayDatum>::
isDatumInVolume(const VSEventArrayDatum& x) const
{
VERITAS::VSNSpace::Point point(m_ndatum);
for(unsigned i = 0; i < m_ndatum; i++)
{
vsassert(!m_is_scope_datum[i]);
if(!m_array_datums[i]->getValue(x,point.x[i])) return false;
}
return m_volume.isPointInVolume(point);
}
bool VSNSpaceFilterDatum<VSEventArrayDatum>::
isDatumInVolume(const VSEventArrayDatum& x, unsigned index) const
{
VERITAS::VSNSpace::Point point(m_ndatum);
unsigned iscope = 0;
unsigned iarray = 0;
for(unsigned i = 0; i < m_ndatum; i++)
{
if(m_is_scope_datum[i])
{
if(!m_scope_datums[iscope]->getValue(*(x.scope[index]),point.x[i]))
return false;
iscope++;
}
else
{
if(!m_array_datums[iarray]->getValue(x,point.x[i]))
return false;
iarray++;
}
}
return m_volume.isPointInVolume(point);
}
const VSNSpace::Volume& VSNSpaceFilterDatum<VSEventArrayDatum>::
getVolume() const
{
return m_volume;
}
// ============================================================================
// VSNSpaceCutsCalc
// ============================================================================
VSNSpaceCutsCalc::Options VSNSpaceCutsCalc::s_default_options;
VSNSpaceCutsCalc::VSNSpaceCutsCalc(const Options& opt):
VSCutsCalc(), m_options(opt),
m_array_filter(), m_scope_filter_default(), m_scope_filter()
{
if(!m_options.nspace_cuts_file.empty())
VSFileUtility::expandFilename(m_options.nspace_cuts_file);
if(VSFileUtility::isFile(m_options.nspace_cuts_file) &&
!m_options.nspace_cuts_file.empty() &&
VSOctaveH5ReaderStruct::isHDF5(m_options.nspace_cuts_file) )
{
std::cout << "Loading nspace cuts from file: "
<< m_options.nspace_cuts_file << std::endl;
VSOctaveH5Reader *reader =
new VSOctaveH5Reader(m_options.nspace_cuts_file);
if(reader->isStruct("nspace_cuts"))
{
VSOctaveH5ReaderStruct* s = reader->readStruct("nspace_cuts");
load(s);
delete s;
}
else load(reader);
delete reader;
}
else if(!m_options.nspace_cuts_file.empty())
{
std::cerr << m_options.nspace_cuts_file << " is not a valid file."
<< std::endl;
exit(EXIT_FAILURE);
}
}
VSNSpaceCutsCalc::
VSNSpaceCutsCalc(const VSNSpace::Volume* array_vol,
const VSNSpace::Volume* scope_vol_default,
const std::vector< const VSNSpace::Volume* >& scope_vol):
VSCutsCalc(), m_array_filter(), m_scope_filter_default(), m_scope_filter()
{
if(array_vol)m_array_filter = new ArrayFilter(*array_vol);
if(scope_vol_default)
m_scope_filter_default = new ArrayFilter(*scope_vol_default);
m_scope_filter.resize(scope_vol.size());
for(unsigned iscope=0;iscope<m_scope_filter.size();iscope++)
if(scope_vol[iscope])
m_scope_filter[iscope] = new ScopeFilter(*scope_vol[iscope]);
}
VSNSpaceCutsCalc::~VSNSpaceCutsCalc()
{
delete m_array_filter;
delete m_scope_filter_default;
for(unsigned iscope=0;iscope<m_scope_filter.size();iscope++)
delete m_scope_filter[iscope];
}
void VSNSpaceCutsCalc::
getCutResults(VSArrayCutsDatum& cut_results, const VSEventArrayDatum& event)
{
const unsigned nscope_results = cut_results.scope.size();
const unsigned nscope = event.scope.size();
if(nscope_results < nscope)
{
cut_results.scope.resize(nscope);
for(unsigned iscope = nscope_results; iscope < nscope; iscope++)
if(cut_results.scope[iscope] == NULL)
cut_results.scope[iscope] = new VSScopeCutsDatum;
}
if(m_array_filter)
cut_results.passed_array_cut = m_array_filter->isDatumInVolume(event);
else
cut_results.passed_array_cut = true;
unsigned npassed = 0;
for(unsigned iscope=0;iscope<nscope;iscope++)
{
if(event.scope[iscope] == NULL)
continue;
else if(iscope < m_scope_filter.size() && m_scope_filter[iscope])
{
bool passed = event.scope[iscope]->has_image
&& m_scope_filter[iscope]->isDatumInVolume(*event.scope[iscope]);
cut_results.scope[iscope]->passed_scope_cut = passed;
if(passed)npassed++;
}
else if(m_scope_filter_default)
{
// bool passed = event.scope[iscope]->has_image
// && m_scope_filter_default->isDatumInVolume(*event.scope[iscope]);
bool passed = event.scope[iscope]->has_image
&& m_scope_filter_default->isDatumInVolume(event,iscope);
cut_results.scope[iscope]->passed_scope_cut = passed;
if(passed)npassed++;
}
else
{
cut_results.scope[iscope]->passed_scope_cut = true;
npassed++;
}
}
cut_results.npassed_scope_cut = npassed;
if(cut_results.passed_array_cut &&
cut_results.npassed_scope_cut >= m_options.nscope)
cut_results.passed_cuts = true;
else
cut_results.passed_cuts = false;
}
void VSNSpaceCutsCalc::clear()
{
delete m_array_filter, m_array_filter = NULL;
delete m_scope_filter_default, m_scope_filter_default = NULL;
const unsigned nscope = m_scope_filter.size();
for(unsigned iscope = 0; iscope < nscope; iscope++)
delete m_scope_filter[iscope];
m_scope_filter.clear();
}
bool VSNSpaceCutsCalc::load(VSOctaveH5ReaderStruct* reader)
{
reader->readScalar("nscope_cut",m_options.nscope);
VSNSpaceOctaveH5IO io;
if(reader->isStruct("array"))
{
VSOctaveH5ReaderStruct* s2 = reader->readStruct("array");
VSNSpace::Volume* array_vol = new VSNSpace::Volume;
io.readVolume(s2,*array_vol);
m_array_filter = new ArrayFilter(*array_vol);
delete array_vol;
delete s2;
}
if(reader->isStruct("scope_default"))
{
VSOctaveH5ReaderStruct* s2 =
reader->readStruct("scope_default");
VSNSpace::Volume* scope_vol_default = new VSNSpace::Volume;
io.readVolume(s2,*scope_vol_default);
m_scope_filter_default = new ArrayFilter(*scope_vol_default);
delete scope_vol_default;
delete s2;
}
if(reader->isCellVector("scope"))
{
VSOctaveH5ReaderCellVector* c = reader->readCellVector("scope");
unsigned nscope = c->dimensions();
m_scope_filter.resize(nscope);
for(unsigned iscope=0;iscope<nscope;iscope++)
if(c->isStruct(iscope))
{
VSOctaveH5ReaderStruct* s2 = c->readStruct(iscope);
VSNSpace::Volume* scope_vol = new VSNSpace::Volume;
io.readVolume(s2,*scope_vol);
m_scope_filter[iscope] = new ScopeFilter(*scope_vol);
delete scope_vol;
delete s2;
}
delete c;
}
return true;
}
bool VSNSpaceCutsCalc::save(VSOctaveH5WriterStruct* writer)
{
writer->writeScalar("nscope_cut",m_options.nscope);
VSNSpaceOctaveH5IO io;
if(m_array_filter != NULL)
{
VSOctaveH5WriterStruct* ws = writer->writeStruct("array");
io.writeVolume(ws,m_array_filter->getVolume());
}
if(m_scope_filter_default != NULL)
{
VSOctaveH5WriterStruct* ws = writer->writeStruct("scope_default");
io.writeVolume(ws,m_scope_filter_default->getVolume());
}
if(m_scope_filter.size() > 0)
{
const unsigned nscope = m_scope_filter.size();
VSOctaveH5WriterCellVector* wc = writer->writeCellVector("scope",nscope);
for(unsigned iscope=0;iscope<nscope;iscope++)
{
if(m_scope_filter[iscope] == NULL) continue;
VSOctaveH5WriterStruct* ws = wc->writeStruct(iscope);
io.writeVolume(ws,m_scope_filter[iscope]->getVolume());
}
}
return true;
}
#define OPTNAME(x,y) std::string(x)+std::string(y)
void VSNSpaceCutsCalc::configure(VSOptions& options,
const std::string& profile,
const std::string& opt_prefix)
{
options.findWithValue(OPTNAME(opt_prefix,"nspace_cuts"),
s_default_options.nspace_cuts_file,
"HDF5 file defining a set of nspace volumes "
"used to select events.",
OPTNAME(opt_prefix,"cuts"));
options.findWithValue(OPTNAME(opt_prefix,"nspace_cuts_nscope"),
s_default_options.nscope,
"Minimum number of telescopes which must pass all "
"scope-level cuts.",
OPTNAME(opt_prefix,"cuts"));
}
| 28.438953 | 79 | 0.676071 | [
"vector"
] |
012ee24f38b5dc62371986cab78ac4bf2be279cf | 14,409 | cxx | C++ | main/sc/source/filter/excel/xlroot.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sc/source/filter/excel/xlroot.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sc/source/filter/excel/xlroot.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_scfilt.hxx"
#include "xlroot.hxx"
#include <com/sun/star/awt/XDevice.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/XFramesSupplier.hpp>
#include <com/sun/star/i18n/ScriptType.hpp>
#include <comphelper/processfactory.hxx>
#include <vcl/svapp.hxx>
#include <svl/stritem.hxx>
#include <svl/languageoptions.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/printer.hxx>
#include <sfx2/docfile.hxx>
#include <vcl/font.hxx>
#include <editeng/editstat.hxx>
#include "scitems.hxx"
#include <editeng/eeitem.hxx>
#include "document.hxx"
#include "docpool.hxx"
#include "docuno.hxx"
#include "editutil.hxx"
#include "drwlayer.hxx"
#include "scextopt.hxx"
#include "patattr.hxx"
#include "fapihelper.hxx"
#include "xlconst.hxx"
#include "xlstyle.hxx"
#include "xlchart.hxx"
#include "xltracer.hxx"
#include <unotools/useroptions.hxx>
#include "root.hxx"
namespace ApiScriptType = ::com::sun::star::i18n::ScriptType;
using ::rtl::OUString;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::uno::UNO_SET_THROW;
using ::com::sun::star::awt::XDevice;
using ::com::sun::star::awt::DeviceInfo;
using ::com::sun::star::frame::XFrame;
using ::com::sun::star::frame::XFramesSupplier;
using ::com::sun::star::lang::XMultiServiceFactory;
using namespace ::com::sun::star;
// Global data ================================================================
#ifdef DBG_UTIL
XclDebugObjCounter::~XclDebugObjCounter()
{
DBG_ASSERT( mnObjCnt == 0, "XclDebugObjCounter::~XclDebugObjCounter - wrong root object count" );
}
#endif
// ----------------------------------------------------------------------------
XclRootData::XclRootData( XclBiff eBiff, SfxMedium& rMedium,
SotStorageRef xRootStrg, ScDocument& rDoc, rtl_TextEncoding eTextEnc, bool bExport ) :
meBiff( eBiff ),
meOutput( EXC_OUTPUT_BINARY ),
mrMedium( rMedium ),
mxRootStrg( xRootStrg ),
mrDoc( rDoc ),
maDefPassword( CREATE_STRING( "VelvetSweatshop" ) ),
meTextEnc( eTextEnc ),
meSysLang( Application::GetSettings().GetLanguage() ),
meDocLang( Application::GetSettings().GetLanguage() ),
meUILang( Application::GetSettings().GetUILanguage() ),
mnDefApiScript( ApiScriptType::LATIN ),
maScMaxPos( MAXCOL, MAXROW, MAXTAB ),
maXclMaxPos( EXC_MAXCOL2, EXC_MAXROW2, EXC_MAXTAB2 ),
maMaxPos( EXC_MAXCOL2, EXC_MAXROW2, EXC_MAXTAB2 ),
mxFontPropSetHlp( new XclFontPropSetHelper ),
mxChPropSetHlp( new XclChPropSetHelper ),
mxRD( new RootData ),//!
mfScreenPixelX( 50.0 ),
mfScreenPixelY( 50.0 ),
mnCharWidth( 110 ),
mnScTab( 0 ),
mbExport( bExport )
{
maUserName = SvtUserOptions().GetLastName();
if( maUserName.Len() == 0 )
maUserName = CREATE_STRING( "Calc" );
switch( ScGlobal::GetDefaultScriptType() )
{
case SCRIPTTYPE_LATIN: mnDefApiScript = ApiScriptType::LATIN; break;
case SCRIPTTYPE_ASIAN: mnDefApiScript = ApiScriptType::ASIAN; break;
case SCRIPTTYPE_COMPLEX: mnDefApiScript = ApiScriptType::COMPLEX; break;
default: DBG_ERRORFILE( "XclRootData::XclRootData - unknown script type" );
}
// maximum cell position
switch( meBiff )
{
case EXC_BIFF2: maXclMaxPos.Set( EXC_MAXCOL2, EXC_MAXROW2, EXC_MAXTAB2 ); break;
case EXC_BIFF3: maXclMaxPos.Set( EXC_MAXCOL3, EXC_MAXROW3, EXC_MAXTAB3 ); break;
case EXC_BIFF4: maXclMaxPos.Set( EXC_MAXCOL4, EXC_MAXROW4, EXC_MAXTAB4 ); break;
case EXC_BIFF5: maXclMaxPos.Set( EXC_MAXCOL5, EXC_MAXROW5, EXC_MAXTAB5 ); break;
case EXC_BIFF8: maXclMaxPos.Set( EXC_MAXCOL8, EXC_MAXROW8, EXC_MAXTAB8 ); break;
default: DBG_ERROR_BIFF();
}
maMaxPos.SetCol( ::std::min( maScMaxPos.Col(), maXclMaxPos.Col() ) );
maMaxPos.SetRow( ::std::min( maScMaxPos.Row(), maXclMaxPos.Row() ) );
maMaxPos.SetTab( ::std::min( maScMaxPos.Tab(), maXclMaxPos.Tab() ) );
// document URL and path
if( const SfxItemSet* pItemSet = mrMedium.GetItemSet() )
if( const SfxStringItem* pItem = static_cast< const SfxStringItem* >( pItemSet->GetItem( SID_FILE_NAME ) ) )
maDocUrl = pItem->GetValue();
maBasePath = maDocUrl.Copy( 0, maDocUrl.SearchBackward( '/' ) + 1 );
// extended document options - always own object, try to copy existing data from document
if( const ScExtDocOptions* pOldDocOpt = mrDoc.GetExtDocOptions() )
mxExtDocOpt.reset( new ScExtDocOptions( *pOldDocOpt ) );
else
mxExtDocOpt.reset( new ScExtDocOptions );
// screen pixel size
try
{
Reference< XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory(), UNO_SET_THROW );
Reference< XFramesSupplier > xFramesSupp( xFactory->createInstance( CREATE_OUSTRING( "com.sun.star.frame.Desktop" ) ), UNO_QUERY_THROW );
Reference< XFrame > xFrame( xFramesSupp->getActiveFrame(), UNO_SET_THROW );
Reference< XDevice > xDevice( xFrame->getContainerWindow(), UNO_QUERY_THROW );
DeviceInfo aDeviceInfo = xDevice->getInfo();
mfScreenPixelX = (aDeviceInfo.PixelPerMeterX > 0) ? (100000.0 / aDeviceInfo.PixelPerMeterX) : 50.0;
mfScreenPixelY = (aDeviceInfo.PixelPerMeterY > 0) ? (100000.0 / aDeviceInfo.PixelPerMeterY) : 50.0;
}
catch( Exception& )
{
OSL_ENSURE( false, "XclRootData::XclRootData - cannot get output device info" );
}
}
XclRootData::~XclRootData()
{
}
// ----------------------------------------------------------------------------
XclRoot::XclRoot( XclRootData& rRootData ) :
mrData( rRootData )
{
#ifdef DBG_UTIL
++mrData.mnObjCnt;
#endif
// filter tracer
// do not use CREATE_OUSTRING for conditional expression
mrData.mxTracer.reset( new XclTracer( GetDocUrl(), OUString::createFromAscii(
IsExport() ? "Office.Tracing/Export/Excel" : "Office.Tracing/Import/Excel" ) ) );
}
XclRoot::XclRoot( const XclRoot& rRoot ) :
mrData( rRoot.mrData )
{
#ifdef DBG_UTIL
++mrData.mnObjCnt;
#endif
}
XclRoot::~XclRoot()
{
#ifdef DBG_UTIL
--mrData.mnObjCnt;
#endif
}
XclRoot& XclRoot::operator=( const XclRoot& rRoot )
{
(void)rRoot; // avoid compiler warning
// allowed for assignment in derived classes - but test if the same root data is used
DBG_ASSERT( &mrData == &rRoot.mrData, "XclRoot::operator= - incompatible root data" );
return *this;
}
void XclRoot::SetTextEncoding( rtl_TextEncoding eTextEnc )
{
if( eTextEnc != RTL_TEXTENCODING_DONTKNOW )
mrData.meTextEnc = eTextEnc;
}
void XclRoot::SetCharWidth( const XclFontData& rFontData )
{
mrData.mnCharWidth = 0;
if( OutputDevice* pPrinter = GetPrinter() )
{
Font aFont( rFontData.maName, Size( 0, rFontData.mnHeight ) );
aFont.SetFamily( rFontData.GetScFamily( GetTextEncoding() ) );
aFont.SetCharSet( rFontData.GetFontEncoding() );
aFont.SetWeight( rFontData.GetScWeight() );
pPrinter->SetFont( aFont );
mrData.mnCharWidth = pPrinter->GetTextWidth( String( '0' ) );
}
if( mrData.mnCharWidth <= 0 )
{
// #i48717# Win98 with HP LaserJet returns 0
DBG_ERRORFILE( "XclRoot::SetCharWidth - invalid character width (no printer?)" );
mrData.mnCharWidth = 11 * rFontData.mnHeight / 20;
}
}
sal_Int32 XclRoot::GetHmmFromPixelX( double fPixelX ) const
{
return static_cast< sal_Int32 >( fPixelX * mrData.mfScreenPixelX + 0.5 );
}
sal_Int32 XclRoot::GetHmmFromPixelY( double fPixelY ) const
{
return static_cast< sal_Int32 >( fPixelY * mrData.mfScreenPixelY + 0.5 );
}
uno::Sequence< beans::NamedValue > XclRoot::RequestEncryptionData( ::comphelper::IDocPasswordVerifier& rVerifier ) const
{
::std::vector< OUString > aDefaultPasswords;
aDefaultPasswords.push_back( mrData.maDefPassword );
return ScfApiHelper::QueryEncryptionDataForMedium( mrData.mrMedium, rVerifier, &aDefaultPasswords );
}
bool XclRoot::HasVbaStorage() const
{
SotStorageRef xRootStrg = GetRootStorage();
return xRootStrg.Is() && xRootStrg->IsContained( EXC_STORAGE_VBA_PROJECT );
}
SotStorageRef XclRoot::OpenStorage( SotStorageRef xStrg, const String& rStrgName ) const
{
return mrData.mbExport ?
ScfTools::OpenStorageWrite( xStrg, rStrgName ) :
ScfTools::OpenStorageRead( xStrg, rStrgName );
}
SotStorageRef XclRoot::OpenStorage( const String& rStrgName ) const
{
return OpenStorage( GetRootStorage(), rStrgName );
}
SotStorageStreamRef XclRoot::OpenStream( SotStorageRef xStrg, const String& rStrmName ) const
{
return mrData.mbExport ?
ScfTools::OpenStorageStreamWrite( xStrg, rStrmName ) :
ScfTools::OpenStorageStreamRead( xStrg, rStrmName );
}
SotStorageStreamRef XclRoot::OpenStream( const String& rStrmName ) const
{
return OpenStream( GetRootStorage(), rStrmName );
}
SfxObjectShell* XclRoot::GetDocShell() const
{
return GetDoc().GetDocumentShell();
}
ScModelObj* XclRoot::GetDocModelObj() const
{
SfxObjectShell* pDocShell = GetDocShell();
return pDocShell ? ScModelObj::getImplementation( pDocShell->GetModel() ) : 0;
}
OutputDevice* XclRoot::GetPrinter() const
{
return GetDoc().GetRefDevice();
}
ScStyleSheetPool& XclRoot::GetStyleSheetPool() const
{
return *GetDoc().GetStyleSheetPool();
}
ScRangeName& XclRoot::GetNamedRanges() const
{
return *GetDoc().GetRangeName();
}
ScDBCollection& XclRoot::GetDatabaseRanges() const
{
return *GetDoc().GetDBCollection();
}
SdrPage* XclRoot::GetSdrPage( SCTAB nScTab ) const
{
return ((nScTab >= 0) && GetDoc().GetDrawLayer()) ?
GetDoc().GetDrawLayer()->GetPage( static_cast< sal_uInt16 >( nScTab ) ) : 0;
}
SvNumberFormatter& XclRoot::GetFormatter() const
{
return *GetDoc().GetFormatTable();
}
DateTime XclRoot::GetNullDate() const
{
return *GetFormatter().GetNullDate();
}
sal_uInt16 XclRoot::GetBaseYear() const
{
// return 1904 for 1904-01-01, and 1900 for 1899-12-30
return (GetNullDate().GetYear() == 1904) ? 1904 : 1900;
}
double XclRoot::GetDoubleFromDateTime( const DateTime& rDateTime ) const
{
double fValue = rDateTime - GetNullDate();
// adjust dates before 1900-03-01 to get correct time values in the range [0.0,1.0)
if( rDateTime < DateTime( Date( 1, 3, 1900 ) ) )
fValue -= 1.0;
return fValue;
}
DateTime XclRoot::GetDateTimeFromDouble( double fValue ) const
{
DateTime aDateTime = GetNullDate() + fValue;
// adjust dates before 1900-03-01 to get correct time values
if( aDateTime < DateTime( Date( 1, 3, 1900 ) ) )
aDateTime += 1L;
return aDateTime;
}
ScEditEngineDefaulter& XclRoot::GetEditEngine() const
{
if( !mrData.mxEditEngine.get() )
{
mrData.mxEditEngine.reset( new ScEditEngineDefaulter( GetDoc().GetEnginePool() ) );
ScEditEngineDefaulter& rEE = *mrData.mxEditEngine;
rEE.SetRefMapMode( MAP_100TH_MM );
rEE.SetEditTextObjectPool( GetDoc().GetEditPool() );
rEE.SetUpdateMode( sal_False );
rEE.EnableUndo( sal_False );
rEE.SetControlWord( rEE.GetControlWord() & ~EE_CNTRL_ALLOWBIGOBJS );
}
return *mrData.mxEditEngine;
}
ScHeaderEditEngine& XclRoot::GetHFEditEngine() const
{
if( !mrData.mxHFEditEngine.get() )
{
mrData.mxHFEditEngine.reset( new ScHeaderEditEngine( EditEngine::CreatePool(), sal_True ) );
ScHeaderEditEngine& rEE = *mrData.mxHFEditEngine;
rEE.SetRefMapMode( MAP_TWIP ); // headers/footers use twips as default metric
rEE.SetUpdateMode( sal_False );
rEE.EnableUndo( sal_False );
rEE.SetControlWord( rEE.GetControlWord() & ~EE_CNTRL_ALLOWBIGOBJS );
// set Calc header/footer defaults
SfxItemSet* pEditSet = new SfxItemSet( rEE.GetEmptyItemSet() );
SfxItemSet aItemSet( *GetDoc().GetPool(), ATTR_PATTERN_START, ATTR_PATTERN_END );
ScPatternAttr::FillToEditItemSet( *pEditSet, aItemSet );
// FillToEditItemSet() adjusts font height to 1/100th mm, we need twips
pEditSet->Put( aItemSet.Get( ATTR_FONT_HEIGHT ), EE_CHAR_FONTHEIGHT );
pEditSet->Put( aItemSet.Get( ATTR_CJK_FONT_HEIGHT ), EE_CHAR_FONTHEIGHT_CJK );
pEditSet->Put( aItemSet.Get( ATTR_CTL_FONT_HEIGHT ), EE_CHAR_FONTHEIGHT_CTL );
rEE.SetDefaults( pEditSet ); // takes ownership
}
return *mrData.mxHFEditEngine;
}
EditEngine& XclRoot::GetDrawEditEngine() const
{
if( !mrData.mxDrawEditEng.get() )
{
mrData.mxDrawEditEng.reset( new EditEngine( &GetDoc().GetDrawLayer()->GetItemPool() ) );
EditEngine& rEE = *mrData.mxDrawEditEng;
rEE.SetRefMapMode( MAP_100TH_MM );
rEE.SetUpdateMode( sal_False );
rEE.EnableUndo( sal_False );
rEE.SetControlWord( rEE.GetControlWord() & ~EE_CNTRL_ALLOWBIGOBJS );
}
return *mrData.mxDrawEditEng;
}
XclFontPropSetHelper& XclRoot::GetFontPropSetHelper() const
{
return *mrData.mxFontPropSetHlp;
}
XclChPropSetHelper& XclRoot::GetChartPropSetHelper() const
{
return *mrData.mxChPropSetHlp;
}
ScExtDocOptions& XclRoot::GetExtDocOptions() const
{
return *mrData.mxExtDocOpt;
}
XclTracer& XclRoot::GetTracer() const
{
return *mrData.mxTracer;
}
// ============================================================================
| 33.983491 | 145 | 0.677146 | [
"object",
"vector"
] |
013a511f7c547a7bae7458790a4868990f50bc27 | 12,612 | hpp | C++ | include/Org/BouncyCastle/Math/EC/FpFieldElement.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Org/BouncyCastle/Math/EC/FpFieldElement.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Org/BouncyCastle/Math/EC/FpFieldElement.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: Org.BouncyCastle.Math.EC.AbstractFpFieldElement
#include "Org/BouncyCastle/Math/EC/AbstractFpFieldElement.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Org::BouncyCastle::Math
namespace Org::BouncyCastle::Math {
// Forward declaring type: BigInteger
class BigInteger;
}
// Forward declaring namespace: Org::BouncyCastle::Math::EC
namespace Org::BouncyCastle::Math::EC {
// Skipping declaration: ECFieldElement because it is already included!
}
// Completed forward declares
// Type namespace: Org.BouncyCastle.Math.EC
namespace Org::BouncyCastle::Math::EC {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: Org.BouncyCastle.Math.EC.FpFieldElement
class FpFieldElement : public Org::BouncyCastle::Math::EC::AbstractFpFieldElement {
public:
// private readonly Org.BouncyCastle.Math.BigInteger q
// Size: 0x8
// Offset: 0x10
Org::BouncyCastle::Math::BigInteger* q;
// Field size check
static_assert(sizeof(Org::BouncyCastle::Math::BigInteger*) == 0x8);
// private readonly Org.BouncyCastle.Math.BigInteger r
// Size: 0x8
// Offset: 0x18
Org::BouncyCastle::Math::BigInteger* r;
// Field size check
static_assert(sizeof(Org::BouncyCastle::Math::BigInteger*) == 0x8);
// private readonly Org.BouncyCastle.Math.BigInteger x
// Size: 0x8
// Offset: 0x20
Org::BouncyCastle::Math::BigInteger* x;
// Field size check
static_assert(sizeof(Org::BouncyCastle::Math::BigInteger*) == 0x8);
// Creating value type constructor for type: FpFieldElement
FpFieldElement(Org::BouncyCastle::Math::BigInteger* q_ = {}, Org::BouncyCastle::Math::BigInteger* r_ = {}, Org::BouncyCastle::Math::BigInteger* x_ = {}) noexcept : q{q_}, r{r_}, x{x_} {}
// static Org.BouncyCastle.Math.BigInteger CalculateResidue(Org.BouncyCastle.Math.BigInteger p)
// Offset: 0x2139FB4
static Org::BouncyCastle::Math::BigInteger* CalculateResidue(Org::BouncyCastle::Math::BigInteger* p);
// System.Void .ctor(Org.BouncyCastle.Math.BigInteger q, Org.BouncyCastle.Math.BigInteger r, Org.BouncyCastle.Math.BigInteger x)
// Offset: 0x213A3EC
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static FpFieldElement* New_ctor(Org::BouncyCastle::Math::BigInteger* q, Org::BouncyCastle::Math::BigInteger* r, Org::BouncyCastle::Math::BigInteger* x) {
static auto ___internal__logger = ::Logger::get().WithContext("Org::BouncyCastle::Math::EC::FpFieldElement::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<FpFieldElement*, creationType>(q, r, x)));
}
// private Org.BouncyCastle.Math.EC.ECFieldElement CheckSqrt(Org.BouncyCastle.Math.EC.ECFieldElement z)
// Offset: 0x213B8B4
Org::BouncyCastle::Math::EC::ECFieldElement* CheckSqrt(Org::BouncyCastle::Math::EC::ECFieldElement* z);
// private Org.BouncyCastle.Math.BigInteger[] LucasSequence(Org.BouncyCastle.Math.BigInteger P, Org.BouncyCastle.Math.BigInteger Q, Org.BouncyCastle.Math.BigInteger k)
// Offset: 0x213B90C
::Array<Org::BouncyCastle::Math::BigInteger*>* LucasSequence(Org::BouncyCastle::Math::BigInteger* P, Org::BouncyCastle::Math::BigInteger* Q, Org::BouncyCastle::Math::BigInteger* k);
// protected Org.BouncyCastle.Math.BigInteger ModAdd(Org.BouncyCastle.Math.BigInteger x1, Org.BouncyCastle.Math.BigInteger x2)
// Offset: 0x213BE5C
Org::BouncyCastle::Math::BigInteger* ModAdd(Org::BouncyCastle::Math::BigInteger* x1, Org::BouncyCastle::Math::BigInteger* x2);
// protected Org.BouncyCastle.Math.BigInteger ModDouble(Org.BouncyCastle.Math.BigInteger x)
// Offset: 0x213BEC4
Org::BouncyCastle::Math::BigInteger* ModDouble(Org::BouncyCastle::Math::BigInteger* x);
// protected Org.BouncyCastle.Math.BigInteger ModHalfAbs(Org.BouncyCastle.Math.BigInteger x)
// Offset: 0x213BF30
Org::BouncyCastle::Math::BigInteger* ModHalfAbs(Org::BouncyCastle::Math::BigInteger* x);
// protected Org.BouncyCastle.Math.BigInteger ModInverse(Org.BouncyCastle.Math.BigInteger x)
// Offset: 0x213BF94
Org::BouncyCastle::Math::BigInteger* ModInverse(Org::BouncyCastle::Math::BigInteger* x);
// protected Org.BouncyCastle.Math.BigInteger ModMult(Org.BouncyCastle.Math.BigInteger x1, Org.BouncyCastle.Math.BigInteger x2)
// Offset: 0x213C074
Org::BouncyCastle::Math::BigInteger* ModMult(Org::BouncyCastle::Math::BigInteger* x1, Org::BouncyCastle::Math::BigInteger* x2);
// protected Org.BouncyCastle.Math.BigInteger ModReduce(Org.BouncyCastle.Math.BigInteger x)
// Offset: 0x213C0BC
Org::BouncyCastle::Math::BigInteger* ModReduce(Org::BouncyCastle::Math::BigInteger* x);
// protected Org.BouncyCastle.Math.BigInteger ModSubtract(Org.BouncyCastle.Math.BigInteger x1, Org.BouncyCastle.Math.BigInteger x2)
// Offset: 0x213C3EC
Org::BouncyCastle::Math::BigInteger* ModSubtract(Org::BouncyCastle::Math::BigInteger* x1, Org::BouncyCastle::Math::BigInteger* x2);
// public System.Boolean Equals(Org.BouncyCastle.Math.EC.FpFieldElement other)
// Offset: 0x213C4FC
bool Equals(Org::BouncyCastle::Math::EC::FpFieldElement* other);
// public override Org.BouncyCastle.Math.BigInteger ToBigInteger()
// Offset: 0x213A804
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.BigInteger ECFieldElement::ToBigInteger()
Org::BouncyCastle::Math::BigInteger* ToBigInteger();
// public override System.Int32 get_FieldSize()
// Offset: 0x213A80C
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: System.Int32 ECFieldElement::get_FieldSize()
int get_FieldSize();
// public override Org.BouncyCastle.Math.EC.ECFieldElement Add(Org.BouncyCastle.Math.EC.ECFieldElement b)
// Offset: 0x213A828
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::Add(Org.BouncyCastle.Math.EC.ECFieldElement b)
Org::BouncyCastle::Math::EC::ECFieldElement* Add(Org::BouncyCastle::Math::EC::ECFieldElement* b);
// public override Org.BouncyCastle.Math.EC.ECFieldElement AddOne()
// Offset: 0x213A8E8
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::AddOne()
Org::BouncyCastle::Math::EC::ECFieldElement* AddOne();
// public override Org.BouncyCastle.Math.EC.ECFieldElement Subtract(Org.BouncyCastle.Math.EC.ECFieldElement b)
// Offset: 0x213A9DC
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::Subtract(Org.BouncyCastle.Math.EC.ECFieldElement b)
Org::BouncyCastle::Math::EC::ECFieldElement* Subtract(Org::BouncyCastle::Math::EC::ECFieldElement* b);
// public override Org.BouncyCastle.Math.EC.ECFieldElement Multiply(Org.BouncyCastle.Math.EC.ECFieldElement b)
// Offset: 0x213AA9C
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::Multiply(Org.BouncyCastle.Math.EC.ECFieldElement b)
Org::BouncyCastle::Math::EC::ECFieldElement* Multiply(Org::BouncyCastle::Math::EC::ECFieldElement* b);
// public override Org.BouncyCastle.Math.EC.ECFieldElement MultiplyMinusProduct(Org.BouncyCastle.Math.EC.ECFieldElement b, Org.BouncyCastle.Math.EC.ECFieldElement x, Org.BouncyCastle.Math.EC.ECFieldElement y)
// Offset: 0x213AB5C
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::MultiplyMinusProduct(Org.BouncyCastle.Math.EC.ECFieldElement b, Org.BouncyCastle.Math.EC.ECFieldElement x, Org.BouncyCastle.Math.EC.ECFieldElement y)
Org::BouncyCastle::Math::EC::ECFieldElement* MultiplyMinusProduct(Org::BouncyCastle::Math::EC::ECFieldElement* b, Org::BouncyCastle::Math::EC::ECFieldElement* x, Org::BouncyCastle::Math::EC::ECFieldElement* y);
// public override Org.BouncyCastle.Math.EC.ECFieldElement MultiplyPlusProduct(Org.BouncyCastle.Math.EC.ECFieldElement b, Org.BouncyCastle.Math.EC.ECFieldElement x, Org.BouncyCastle.Math.EC.ECFieldElement y)
// Offset: 0x213AC94
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::MultiplyPlusProduct(Org.BouncyCastle.Math.EC.ECFieldElement b, Org.BouncyCastle.Math.EC.ECFieldElement x, Org.BouncyCastle.Math.EC.ECFieldElement y)
Org::BouncyCastle::Math::EC::ECFieldElement* MultiplyPlusProduct(Org::BouncyCastle::Math::EC::ECFieldElement* b, Org::BouncyCastle::Math::EC::ECFieldElement* x, Org::BouncyCastle::Math::EC::ECFieldElement* y);
// public override Org.BouncyCastle.Math.EC.ECFieldElement Divide(Org.BouncyCastle.Math.EC.ECFieldElement b)
// Offset: 0x213AE48
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::Divide(Org.BouncyCastle.Math.EC.ECFieldElement b)
Org::BouncyCastle::Math::EC::ECFieldElement* Divide(Org::BouncyCastle::Math::EC::ECFieldElement* b);
// public override Org.BouncyCastle.Math.EC.ECFieldElement Negate()
// Offset: 0x213AF20
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::Negate()
Org::BouncyCastle::Math::EC::ECFieldElement* Negate();
// public override Org.BouncyCastle.Math.EC.ECFieldElement Square()
// Offset: 0x213AFC4
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::Square()
Org::BouncyCastle::Math::EC::ECFieldElement* Square();
// public override Org.BouncyCastle.Math.EC.ECFieldElement SquarePlusProduct(Org.BouncyCastle.Math.EC.ECFieldElement x, Org.BouncyCastle.Math.EC.ECFieldElement y)
// Offset: 0x213B05C
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::SquarePlusProduct(Org.BouncyCastle.Math.EC.ECFieldElement x, Org.BouncyCastle.Math.EC.ECFieldElement y)
Org::BouncyCastle::Math::EC::ECFieldElement* SquarePlusProduct(Org::BouncyCastle::Math::EC::ECFieldElement* x, Org::BouncyCastle::Math::EC::ECFieldElement* y);
// public override Org.BouncyCastle.Math.EC.ECFieldElement Invert()
// Offset: 0x213B1EC
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::Invert()
Org::BouncyCastle::Math::EC::ECFieldElement* Invert();
// public override Org.BouncyCastle.Math.EC.ECFieldElement Sqrt()
// Offset: 0x213B280
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: Org.BouncyCastle.Math.EC.ECFieldElement ECFieldElement::Sqrt()
Org::BouncyCastle::Math::EC::ECFieldElement* Sqrt();
// public override System.Boolean Equals(System.Object obj)
// Offset: 0x213C440
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: System.Boolean ECFieldElement::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj);
// public override System.Int32 GetHashCode()
// Offset: 0x213C558
// Implemented from: Org.BouncyCastle.Math.EC.ECFieldElement
// Base method: System.Int32 ECFieldElement::GetHashCode()
int GetHashCode();
}; // Org.BouncyCastle.Math.EC.FpFieldElement
#pragma pack(pop)
static check_size<sizeof(FpFieldElement), 32 + sizeof(Org::BouncyCastle::Math::BigInteger*)> __Org_BouncyCastle_Math_EC_FpFieldElementSizeCheck;
static_assert(sizeof(FpFieldElement) == 0x28);
}
DEFINE_IL2CPP_ARG_TYPE(Org::BouncyCastle::Math::EC::FpFieldElement*, "Org.BouncyCastle.Math.EC", "FpFieldElement");
| 70.853933 | 226 | 0.740327 | [
"object"
] |
013a93fb8a2d13547ee5ee372d5e33e65e57489d | 42,581 | cc | C++ | tests/unit/io/Serialization_unittest.cc | srgnuclear/shogun | 33c04f77a642416376521b0cd1eed29b3256ac13 | [
"Ruby",
"MIT"
] | 1 | 2015-11-05T18:31:14.000Z | 2015-11-05T18:31:14.000Z | tests/unit/io/Serialization_unittest.cc | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | tests/unit/io/Serialization_unittest.cc | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2013 Soumyajit De
*/
#include <shogun/lib/common.h>
#include <shogun/base/Parameter.h>
#include <shogun/io/SerializableAsciiFile.h>
#include <shogun/io/SerializableJsonFile.h>
#include <shogun/io/SerializableXmlFile.h>
#include <shogun/io/SerializableHdf5File.h>
#include <gtest/gtest.h>
#include <shogun/lib/SGVector.h>
#include <shogun/lib/SGMatrix.h>
using namespace shogun;
TEST(Serialization, Ascii_scalar_equal_BOOL)
{
bool a=true;
bool b=false;
TSGDataType type(CT_SCALAR, ST_NONE, PT_BOOL);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="bool_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_CHAR)
{
char a='a';
char b='b';
TSGDataType type(CT_SCALAR, ST_NONE, PT_CHAR);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="char_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_INT8)
{
int8_t a=1;
int8_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT8);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int8_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_UINT8)
{
uint8_t a=1;
uint8_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT8);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint8_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_INT16)
{
int16_t a=1;
int16_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT16);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int16_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_UINT16)
{
uint16_t a=1;
uint16_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT16);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint16_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_INT32)
{
int32_t a=1;
int32_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT32);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int32_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_UINT32)
{
uint32_t a=1;
uint32_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT32);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint32_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_INT64)
{
int64_t a=1;
int64_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int64_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_UINT64)
{
uint64_t a=1;
uint64_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint64_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_FLOAT32)
{
float32_t a=1.71265;
float32_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOAT32);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="float32_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_FLOAT64)
{
float64_t a=1.7126587125;
float64_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOAT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="float64_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_FLOATMAX)
{
floatmax_t a=1.7126587125;
floatmax_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOATMAX);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="floatmax_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=1E-15;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_scalar_equal_COMPLEX128)
{
complex128_t a(1.7126587125, 2.7126587125);
complex128_t b(0.0, 0.0);
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOAT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="complex128_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_vector_equal_FLOAT64)
{
SGVector<float64_t> a(2);
SGVector<float64_t> b(2);
a.set_const(1.14263158);
b.zero();
TSGDataType type(CT_SGVECTOR, ST_NONE, PT_FLOAT64, &a.vlen);
TParameter* param1=new TParameter(&type, &a.vector, "param", "");
TParameter* param2=new TParameter(&type, &b.vector, "param", "");
const char* filename="float64_sgvec_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_vector_equal_COMPLEX128)
{
SGVector<complex128_t> a(2);
SGVector<complex128_t> b(2);
a.set_const(complex128_t(1.14263158, 2.83645548));
b.zero();
TSGDataType type(CT_SGVECTOR, ST_NONE, PT_COMPLEX128, &a.vlen);
TParameter* param1=new TParameter(&type, &a.vector, "param", "");
TParameter* param2=new TParameter(&type, &b.vector, "param", "");
const char* filename="complex128_sgvec_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_matrix_equal_FLOAT64)
{
SGMatrix<float64_t> a(2, 2);
SGMatrix<float64_t> b(2, 2);
a.set_const(1.14263158);
b.zero();
TSGDataType type(CT_SGMATRIX, ST_NONE, PT_FLOAT64, &a.num_rows, &a.num_cols);
TParameter* param1=new TParameter(&type, &a.matrix, "param", "");
TParameter* param2=new TParameter(&type, &b.matrix, "param", "");
const char* filename="float64_sgmat_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Ascii_matrix_equal_COMPLEX128)
{
SGMatrix<complex128_t> a(2, 2);
SGMatrix<complex128_t> b(2, 2);
a.set_const(complex128_t(1.14263158, 2.435754));
b.zero();
TSGDataType type(CT_SGMATRIX, ST_NONE, PT_COMPLEX128, &a.num_rows, &a.num_cols);
TParameter* param1=new TParameter(&type, &a.matrix, "param", "");
TParameter* param2=new TParameter(&type, &b.matrix, "param", "");
const char* filename="complex128_sgmat_param.txt";
// save parameter to an ascii file
CSerializableAsciiFile *file=new CSerializableAsciiFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from an ascii file
file=new CSerializableAsciiFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
#ifdef HAVE_JSON
TEST(Serialization, Json_scalar_equal_BOOL)
{
bool a=true;
bool b=false;
TSGDataType type(CT_SCALAR, ST_NONE, PT_BOOL);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="bool_param.json";
// save parameter to a json file
CSerializableJsonFile *file=new CSerializableJsonFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a json file
file=new CSerializableJsonFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Json_scalar_equal_FLOAT32)
{
float32_t a=1.7325;
float32_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOAT32);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="float32_param.json";
// save parameter to a json file
CSerializableJsonFile *file=new CSerializableJsonFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a json file
file=new CSerializableJsonFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=1E-6;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Json_scalar_equal_FLOAT64)
{
float64_t a=1.7126587125;
float64_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOAT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="float64_param.json";
// save parameter to a json file
CSerializableJsonFile *file=new CSerializableJsonFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a json file
file=new CSerializableJsonFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=1E-6;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Json_scalar_equal_FLOATMAX)
{
floatmax_t a=1.7126587125;
floatmax_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOATMAX);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="floatmax_param.json";
// save parameter to a json file
CSerializableJsonFile *file=new CSerializableJsonFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a json file
file=new CSerializableJsonFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=1E-6;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Json_vector_equal_FLOAT64)
{
SGVector<float64_t> a(2);
SGVector<float64_t> b(2);
a.set_const(1.14263158);
b.zero();
TSGDataType type(CT_SGVECTOR, ST_NONE, PT_FLOAT64, &a.vlen);
TParameter* param1=new TParameter(&type, &a.vector, "param", "");
TParameter* param2=new TParameter(&type, &b.vector, "param", "");
const char* filename="float64_sgvec_param.json";
// save parameter to a json file
CSerializableJsonFile *file=new CSerializableJsonFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a json file
file=new CSerializableJsonFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=1E-6;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Json_matrix_equal_FLOAT64)
{
SGMatrix<float64_t> a(2, 2);
SGMatrix<float64_t> b(2, 2);
a.set_const(1.14263158);
b.zero();
TSGDataType type(CT_SGMATRIX, ST_NONE, PT_FLOAT64, &a.num_rows, &a.num_cols);
TParameter* param1=new TParameter(&type, &a.matrix, "param", "");
TParameter* param2=new TParameter(&type, &b.matrix, "param", "");
const char* filename="float64_sgmat_param.json";
// save parameter to a json file
CSerializableJsonFile *file=new CSerializableJsonFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a json file
file=new CSerializableJsonFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=1E-6;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
#endif // HAVE_JSON
#ifdef HAVE_XML
TEST(Serialization, Xml_scalar_equal_BOOL)
{
bool a=true;
bool b=false;
TSGDataType type(CT_SCALAR, ST_NONE, PT_BOOL);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="bool_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_CHAR)
{
char a='a';
char b='b';
TSGDataType type(CT_SCALAR, ST_NONE, PT_CHAR);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="char_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_INT8)
{
int8_t a=1;
int8_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT8);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int8_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_UINT8)
{
uint8_t a=1;
uint8_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT8);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint8_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_INT16)
{
int16_t a=1;
int16_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT16);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int16_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_UINT16)
{
uint16_t a=1;
uint16_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT16);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint16_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_INT32)
{
int32_t a=1;
int32_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT32);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int32_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_UINT32)
{
uint32_t a=1;
uint32_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT32);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint32_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_INT64)
{
int64_t a=1;
int64_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int64_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_UINT64)
{
uint64_t a=1;
uint64_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint64_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_FLOAT32)
{
float32_t a=1.71265;
float32_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOAT32);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="float32_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=1E-15;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_FLOAT64)
{
float64_t a=1.7126587125;
float64_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOAT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="float64_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=1E-15;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_FLOATMAX)
{
floatmax_t a=1.7126587125;
floatmax_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOATMAX);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="floatmax_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=1E-15;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Xml_scalar_equal_COMPLEX128)
{
complex128_t a(1.7126587125, 1.7126587125);
complex128_t b(0.0);
TSGDataType type(CT_SCALAR, ST_NONE, PT_COMPLEX128);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="complex128_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=1E-15;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Xml_vector_equal_FLOAT64)
{
SGVector<float64_t> a(2);
SGVector<float64_t> b(2);
a.set_const(1.14263158);
b.zero();
TSGDataType type(CT_SGVECTOR, ST_NONE, PT_FLOAT64, &a.vlen);
TParameter* param1=new TParameter(&type, &a.vector, "param", "");
TParameter* param2=new TParameter(&type, &b.vector, "param", "");
const char* filename="float64_sgvec_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Xml_vector_equal_COMPLEX128)
{
SGVector<complex128_t> a(2);
SGVector<complex128_t> b(2);
a.set_const(complex128_t(1.14263158, 2.83645548));
b.zero();
TSGDataType type(CT_SGVECTOR, ST_NONE, PT_COMPLEX128, &a.vlen);
TParameter* param1=new TParameter(&type, &a.vector, "param", "");
TParameter* param2=new TParameter(&type, &b.vector, "param", "");
const char* filename="complex128_sgvec_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Xml_matrix_equal_FLOAT64)
{
SGMatrix<float64_t> a(2, 2);
SGMatrix<float64_t> b(2, 2);
a.set_const(1.14263158);
b.zero();
TSGDataType type(CT_SGMATRIX, ST_NONE, PT_FLOAT64, &a.num_rows, &a.num_cols);
TParameter* param1=new TParameter(&type, &a.matrix, "param", "");
TParameter* param2=new TParameter(&type, &b.matrix, "param", "");
const char* filename="float64_sgmat_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Xml_matrix_equal_COMPLEX128)
{
SGMatrix<complex128_t> a(2, 2);
SGMatrix<complex128_t> b(2, 2);
a.set_const(complex128_t(1.14263158, 2.435754));
b.zero();
TSGDataType type(CT_SGMATRIX, ST_NONE, PT_COMPLEX128, &a.num_rows, &a.num_cols);
TParameter* param1=new TParameter(&type, &a.matrix, "param", "");
TParameter* param2=new TParameter(&type, &b.matrix, "param", "");
const char* filename="complex128_sgmat_param.xml";
// save parameter to a xml file
CSerializableXmlFile *file=new CSerializableXmlFile(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a xml file
file=new CSerializableXmlFile(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
#endif // HAVE_XML
#ifdef HAVE_HDF5
TEST(Serialization, Hdf5_scalar_equal_BOOL)
{
bool a=true;
bool b=false;
TSGDataType type(CT_SCALAR, ST_NONE, PT_BOOL);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="bool_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_CHAR)
{
char a='a';
char b='b';
TSGDataType type(CT_SCALAR, ST_NONE, PT_CHAR);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="char_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_INT8)
{
int8_t a=1;
int8_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT8);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int8_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_UINT8)
{
uint8_t a=1;
uint8_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT8);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint8_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_INT16)
{
int16_t a=1;
int16_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT16);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int16_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_UINT16)
{
uint16_t a=1;
uint16_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT16);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint16_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_INT32)
{
int32_t a=1;
int32_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT32);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int32_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_UINT32)
{
uint32_t a=1;
uint32_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT32);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint32_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_INT64)
{
int64_t a=1;
int64_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_INT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="int64_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_UINT64)
{
uint64_t a=1;
uint64_t b=2;
TSGDataType type(CT_SCALAR, ST_NONE, PT_UINT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="uint64_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
EXPECT_TRUE(param1->equals(param2));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_FLOAT32)
{
float64_t a=1.71265;
float32_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOAT32);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="float32_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_FLOAT64)
{
float64_t a=1.7126587125;
float64_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOAT64);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="float64_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_scalar_equal_FLOATMAX)
{
floatmax_t a=1.7126587125;
floatmax_t b=0.0;
TSGDataType type(CT_SCALAR, ST_NONE, PT_FLOATMAX);
TParameter* param1=new TParameter(&type, &a, "param", "");
TParameter* param2=new TParameter(&type, &b, "param", "");
const char* filename="floatmax_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Hd5f_vector_equal_FLOAT64)
{
SGVector<float64_t> a(2);
SGVector<float64_t> b(2);
a.set_const(1.14263158);
b.zero();
TSGDataType type(CT_SGVECTOR, ST_NONE, PT_FLOAT64, &a.vlen);
TParameter* param1=new TParameter(&type, &a.vector, "param", "");
TParameter* param2=new TParameter(&type, &b.vector, "param", "");
const char* filename="float64_sgvec_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
TEST(Serialization, Hdf5_matrix_equal_FLOAT64)
{
SGMatrix<float64_t> a(2, 2);
SGMatrix<float64_t> b(2, 2);
a.set_const(1.14263158);
b.zero();
TSGDataType type(CT_SGMATRIX, ST_NONE, PT_FLOAT64, &a.num_rows, &a.num_cols);
TParameter* param1=new TParameter(&type, &a.matrix, "param", "");
TParameter* param2=new TParameter(&type, &b.matrix, "param", "");
const char* filename="float64_sgmat_param.hdf5";
// save parameter to a hdf5 file
CSerializableHdf5File *file=new CSerializableHdf5File(filename, 'w');
param1->save(file);
file->close();
SG_UNREF(file);
// load parameter from a hdf5 file
file=new CSerializableHdf5File(filename, 'r');
param2->load(file);
file->close();
SG_UNREF(file);
// check for equality
float64_t accuracy=0.0;
EXPECT_TRUE(param1->equals(param2, accuracy));
delete param1;
delete param2;
}
#endif // HAVE_HDF5
| 24.401719 | 81 | 0.7222 | [
"vector"
] |
01474a262a821c6020773b968ba9e25efca7013f | 1,534 | cpp | C++ | src/cegis/jsa/preprocessing/default_jsa_constant_strategy.cpp | lihaol/cbmc | ea3a21fb0a4e9775736cac4abf2bedfd410c7885 | [
"BSD-4-Clause"
] | 1 | 2021-08-17T08:41:12.000Z | 2021-08-17T08:41:12.000Z | src/cegis/jsa/preprocessing/default_jsa_constant_strategy.cpp | lihaol/cbmc | ea3a21fb0a4e9775736cac4abf2bedfd410c7885 | [
"BSD-4-Clause"
] | null | null | null | src/cegis/jsa/preprocessing/default_jsa_constant_strategy.cpp | lihaol/cbmc | ea3a21fb0a4e9775736cac4abf2bedfd410c7885 | [
"BSD-4-Clause"
] | null | null | null | /*******************************************************************\
Module: Counterexample-Guided Inductive Synthesis
Author: Daniel Kroening, kroening@kroening.com
Pascal Kesseli, pascal.kesseli@cs.ox.ac.uk
\*******************************************************************/
#include <util/arith_tools.h>
#include <cegis/constant/literals_collector.h>
#include <cegis/cegis-util/program_helper.h>
#include <cegis/jsa/value/jsa_types.h>
#include <cegis/jsa/instrument/jsa_meta_data.h>
#include <cegis/jsa/preprocessing/add_constraint_meta_variables.h>
#include <cegis/jsa/preprocessing/default_jsa_constant_strategy.h>
namespace
{
std::string get_name(size_t index)
{
std::string name(JSA_CONSTANT_PREFIX);
return name+=integer2string(index);
}
}
goto_programt::targett default_jsa_constant_strategy(symbol_tablet &st,
goto_functionst &gf)
{
const std::vector<constant_exprt> literals(collect_integer_literals(st, gf));
const typet word_type(jsa_word_type());
size_t const_index=0u;
goto_programt &body=get_entry_body(gf);
goto_programt::targett pos=body.instructions.begin();
for (const constant_exprt &expr : literals)
{
mp_integer value;
to_integer(expr, value);
const constant_exprt expr_value(from_integer(value, word_type));
const std::string base_name(get_name(const_index++));
pos=body.insert_after(pos);
declare_jsa_meta_variable(st, pos, base_name, expr_value.type());
pos=assign_jsa_meta_variable(st, gf, pos, base_name, expr_value);
}
return pos;
}
| 31.958333 | 79 | 0.699478 | [
"vector"
] |
014b5d10adcb645d379b7eddf0146e24a47714b5 | 2,908 | cpp | C++ | src/glParticleRenderer.cpp | IcedLeon/Introduction-to-3D-with-OpenGL | 7e0edcb768d2e2b4b19cb5015a73335c60cd8f60 | [
"MIT"
] | null | null | null | src/glParticleRenderer.cpp | IcedLeon/Introduction-to-3D-with-OpenGL | 7e0edcb768d2e2b4b19cb5015a73335c60cd8f60 | [
"MIT"
] | null | null | null | src/glParticleRenderer.cpp | IcedLeon/Introduction-to-3D-with-OpenGL | 7e0edcb768d2e2b4b19cb5015a73335c60cd8f60 | [
"MIT"
] | null | null | null | #include "glParticleRenderer.h"
#include "ParticleSystem.h"
#include "gl_core_4_4.h"
#include <assert.h>
void GLParticleRenderer::Generate(ParticleSystem* a_oSys, bool a_bUseQuads)
{
assert(a_oSys != nullptr);
m_oSystem = a_oSys;
const size_t count = a_oSys->AllTheParticles();
glGenVertexArrays(1, &m_uiVAO);
glBindVertexArray(m_uiVAO);
glGenBuffers(1, &m_uiBufPos);
glBindBuffer(GL_ARRAY_BUFFER, m_uiBufPos);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 4 * count, nullptr, GL_STREAM_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, (4)*sizeof(float), (void *)((0) + sizeof(float)));
//if (ogl_ext_ARB_vertex_attrib_binding)
//{
// glBindVertexBuffer(0, m_uiBufPos, 0, sizeof(float) * 4);
// glVertexAttribFormat(0, 4, GL_FLOAT, GL_FALSE, 0);
// glVertexAttribBinding(0, 0);
//}
//else
glGenBuffers(1, &m_uiBufCol);
glBindBuffer(GL_ARRAY_BUFFER, m_uiBufCol);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 4 * count, nullptr, GL_STREAM_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, (4)*sizeof(float), (void *)((0) + sizeof(float)));
//if (ogl_ext_ARB_vertex_attrib_binding)
//{
// glBindVertexBuffer(1, m_uiBufCol, 0, sizeof(float) * 4);
// glVertexAttribFormat(1, 4, GL_FLOAT, GL_FALSE, 0);
// glVertexAttribBinding(1, 1);
//}
//else
//Bilboarding!!! TRY HERE!!!
//glEnableVertexAttribArray(2);
//glVertexAttribPointer(2, 4, GL_FLOAT, GL_TRUE, (4)*sizeof(float), (void *)((0)*sizeof(float)));
//glBindVertexBuffer(0, positionBufferHandle, 0, sizeof(GLfloat)* 3);
//glBindVertexBuffer(1, colorBufferHandle, 0, sizeof(GLfloat)* 3);
//glVertexAttribFormat(0, 3, GL_FLOAT, GL_FALSE, 0);
//glVertexAttribBinding(0, 0);
//glVertexAttribFormat(1, 3, GL_FLOAT, GL_FALSE, 0);
//glVertexAttribBinding(1, 1);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void GLParticleRenderer::Destroy()
{
if (m_uiBufPos != 0)
{
glDeleteBuffers(1, &m_uiBufPos);
m_uiBufPos = 0;
}
if (m_uiBufCol != 0)
{
glDeleteBuffers(1, &m_uiBufCol);
m_uiBufCol = 0;
}
}
void GLParticleRenderer::Update()
{
assert(m_oSystem != nullptr);
assert(m_uiBufPos > 0 && m_uiBufCol > 0);
const size_t _count = m_oSystem->AllTheParticlesAlive();
if (_count > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, m_uiBufPos);
float* _ptr = (float *)(m_oSystem->GetParticle()->m_pvPosition.get());
glBufferSubData(GL_ARRAY_BUFFER, 0, _count * sizeof(float) * 4, _ptr);
glBindBuffer(GL_ARRAY_BUFFER, m_uiBufCol);
_ptr = (float*)(m_oSystem->GetParticle()->m_pvColour.get());
glBufferSubData(GL_ARRAY_BUFFER, 0, _count * sizeof(float) * 4, _ptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
void GLParticleRenderer::Render()
{
glBindVertexArray(m_uiVAO);
const size_t _count = m_oSystem->AllTheParticlesAlive();
if (_count > 0)
{
glDrawArrays(GL_POINTS, 0, _count);
}
glBindVertexArray(0);
} | 27.17757 | 99 | 0.717675 | [
"render"
] |
0154d72ef160085b4148bc21704cc8596c43fbcd | 15,722 | cc | C++ | src/bringup/bin/console-launcher/main.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | 5 | 2022-01-10T20:22:17.000Z | 2022-01-21T20:14:17.000Z | src/bringup/bin/console-launcher/main.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | src/bringup/bin/console-launcher/main.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fidl/fuchsia.boot/cpp/wire.h>
#include <fidl/fuchsia.hardware.virtioconsole/cpp/wire.h>
#include <fidl/fuchsia.io/cpp/wire.h>
#include <fidl/fuchsia.virtualconsole/cpp/wire.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/async/cpp/task.h>
#include <lib/fdio/cpp/caller.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/fd.h>
#include <lib/fdio/namespace.h>
#include <lib/fdio/spawn.h>
#include <lib/fit/defer.h>
#include <lib/service/llcpp/service.h>
#include <lib/syslog/cpp/log_settings.h>
#include <lib/syslog/cpp/macros.h>
#include <lib/zx/debuglog.h>
#include <lib/zx/process.h>
#include <lib/zx/time.h>
#include <zircon/status.h>
#include <zircon/types.h>
#include <algorithm>
#include <future>
#include <latch>
#include <utility>
#include <fbl/ref_ptr.h>
#include "src/bringup/bin/console-launcher/console_launcher.h"
#include "src/lib/fxl/strings/split_string.h"
#include "src/lib/storage/vfs/cpp/managed_vfs.h"
#include "src/lib/storage/vfs/cpp/pseudo_dir.h"
#include "src/lib/storage/vfs/cpp/remote_dir.h"
#include "src/lib/storage/vfs/cpp/vfs_types.h"
#include "src/sys/lib/stdout-to-debuglog/cpp/stdout-to-debuglog.h"
namespace {
template <typename FOnOpen, typename FOnConnectionInfo>
class EventHandler : public fidl::WireSyncEventHandler<fuchsia_io::Directory> {
public:
explicit EventHandler(FOnOpen on_open, FOnConnectionInfo on_connection_info)
: on_open_(std::move(on_open)), on_connection_info_(std::move(on_connection_info)) {}
void OnOpen(fidl::WireEvent<fuchsia_io::Directory::OnOpen>* event) override { on_open_(event); }
void OnConnectionInfo(fidl::WireEvent<fuchsia_io::Directory::OnConnectionInfo>* event) override {
on_connection_info_(event);
}
private:
FOnOpen on_open_;
FOnConnectionInfo on_connection_info_;
};
std::ostream& operator<<(std::ostream& os, const std::vector<std::string>& args) {
for (size_t i = 0; i < args.size(); ++i) {
if (i != 0) {
os << ' ';
}
os << args[i];
}
return os;
}
zx_status_t CreateVirtualConsoles(const console_launcher::ConsoleLauncher& launcher,
fs::FuchsiaVfs& vfs, const fbl::RefPtr<fs::Vnode>& root,
bool need_debuglog, const std::string& term) {
zx::status virtcon = service::Connect<fuchsia_virtualconsole::SessionManager>();
if (virtcon.is_error()) {
FX_PLOGS(ERROR, virtcon.status_value())
<< "failed to connect to "
<< fidl::DiscoverableProtocolName<fuchsia_virtualconsole::SessionManager>;
return virtcon.status_value();
}
constexpr size_t kNumShells = 3;
for (size_t i = 0; i < kNumShells; i++) {
zx::status device_endpoints = fidl::CreateEndpoints<fuchsia_hardware_pty::Device>();
if (device_endpoints.is_error()) {
return device_endpoints.status_value();
}
const fidl::WireResult result =
fidl::WireCall(virtcon.value())->CreateSession(std::move(device_endpoints->server));
if (!result.ok()) {
FX_PLOGS(ERROR, result.status()) << "failed to create virtcon session";
return result.status();
}
const fidl::WireResponse response = result.value();
if (response.status != ZX_OK) {
FX_PLOGS(ERROR, response.status) << "failed to create virtcon session";
return response.status;
}
zx::status vfs_endpoints = fidl::CreateEndpoints<fuchsia_io::Directory>();
if (vfs_endpoints.is_error()) {
return vfs_endpoints.status_value();
}
if (zx_status_t status =
vfs.ServeDirectory(root, std::move(vfs_endpoints->server), fs::Rights::All());
status != ZX_OK) {
return status;
}
std::optional<std::string> cmd;
if (need_debuglog && (i == 0)) {
cmd = "dlog -f -t";
}
zx::status process =
launcher.LaunchShell(std::move(vfs_endpoints->client),
std::move(device_endpoints->client).TakeChannel(), term, cmd);
if (process.is_error()) {
return process.status_value();
}
}
return ZX_OK;
}
} // namespace
int main(int argv, char** argc) {
syslog::SetTags({"console-launcher"});
if (zx_status_t status = StdoutToDebuglog::Init(); status != ZX_OK) {
FX_PLOGS(ERROR, status)
<< "failed to redirect stdout to debuglog, assuming test environment and continuing";
}
FX_LOGS(INFO) << "running";
zx::status boot_args = service::Connect<fuchsia_boot::Arguments>();
if (boot_args.is_error()) {
FX_PLOGS(FATAL, boot_args.status_value())
<< "failed to connect to " << fidl::DiscoverableProtocolName<fuchsia_boot::Arguments>;
}
zx::status args = console_launcher::GetArguments(boot_args.value());
if (args.is_error()) {
FX_PLOGS(FATAL, args.status_value()) << "failed to get arguments";
}
if (!args->run_shell) {
if (!args->autorun_boot.empty()) {
FX_LOGS(ERROR) << "cannot launch autorun command '" << args->autorun_boot << "'";
}
FX_LOGS(INFO) << "console.shell: disabled";
// TODO(https://fxbug.dev/97657): Hang around. If we exit before archivist has started, our logs
// will be lost, and this log is load bearing in shell_disabled_test.
std::promise<void>().get_future().wait();
return 0;
}
FX_LOGS(INFO) << "console.shell: enabled";
async::Loop loop(&kAsyncLoopConfigNeverAttachToThread);
async_dispatcher_t* dispatcher = loop.dispatcher();
fbl::RefPtr root = fbl::MakeRefCounted<fs::PseudoDir>();
std::unordered_map<std::string_view, std::thread> threads;
fdio_flat_namespace_t* flat;
if (zx_status_t status = fdio_ns_export_root(&flat); status != ZX_OK) {
FX_PLOGS(FATAL, status) << "failed to get namespace root";
}
auto free_flat = fit::defer([&flat]() { fdio_ns_free_flat_ns(flat); });
// Our incoming namespace contains directories provided by fshost that may not
// yet be responding to requests. This is ordinarily fine, but can cause
// indefinite hangs in an interactive shell when storage devices fail to
// start.
//
// Rather than expose these directly to the shell, indirect through a local
// VFS to which entries are added only once they are seen to be servicing
// requests. This causes the shell to initially observe an empty root
// directory to which entries are added once they are ready for blocking
// operations.
for (size_t i = 0; i < flat->count; ++i) {
zx::status endpoints = fidl::CreateEndpoints<fuchsia_io::Directory>();
if (endpoints.is_error()) {
FX_PLOGS(FATAL, endpoints.status_value()) << "failed to create endpoints";
}
std::string_view path = flat->path[i];
const fidl::WireResult result =
fidl::WireCall(fidl::UnownedClientEnd<fuchsia_io::Directory>(flat->handle[i]))
->Clone(fuchsia_io::wire::OpenFlags::kDescribe |
fuchsia_io::wire::OpenFlags::kCloneSameRights,
fidl::ServerEnd<fuchsia_io::Node>(endpoints->server.TakeChannel()));
if (!result.ok()) {
FX_PLOGS(ERROR, result.status()) << "failed to clone '" << path << "'";
continue;
}
// TODO(https://fxbug.dev/68742): Replace the use of threads with async clients when it is
// possible to extract the channel from the client.
auto [thread, inserted] = threads.emplace(
path, [&root, client_end = std::move(endpoints->client), dispatcher, path]() mutable {
EventHandler handler(
[&](fidl::WireEvent<fuchsia_io::Directory::OnOpen>* event) {
if (event->s != ZX_OK) {
FX_PLOGS(ERROR, event->s) << "failed to open '" << path << "'";
return;
}
// Must run on the dispatcher thread to avoid racing with VFS dispatch.
std::latch mounted(1);
async::PostTask(dispatcher, [&mounted, &root, path,
client_end = std::move(client_end)]() mutable {
// Drop the leading slash.
std::string_view relative_path = path;
if (relative_path.front() == '/') {
relative_path = relative_path.substr(1);
}
if (zx_status_t status = root->AddEntry(
relative_path, fbl::MakeRefCounted<fs::RemoteDir>(std::move(client_end)));
status != ZX_OK) {
FX_PLOGS(ERROR, status) << "failed to add entry for '" << path << "'";
} else {
FX_LOGS(INFO) << "mounted '" << path << "'";
}
mounted.count_down();
});
mounted.wait();
},
[&](fidl::WireEvent<fuchsia_io::Directory::OnConnectionInfo>* event) {
FX_PLOGS(FATAL, ZX_ERR_NOT_SUPPORTED) << "unexpected OnConnectionInfo";
});
if (fidl::Status status = handler.HandleOneEvent(client_end); !status.ok()) {
FX_PLOGS(ERROR, status.status())
<< "failed to receive OnOpen event for '" << path << "'";
}
});
if (!inserted) {
FX_LOGS(FATAL) << "duplicate namespace entry: " << path;
}
}
std::thread thread([&loop]() {
if (zx_status_t status = loop.Run(); status != ZX_OK) {
FX_PLOGS(ERROR, status) << "VFS loop exited";
}
});
fs::ManagedVfs vfs(dispatcher);
zx::status result = console_launcher::ConsoleLauncher::Create();
if (result.is_error()) {
FX_PLOGS(FATAL, result.status_value()) << "failed to create console launcher";
}
const auto& launcher = result.value();
std::tuple<const char*, std::string&, std::vector<std::string_view>> map[] = {
// NB: //tools/emulator/emulator.go expects these to be available in its boot autorun.
{"autorun:boot", args->autorun_boot, {"/dev", "/mnt"}},
{"autorun:system", args->autorun_system, {"/system"}},
};
std::vector<std::thread> autorun;
for (const auto& [name, args, paths] : map) {
if (args.empty()) {
continue;
}
zx::status endpoints = fidl::CreateEndpoints<fuchsia_io::Directory>();
if (endpoints.is_error()) {
FX_PLOGS(FATAL, endpoints.status_value()) << "failed to create endpoints";
}
if (zx_status_t status =
vfs.ServeDirectory(root, std::move(endpoints->server), fs::Rights::All());
status != ZX_OK) {
FX_PLOGS(FATAL, status) << "failed to serve root directory";
}
// Get the full commandline by splitting on '+'.
std::vector argv = fxl::SplitStringCopy(args, "+", fxl::WhiteSpaceHandling::kTrimWhitespace,
fxl::SplitResult::kSplitWantNonEmpty);
autorun.emplace_back([paths = paths, &threads, args = std::move(argv), name = name,
client_end = std::move(endpoints->client),
&job = launcher.shell_job()]() {
for (std::string_view path : paths) {
if (auto it = threads.find(path); it != threads.end()) {
it->second.join();
} else {
FX_LOGS(ERROR) << "unable to run '" << name << "': could not mount required path '"
<< path << "'";
return;
}
}
const char* argv[args.size() + 1];
argv[args.size()] = nullptr;
for (size_t i = 0; i < args.size(); ++i) {
argv[i] = args[i].c_str();
}
fdio_spawn_action_t actions[] = {
{
.action = FDIO_SPAWN_ACTION_SET_NAME,
.name =
{
.data = name,
},
},
{
.action = FDIO_SPAWN_ACTION_ADD_NS_ENTRY,
.ns =
{
.prefix = "/",
.handle = client_end.channel().get(),
},
},
};
zx::process process;
char err_msg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
constexpr uint32_t flags = FDIO_SPAWN_CLONE_ALL & ~FDIO_SPAWN_CLONE_NAMESPACE;
FX_LOGS(INFO) << "starting '" << name << "': " << args;
zx_status_t status =
fdio_spawn_etc(job.get(), flags, argv[0], argv, nullptr, std::size(actions), actions,
process.reset_and_get_address(), err_msg);
if (status != ZX_OK) {
FX_PLOGS(ERROR, status) << "failed to start '" << name << "': " << err_msg;
return;
}
if (zx_status_t status =
process.wait_one(ZX_PROCESS_TERMINATED, zx::time::infinite(), nullptr);
status != ZX_OK) {
FX_PLOGS(ERROR, status) << "failed to wait for '" << name << "' termination";
}
FX_LOGS(INFO) << "completed '" << name << "': " << args;
});
}
if (zx_status_t status = CreateVirtualConsoles(launcher, vfs, root,
args->virtual_console_need_debuglog, args->term);
status != ZX_OK) {
// If launching virtcon fails, we still should continue so that the autorun programs
// and serial console are launched.
FX_PLOGS(ERROR, status) << "failed to set up virtcon";
}
while (true) {
zx::status fd = console_launcher::WaitForFile(args->device.path.c_str(), zx::time::infinite());
if (fd.is_error()) {
FX_PLOGS(FATAL, fd.status_value())
<< "failed to wait for console '" << args->device.path << "'";
}
fdio_cpp::FdioCaller caller(std::move(fd).value());
zx::channel stdio;
// If the console is a virtio connection, then speak the
// fuchsia.hardware.virtioconsole.Device interface to get the real
// fuchsia.io.File connection
//
// TODO(fxbug.dev/33183): Clean this up once devhost stops speaking
// fuchsia.io.File on behalf of drivers. Once that happens, the virtio-console
// driver should just speak that instead of this shim interface.
if (args->device.is_virtio) {
zx::status endpoints = fidl::CreateEndpoints<fuchsia_hardware_pty::Device>();
if (endpoints.is_error()) {
FX_PLOGS(FATAL, endpoints.status_value()) << "failed to create pty endpoints";
}
const fidl::WireResult result =
fidl::WireCall(caller.borrow_as<fuchsia_hardware_virtioconsole::Device>())
->GetChannel(std::move(endpoints->server));
if (!result.ok()) {
FX_PLOGS(FATAL, result.status()) << "failed to get virtio console channel";
}
stdio = std::move(endpoints->client).TakeChannel();
} else {
zx::status channel = caller.take_channel();
if (channel.is_error()) {
FX_PLOGS(FATAL, channel.status_value()) << "failed to get console channel";
}
stdio = std::move(channel.value());
}
zx::status endpoints = fidl::CreateEndpoints<fuchsia_io::Directory>();
if (endpoints.is_error()) {
FX_PLOGS(FATAL, endpoints.status_value()) << "failed to create endpoints";
}
if (zx_status_t status =
vfs.ServeDirectory(root, std::move(endpoints->server), fs::Rights::All());
status != ZX_OK) {
FX_PLOGS(FATAL, status) << "failed to serve root directory";
}
zx::status process =
launcher.LaunchShell(std::move(endpoints->client), std::move(stdio), args->term);
if (process.is_error()) {
FX_PLOGS(FATAL, process.status_value()) << "failed to launch shell";
}
if (zx_status_t status = console_launcher::WaitForExit(std::move(process.value()));
status != ZX_OK) {
FX_PLOGS(FATAL, status) << "failed to wait for shell exit";
}
}
}
| 38.819753 | 100 | 0.613026 | [
"vector"
] |
015eab2ac6b798da3ba93b93d25ce76e1cf6152e | 54,574 | cpp | C++ | D-Squared-Engine/source/Test.Library.Shared/VectorTest.cpp | stropheum/D_Square_Engine | 4e607f7cd6f5e7ffd9dc5207dc2b29ad6c4fa5b1 | [
"MIT"
] | null | null | null | D-Squared-Engine/source/Test.Library.Shared/VectorTest.cpp | stropheum/D_Square_Engine | 4e607f7cd6f5e7ffd9dc5207dc2b29ad6c4fa5b1 | [
"MIT"
] | null | null | null | D-Squared-Engine/source/Test.Library.Shared/VectorTest.cpp | stropheum/D_Square_Engine | 4e607f7cd6f5e7ffd9dc5207dc2b29ad6c4fa5b1 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "CppUnitTest.h"
#include "LeakDetector.h"
#include <Vector.h>
#include "Foo.h"
#include "implementation.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace TestLibraryDesktop
{
TEST_CLASS(VectorTest)
{
public:
Library::Vector<int> intor;
Library::Vector<int*> pointor;
Library::Vector<Foo> footor;
TEST_METHOD_INITIALIZE(InitializeMethod)
{
intor.Clear();
pointor.Clear();
footor.Clear();
LeakDetector::Initialize();
}
TEST_METHOD_CLEANUP(CleanupMethod)
{
intor.Clear();
pointor.Clear();
footor.Clear();
LeakDetector::Finalize();
}
TEST_METHOD(TestCopyConstructor_Integer)
{
Library::Vector<int> copyIntor(intor);
bool intcompare = intor == copyIntor;
Assert::IsTrue(intcompare,
L"Copied vector not equivalent to original");
intor.PushBack(1);
intcompare = intor == copyIntor;
Assert::IsFalse(intcompare,
L"Copied vector equivalent after modifying original");
copyIntor.PushBack(1);
intcompare = intor == copyIntor;
Assert::IsTrue(intcompare,
L"Copied vector not equivalent after pushing identical values");
}
TEST_METHOD(TestCopyConstructor_Pointer)
{
Library::Vector<int*> copyPointor(pointor);
Assert::IsTrue(pointor == copyPointor,
L"Copied pointer vector not equivalent to original");
int x = 1;
pointor.PushBack(&x);
Assert::IsFalse(pointor == copyPointor,
L"Copied vector equivalent after modifying original");
copyPointor.PushBack(&x);
Assert::IsTrue(pointor == copyPointor,
L"Copied vector not equivalent after pushing identical values");
}
TEST_METHOD(TestCopyConstructor_foo)
{
Library::Vector<Foo> copyFootor(footor);
Assert::IsTrue(footor == copyFootor,
L"Copied Foo vector not equivalent to original");
Foo foo(1);
footor.PushBack(foo);
Assert::IsFalse(footor == copyFootor,
L"Copied Foo vector equivalent after modifying original");
copyFootor.PushBack(foo);
Assert::IsTrue(footor == copyFootor,
L"Copied vector not equivalent after pushing identical values");
}
TEST_METHOD(TestComparisonOperator_Integer)
{
Assert::IsTrue(intor == intor,
L"Vector not equivalent to itself");
Library::Vector<int> copyIntor(intor);
Assert::IsTrue(intor == copyIntor,
L"Copy constructor invocation not equivalent");
copyIntor = intor;
Assert::IsTrue(intor == copyIntor,
L"Assignment operator copy not equivalent");
const auto constIntor(intor);
Assert::IsTrue(intor == constIntor,
L"Const copy not equivalent");
Library::Vector<int> wrongIntVector;
for (int i = 0; i < 100; i++)
{
intor.PushBack(100 - i);
wrongIntVector.PushBack(i);
}
Assert::IsFalse(intor == wrongIntVector);
}
TEST_METHOD(TestComparisonOperator_Pointer)
{
Assert::IsTrue(pointor == pointor,
L"Vector not equivalent to itself");
Library::Vector<int*> copyPointor(pointor);
Assert::IsTrue(pointor == copyPointor,
L"Copy constructor invocation not equivalent");
copyPointor = pointor;
Assert::IsTrue(pointor == copyPointor,
L"Assignment operator copy not equivalent");
const auto constPointor(pointor);
Assert::IsTrue(pointor == constPointor,
L"Const copy not equivalent");
int right = 5;
int wrong = 10;
Library::Vector<int*> wrongPtrVector;
for (int i = 0; i < 100; i++)
{
pointor.PushBack(&right);
wrongPtrVector.PushBack(&wrong);
}
Assert::IsFalse(pointor == wrongPtrVector);
}
TEST_METHOD(TestComparisonOperator_Foo)
{
Assert::IsTrue(footor == footor,
L"Vector not equivalent to itself");
Library::Vector<Foo> copyFootor(footor);
Assert::IsTrue(footor == copyFootor,
L"Copy constructor invocation not equivalent");
copyFootor = footor;
Assert::IsTrue(footor == copyFootor,
L"Assignment operator copy not equivalent");
const auto constFootor(footor);
Assert::IsTrue(footor == constFootor,
L"Const copy not equivalent");
Foo rightFoo(5);
Foo wrongFoo(10);
Library::Vector<Foo> wrongFooVector;
for (int i = 0; i < 100; i++)
{
footor.PushBack(rightFoo);
wrongFooVector.PushBack(wrongFoo);
}
Assert::IsFalse(footor == wrongFooVector);
}
TEST_METHOD(TestAssignmentOperator_Integer)
{
Library::Vector<int> copyIntor = intor;
Assert::IsTrue(intor == copyIntor,
L"Copied vector not equivalent to original");
}
TEST_METHOD(TestAssignmentOperator_Pointer)
{
Library::Vector<int*> copyPointor = pointor;
Assert::IsTrue(pointor == copyPointor,
L"Copied pointer vector not equivalent to original");
}
TEST_METHOD(TestAssignmentOperator_Foo)
{
Library::Vector<Foo> copyFootor = footor;
Assert::IsTrue(footor == copyFootor,
L"Copied Foo vector not equivalent to original");
}
TEST_METHOD(TestMoveSemantics_Integer)
{
Library::Vector<int> intVector;
for (int i = 0; i < 10; i++)
{
intVector.PushBack(i);
}
Assert::AreEqual(10u, intVector.Size());
Library::Vector<int> newIntVector = std::move(intVector);
Assert::AreEqual(10u, newIntVector.Size());
Assert::AreEqual(0u, intVector.Size());
for (int i = 0; i < 10; i++)
{
Assert::AreEqual(i, newIntVector[i]);
}
}
TEST_METHOD(TestMoveSemantics_Float)
{
Library::Vector<float> floatVector;
for (int i = 0; i < 10; i++)
{
floatVector.PushBack(static_cast<float>(i));
}
Assert::AreEqual(10u, floatVector.Size());
Library::Vector<float> newFloatVector = std::move(floatVector);
Assert::AreEqual(10u, newFloatVector.Size());
Assert::AreEqual(0u, floatVector.Size());
for (int i = 0; i < 10; i++)
{
Assert::AreEqual(static_cast<float>(i), newFloatVector[i]);
}
}
TEST_METHOD(TestMoveSemantics_Pointer)
{
int ints[10];
for (int i = 0; i < 10; i++)
{
ints[i] = i;
}
Library::Vector<int*> ptrVector;
for (int i = 0; i < 10; i++)
{
ptrVector.PushBack(&ints[i]);
}
Assert::AreEqual(10u, ptrVector.Size());
Library::Vector<int*> newPtrVector = std::move(ptrVector);
Assert::AreEqual(10u, newPtrVector.Size());
Assert::AreEqual(0u, ptrVector.Size());
for (int i = 0; i < 10; i++)
{
Assert::AreEqual(i, *newPtrVector[i]);
}
}
TEST_METHOD(TestMoveSemantics_Foo)
{
Library::Vector<Foo> fooVector;
for (int i = 0; i < 10; i++)
{
fooVector.PushBack(Foo(i));
}
Assert::AreEqual(10u, fooVector.Size());
Library::Vector<Foo> newFooVector = std::move(fooVector);
Assert::AreEqual(10u, newFooVector.Size());
Assert::AreEqual(0u, fooVector.Size());
for (int i = 0; i < 10; i++)
{
Assert::AreEqual(Foo(i), newFooVector[i]);
}
}
TEST_METHOD(TestFind_Integer)
{
auto iter = intor.Find(0);
Assert::IsTrue(iter == intor.end(),
L"begin and end not equivalent on empty vector");
Assert::IsTrue(iter == intor.begin(),
L"Find on first element not equivalent to Vector.begin()");
intor.PushBack(1);
iter = intor.Find(1);
Assert::IsFalse(iter == intor.end(),
L"Find on existing element should not be equivalent to end");
Assert::IsTrue(iter == intor.begin(),
L"Find on first element should be equivalent to begin");
Assert::AreEqual(*iter, 1,
L"Find on first item should be equivalent to the first value pushed");
intor.PushBack(100);
iter = intor.Find(1);
Assert::IsTrue(iter == intor.begin(),
L"Find on first item should not change after pushing a second");
Assert::IsFalse(iter == intor.end(),
L"Find on existing item should not be equivalent to end");
iter = intor.Find(100);
Assert::IsTrue(++iter == intor.end(),
L"Incrementing past final element not equivalent to end");
const auto constIntor(intor);
Assert::IsTrue(constIntor.Find(1) == constIntor.begin(),
L"Const Find value incorrect");
}
TEST_METHOD(TestFind_Pointer)
{
int x = 1;
int y = 2;
auto piter = pointor.Find(&x);
Assert::IsTrue(piter == pointor.end(),
L"begin and end not equivalent on empty vector");
Assert::IsTrue(piter == pointor.begin(),
L"Find on first element not equivalent to Vector.begin()");
pointor.PushBack(&x);
piter = pointor.Find(&x);
Assert::IsFalse(piter == pointor.end(),
L"Find on existing element should not be equivalent to end");
Assert::IsTrue(piter == pointor.begin(),
L"Find on first element should be equivalent to begin");
Assert::AreEqual(*piter, &x,
L"Find on first item should be equivalent to the first value pushed");
pointor.PushBack(&y);
piter = pointor.Find(&x);
Assert::IsTrue(piter == pointor.begin(),
L"Find on first item should not change after pushing a second");
Assert::IsFalse(piter == pointor.end(),
L"Find on existing item should not be equivalent to end");
piter = pointor.Find(&y);
Assert::IsTrue(++piter == pointor.end(),
L"Incrementing past final element not equivalent to end");
const auto constPointor(pointor);
Assert::IsTrue(constPointor.Find(&x) == constPointor.begin(),
L"Const Find value incorrect");
}
TEST_METHOD(TestFind_Foo)
{
Foo foo(1);
Foo bar(2);
auto fooiter = footor.Find(foo);
Assert::IsTrue(fooiter == footor.end(),
L"begin and end not equivalent on empty vector");
Assert::IsTrue(fooiter == footor.begin(),
L"Find on first element not equivalent to Vector.begin()");
footor.PushBack(foo);
fooiter = footor.Find(foo);
Assert::IsFalse(fooiter == footor.end(),
L"Find on existing element should not be equivalent to end");
Assert::IsTrue(fooiter == footor.begin(),
L"Find on first element should be equivalent to begin");
Assert::AreEqual(*fooiter, foo,
L"Find on first item should be equivalent to the first value pushed");
footor.PushBack(bar);
fooiter = footor.Find(foo);
Assert::IsTrue(fooiter == footor.begin(),
L"Find on first item should not change after pushing a second");
Assert::IsFalse(fooiter == footor.end(),
L"Find on existing item should not be equivalent to end");
fooiter = footor.Find(bar);
Assert::IsTrue(++fooiter == footor.end(),
L"Incrementing past final element not equivalent to end");
const auto constFootor(footor);
Assert::IsTrue(constFootor.Find(foo) == constFootor.begin(),
L"Const Find value incorrect");
}
TEST_METHOD(TestBegin_Integer)
{
Assert::IsTrue(intor.begin() == intor.end(),
L"begin should be equivalent to end on an empy vector");
intor.PushBack(1);
Assert::IsTrue(1 == *intor.begin(),
L"begin not equivalent with first value pushed");
Assert::IsFalse(intor.begin() == intor.end());
intor.PushBack(2);
Assert::IsTrue(1 == *intor.begin(),
L"begin value changed after calling push Back on non-empty vector");
Assert::IsTrue(intor[0] == *intor.begin(),
L"First index not equivalent to begin");
const auto constIntor(intor);
Assert::IsTrue(*constIntor.begin() == constIntor[0]);
}
TEST_METHOD(TestBegin_Pointer)
{
int x = 1;
int y = 2;
Assert::IsTrue(pointor.begin() == pointor.end(),
L"begin should be equivalent to end on an empy vector");
pointor.PushBack(&x);
Assert::IsTrue(&x == *pointor.begin(),
L"begin not equivalent with first value pushed");
Assert::IsFalse(pointor.begin() == pointor.end());
pointor.PushBack(&y);
Assert::IsTrue(&x == *pointor.begin(),
L"begin value changed after calling push Back on non-empty vector");
Assert::IsTrue(pointor[0] == *pointor.begin(),
L"First index not equivalent to begin");
const auto constPointor(pointor);
Assert::IsTrue(*constPointor.begin() == constPointor[0]);
}
TEST_METHOD(TestBegin_Foo)
{
Foo foo(1);
Foo bar(2);
Assert::IsTrue(footor.begin() == footor.end(),
L"begin should be equivalent to end on an empy vector");
footor.PushBack(foo);
Assert::IsTrue(foo == *footor.begin(),
L"begin not equivalent with first value pushed");
Assert::IsFalse(footor.begin() == footor.end());
footor.PushBack(bar);
Assert::IsTrue(foo == *footor.begin(),
L"begin value changed after calling push Back on non-empty vector");
Assert::IsTrue(footor[0] == *footor.begin(),
L"First index not equivalent to begin");
const auto constFootor(footor);
Assert::IsTrue(*constFootor.begin() == constFootor[0]);
}
TEST_METHOD(TestEnd_Integer)
{
Assert::IsTrue(intor.begin() == intor.end(),
L"end should be equivalent to begin on an empty vector");
Library::Vector<int>::Iterator iter = intor.end();
Assert::IsTrue(iter == intor.end(),
L"Iterator assigned to end should be equivalent to end");
intor.PushBack(1);
iter = intor.begin();
Assert::IsFalse(iter == intor.end(),
L"Iterator pointing to begin should not be equivalent to end on a non-empty vector");
Assert::IsTrue(++iter == intor.end(),
L"Iterator pointing to last element should be equivalent to end after incrementing");
Assert::IsTrue(pointor.begin() == pointor.end(),
L"end should be equivalent to begin on an empty vector");
const auto constIntor(intor);
auto constIter = constIntor.end();
Assert::IsTrue(constIter == constIntor.end());
}
TEST_METHOD(TestEnd_Pointer)
{
Library::Vector<int*>::Iterator piter = pointor.end();
Assert::IsTrue(piter == pointor.end(),
L"Iterator assigned to end should be equivalent to end");
int x = 1;
pointor.PushBack(&x);
piter = pointor.begin();
Assert::IsFalse(piter == pointor.end(),
L"Iterator pointing to begin should not be equivalent to end on a non-empty vector");
Assert::IsTrue(++piter == pointor.end(),
L"Iterator pointing to last element should be equivalent to end after incrementing");
Assert::IsTrue(footor.begin() == footor.end(),
L"end should be equivalent to begin on an empty vector");
const auto constPointor(pointor);
auto constPIter = constPointor.end();
Assert::IsTrue(constPIter == constPointor.end());
}
TEST_METHOD(TestEnd_Foo)
{
Library::Vector<Foo>::Iterator fooiter = footor.end();
Assert::IsTrue(fooiter == footor.end(),
L"Iterator assigned to end should be equivalent to end");
Foo foo(1);
footor.PushBack(foo);
fooiter = footor.begin();
Assert::IsFalse(fooiter == footor.end(),
L"Iterator pointing to begin should not be equivalent to end on a non-empty vector");
Assert::IsTrue(++fooiter == footor.end(),
L"Iterator pointing to last element should be equivalent to end after incrementing");
const auto constFootor(footor);
auto constFooIter = constFootor.end();
Assert::IsTrue(constFooIter == constFootor.end());
}
TEST_METHOD(TestFront_Integer)
{
auto func = [this] { intor.Front(); };
Assert::ExpectException<std::exception>(func,
L"Front should be equivalent with begin on an empty vector");
intor.PushBack(1);
Assert::IsTrue(intor.Front() == intor[0],
L"Front should be equivalent with first index");
Assert::IsTrue(intor.Front() == *intor.begin(),
L"Front should be equivalent with begin");
intor.Front() = 5;
Assert::IsTrue(intor.Front() == 5,
L"Unable to modify Vector.Front()");
const Library::Vector<int> constIntVector(intor);
Assert::IsTrue(constIntVector.Front() == intor.Front(),
L"Front of const copied vector should be equivalent to original");
}
TEST_METHOD(TestFront_Pointer)
{
auto ptrfunc = [this] { pointor.Front(); };
Assert::ExpectException<std::exception>(ptrfunc,
L"Front should be equivalent with begin on an empty vector");
int x = 1;
pointor.PushBack(&x);
Assert::IsTrue(pointor.Front() == pointor[0],
L"Front should be equivalent with first index");
Assert::IsTrue(pointor.Front() == *pointor.begin(),
L"Front should be equivalent with begin");
int y = 5;
pointor.Front() = &y;
Assert::IsTrue(pointor.Front() == &y,
L"Unable to modify Vector.Front()");
const Library::Vector<int*> constPtrVector(pointor);
Assert::IsTrue(constPtrVector.Front() == pointor.Front(),
L"Front of const copied vector should be equivalent to original");
}
TEST_METHOD(TestFront_Foo)
{
auto foofunc = [this] { footor.Front(); };
Assert::ExpectException<std::exception>(foofunc,
L"Front should be equivalent with begin on an empty vector");
Foo foo(1);
footor.PushBack(foo);
Assert::IsTrue(footor.Front() == footor[0],
L"Front should be equivalent with first index");
Assert::IsTrue(footor.Front() == *footor.begin(),
L"Front should be equivalent with begin");
Foo bar(5);
footor.Front() = bar;
Assert::IsTrue(footor.Front() == bar,
L"Unable to modify Vector.Front()");
const Library::Vector<Foo> constFooVector(footor);
Assert::IsTrue(constFooVector.Front() == footor.Front(),
L"Front of constant copied vector not equal to original vector's Front");
Assert::IsTrue(true);
}
TEST_METHOD(TestBack_Integer)
{
auto func = [this] { intor.Back(); };
Assert::ExpectException<std::exception>(func,
L"Calling Back on an empty vector should throw an exception");
intor.PushBack(1);
Assert::IsTrue(intor.Back() == intor[0],
L"Back should be equivalent to first value pushed onto an empty vector");
intor.PushBack(2);
Assert::IsTrue(intor.Back() == intor[1],
L"Back should b equivalent to last value pushed onto a vector");
intor.Back() = 10;
Assert::IsTrue(intor.Back() == 10,
L"Vector.Back() not modifiable");
}
TEST_METHOD(TestBack_Pointer)
{
auto ptrfunc = [this] { pointor.Back(); };
Assert::ExpectException<std::exception>(ptrfunc,
L"Calling Back on an empty vector should throw an exception");
int x = 1;
pointor.PushBack(&x);
Assert::IsTrue(pointor.Back() == pointor[0],
L"Back should be equivalent to first value pushed onto an empty vector");
int y = 2;
pointor.PushBack(&y);
Assert::IsTrue(pointor.Back() == pointor[1],
L"Back should b equivalent to last value pushed onto a vector");
int z = 10;
pointor.Back() = &z;
Assert::IsTrue(pointor.Back() == &z,
L"Vector.Back() not modifiable");
}
TEST_METHOD(TestBack_Foo)
{
auto foofunc = [this] { footor.Back(); };
Assert::ExpectException<std::exception>(foofunc,
L"Calling Back on an empty vector should throw an exception");
Foo foo(1);
footor.PushBack(foo);
Assert::IsTrue(footor.Back() == footor[0],
L"Back should be equivalent to first value pushed onto an empty vector");
Foo bar(2);
footor.PushBack(bar);
Assert::IsTrue(footor.Back() == footor[1],
L"Back should b equivalent to last value pushed onto a vector");
Foo gar(10);
footor.Back() = gar;
Assert::IsTrue(footor.Back() == gar,
L"Vector.Back() not modifiable");
}
TEST_METHOD(TestAt_Integer)
{
auto func1 = [this] { intor.At(0U); };
Assert::ExpectException<std::exception>(func1,
L"Accessing index of an empty vector should throw an exception");
intor.PushBack(1);
auto func2 = [this] { intor.At(1U); };
Assert::ExpectException<std::exception>(func2,
L"Accessing out of vector bounds should throw an exception");
intor.PushBack(2);
Assert::IsTrue(1 == intor.At(0U),
L"First element should be equivalent to Vector.At(0) after pushing Back multiple values");
Assert::IsTrue(2 == intor.At(1U),
L"Last element should be equivalent to Vector.At(n-1)");
const auto constIntor(intor);
Assert::IsTrue(1 == constIntor.At(0U));
Assert::IsTrue(2 == constIntor.At(1U));
}
TEST_METHOD(TestAt_Pointer)
{
auto ptrfunc1 = [this] { pointor.At(0U); };
Assert::ExpectException<std::exception>(ptrfunc1,
L"Accessing index of an empty vector should throw an exception");
int x = 1;
pointor.PushBack(&x);
auto ptrfunc2 = [this] { pointor.At(1U); };
Assert::ExpectException<std::exception>(ptrfunc2,
L"Accessing out of vector bounds should throw an exception");
int y = 2;
pointor.PushBack(&y);
Assert::IsTrue(&x == pointor.At(0),
L"First element should be equivalent to Vector.At(0) after pushing Back multiple values");
Assert::IsTrue(&y == pointor.At(1),
L"Last element should be equivalent to Vector.At(n-1)");
const auto constPointor(pointor);
Assert::IsTrue(&x == constPointor.At(0));
Assert::IsTrue(&y == constPointor.At(1));
}
TEST_METHOD(TestAt_Foo)
{
auto foofunc1 = [this] { footor.At(0); };
Assert::ExpectException<std::exception>(foofunc1,
L"Accessing index of an empty vector should throw an exception");
Foo foo(1);
footor.PushBack(foo);
auto foofunc2 = [this] { footor.At(1); };
Assert::ExpectException<std::exception>(foofunc2,
L"Accessing out of vector bounds should throw an exception");
Foo bar(2);
footor.PushBack(bar);
Assert::IsTrue(foo == footor.At(0),
L"First element should be equivalent to Vector.At(0) after pushing Back multiple values");
Assert::IsTrue(bar == footor.At(1),
L"Last element should be equivalent to Vector.At(n-1)");
const auto constFootor(footor);
Assert::IsTrue(foo == constFootor.At(0));
Assert::IsTrue(bar == constFootor.At(1));
}
TEST_METHOD(TestIndexOperator_Integer)
{
auto func1 = [this] { intor[0]; };
Assert::ExpectException<std::exception>(func1,
L"Accessing index of an empty vector should throw an exception");
intor.PushBack(1);
auto func2 = [this] { intor[1]; };
Assert::ExpectException<std::exception>(func2,
L"Accessing out of vector bounds should throw an exception");
intor.PushBack(2);
Assert::IsTrue(1 == intor[0],
L"First element should be equivalent to Vector[0] after pushing Back multiple values");
Assert::IsTrue(2 == intor[1],
L"Last element should be equivalent to Vector[n-1]");
const auto constIntor(intor);
Assert::IsTrue(1 == constIntor[0]);
Assert::IsTrue(2 == constIntor[1]);
}
TEST_METHOD(TestIndexOperator_Pointer)
{
auto ptrfunc1 = [this] { pointor[0]; };
Assert::ExpectException<std::exception>(ptrfunc1,
L"Accessing index of an empty vector should throw an exception");
int x = 1;
pointor.PushBack(&x);
auto ptrfunc2 = [this] { pointor[1]; };
Assert::ExpectException<std::exception>(ptrfunc2,
L"Accessing out of vector bounds should throw an exception");
int y = 2;
pointor.PushBack(&y);
Assert::IsTrue(&x == pointor[0],
L"First element should be equivalent to Vector[0] after pushing Back multiple values");
Assert::IsTrue(&y == pointor[1],
L"Last element should be equivalent to Vector[n-1]");
const auto constPointor(pointor);
Assert::IsTrue(&x == constPointor[0]);
Assert::IsTrue(&y == constPointor[1]);
}
TEST_METHOD(TestIndexOperator_Foo)
{
auto foofunc1 = [this] { footor[0U]; };
Assert::ExpectException<std::exception>(foofunc1,
L"Accessing index of an empty vector should throw an exception");
Foo foo(1);
footor.PushBack(foo);
auto foofunc2 = [this] { footor[1U]; };
Assert::ExpectException<std::exception>(foofunc2,
L"Accessing out of vector bounds should throw an exception");
Foo bar(2);
footor.PushBack(bar);
Assert::IsTrue(foo == footor[0],
L"First element should be equivalent to Vector[0] after pushing Back multiple values");
Assert::IsTrue(bar == footor[1],
L"Last element should be equivalent to Vector[n-1]");
const auto constFootor(footor);
Assert::IsTrue(foo == constFootor[0]);
Assert::IsTrue(bar == constFootor[1]);
}
TEST_METHOD(TestPopBack_Integer)
{
auto func1 = [this] { intor.PopBack(); };
Assert::ExpectException<std::exception>(func1,
L"PopBack on empty vector should throw an exception");
intor.PushBack(1);
intor.PushBack(2);
intor.PushBack(3);
intor.PopBack();
Assert::AreEqual(2U, intor.Size(),
L"Vector Size not reducing after valid pop Back");
}
TEST_METHOD(TestPopBack_Pointer)
{
auto ptrfunc1 = [this] { pointor.PopBack(); };
Assert::ExpectException<std::exception>(ptrfunc1,
L"PopBack on empty vector should throw an exception");
int x = 1;
int y = 2;
int z = 3;
pointor.PushBack(&x);
pointor.PushBack(&y);
pointor.PushBack(&z);
pointor.PopBack();
Assert::AreEqual(2U, pointor.Size(),
L"Vector Size not reducing after valid pop Back");
}
TEST_METHOD(TestPopBack_Foo)
{
auto foofunc1 = [this] { footor.PopBack(); };
Assert::ExpectException<std::exception>(foofunc1,
L"PopBack on empty vector should throw an exception");
Foo foo(1);
Foo bar(2);
Foo gar(3);
footor.PushBack(foo);
footor.PushBack(bar);
footor.PushBack(gar);
footor.PopBack();
Assert::AreEqual(2U, footor.Size(),
L"Vector Size not reducing after valid pop Back");
}
TEST_METHOD(TestSize_Integer)
{
intor.Reserve(10);
intor.Reserve(10);
intor.PushBack(1);
intor.PopBack();
Assert::AreEqual(0u, intor.Size(),
L"Size not zero on empty vector");
intor.PushBack(1);
Assert::AreEqual(1u, intor.Size(),
L"Size not one after pushing one value");
intor.PopBack();
Assert::AreEqual(0u, intor.Size(),
L"Size not zero after popping last value");
const auto constIntor(intor);
Assert::AreEqual(0u, constIntor.Size());
}
TEST_METHOD(TestSize_Pointer)
{
Assert::IsTrue(pointor.Size() == 0,
L"Size not zero on empty vector");
int x = 1;
pointor.PushBack(&x);
Assert::AreEqual(1u, pointor.Size(),
L"Size not one after pushing one value");
pointor.PopBack();
Assert::AreEqual(0u, pointor.Size(),
L"Size not zero after popping last value");
const auto constPointor(pointor);
Assert::AreEqual(0u, constPointor.Size());
}
TEST_METHOD(TestSize_Foo)
{
Assert::AreEqual(0u, footor.Size(),
L"Size not zero on empty vector");
Foo foo(1);
footor.PushBack(foo);
Assert::AreEqual(1u, footor.Size(),
L"Size not one after pushing one value");
footor.PopBack();
Assert::AreEqual(0u, footor.Size(),
L"Size not zero after popping last value");
const auto constFootor(footor);
Assert::AreEqual(0u, constFootor.Size());
}
TEST_METHOD(TestCapacity_Integer)
{
Library::Vector<int> newintvector;
Assert::AreEqual(10u, newintvector.Capacity(),
L"New Vector should have a Capacity of 10");
const auto constIntor(newintvector);
Assert::AreEqual(10u, constIntor.Capacity());
for (int i = 0; i < 10; i++)
{
intor.PushBack(i);
Assert::AreEqual(10U, intor.Capacity(),
L"First ten pushes on a vector should retain the Capacity At 10");
}
intor.PushBack(99);
Assert::AreEqual(20U, intor.Capacity(),
L"on 11th push, vector Capacity should be 20");
for (int i = 0; i < 11; i++)
{
intor.PopBack();
Assert::AreEqual(10U, newintvector.Capacity(),
L"New Vector should have Capacity of 10");
}
}
TEST_METHOD(TestCapacity_Pointer)
{
Library::Vector<int> newptrvector;
Assert::AreEqual(10U, newptrvector.Capacity(),
L"New Vector should have a Capacity of 10");
const auto constPointor(newptrvector);
Assert::AreEqual(10U, constPointor.Capacity());
int x[11];
for (int i = 0; i < 10; i++)
{
x[i] = i;
pointor.PushBack(&x[i]);
Assert::AreEqual(10U, pointor.Capacity(),
L"First ten pushes on a vector should retain the Capacity At 10");
}
x[10] = 99;
pointor.PushBack(&x[10]);
Assert::AreEqual(20U, pointor.Capacity(),
L"on 11th push, vector Capacity should be 20");
for (int i = 0; i < 11; i++)
{
pointor.PopBack();
Assert::AreEqual(10U, newptrvector.Capacity(),
L"New Vector should have Capacity of 10");
}
}
TEST_METHOD(TestCapacity_Foo)
{
Library::Vector<int> newfoovector;
Assert::AreEqual(10u, newfoovector.Capacity(),
L"New Vector should have a Capacity of 10");
const auto constFootor(newfoovector);
Assert::AreEqual(10u, constFootor.Capacity());
Foo foo[11];
for (int i = 0; i < 10; i++)
{
foo[i] = Foo(i);
footor.PushBack(foo[i]);
Assert::AreEqual(10u, footor.Capacity(),
L"First ten pushes on a vector should retain the Capacity At 10");
}
foo[10] = Foo(99);
footor.PushBack(foo[10]);
Assert::AreEqual(20u, footor.Capacity(),
L"on 11th push, vector Capacity should be 20");
for (int i = 0; i < 11; i++)
{
footor.PopBack();
Assert::AreEqual(10u, newfoovector.Capacity(),
L"New Vector should have Capacity of 10");
}
}
TEST_METHOD(TestIsEmpty_Integer)
{
const auto constIntor1(intor);
Assert::IsTrue(intor.IsEmpty(),
L"Cleared vector should be empty");
Assert::IsTrue(constIntor1.IsEmpty());
intor.PushBack(1);
const auto constIntor2(intor);
Assert::IsFalse(intor.IsEmpty(),
L"Non-empty vector should not be empty");
Assert::IsFalse(constIntor2.IsEmpty());
intor.PopBack();
const auto constIntor3(intor);
Assert::IsTrue(intor.IsEmpty(),
L"Vector should be empty after popping last value");
Assert::IsTrue(constIntor3.IsEmpty());
}
TEST_METHOD(TestIsEmpty_Pointer)
{
const auto constPointor1(pointor);
Assert::IsTrue(pointor.IsEmpty(),
L"Cleared vector should be empty");
Assert::IsTrue(constPointor1.IsEmpty());
int x = 1;
pointor.PushBack(&x);
const auto constPointor2(pointor);
Assert::IsFalse(pointor.IsEmpty(),
L"Non-empty vector should not be empty");
Assert::IsFalse(constPointor2.IsEmpty());
pointor.PopBack();
const auto constPointor3(pointor);
Assert::IsTrue(pointor.IsEmpty(),
L"Vector should be empty after popping last value");
Assert::IsTrue(constPointor3.IsEmpty());
}
TEST_METHOD(TestIsEmpty_Foo)
{
const auto constFootor1(footor);
Assert::IsTrue(footor.IsEmpty(),
L"Cleared vector should be empty");
Assert::IsTrue(constFootor1.IsEmpty());
Foo foo(1);
footor.PushBack(foo);
const auto constFootor2(footor);
Assert::IsFalse(footor.IsEmpty(),
L"Non-empty vector should not be empty");
Assert::IsFalse(constFootor2.IsEmpty());
footor.PopBack();
const auto constFootor3(footor);
Assert::IsTrue(footor.IsEmpty(),
L"Vector should be empty after popping last value");
Assert::IsTrue(constFootor3.IsEmpty());
}
TEST_METHOD(TestPushBack_Integer)
{
intor.PushBack(1);
Assert::IsTrue(intor.Back() == 1,
L"Value pushed to Back does not match");
Assert::IsTrue(*intor.begin() == 1,
L"First value pushed Back is not equivalent to begin");
intor.PushBack(2);
Assert::IsTrue(intor.Back() == 2,
L"Second value pushed Back is not equivalent to begin");
}
TEST_METHOD(TestPushBack_Pointer)
{
int x = 1;
int y = 2;
pointor.PushBack(&x);
Assert::IsTrue(pointor.Back() == &x,
L"Value pushed to Back does not match");
Assert::IsTrue(*pointor.begin() == &x,
L"First value pushed Back is not equivalent to begin");
pointor.PushBack(&y);
Assert::IsTrue(pointor.Back() == &y,
L"Second value pushed Back is not equivalent to begin");
}
TEST_METHOD(TestPushBack_Foo)
{
Foo foo(1);
Foo bar(2);
footor.PushBack(foo);
Assert::IsTrue(footor.Back() == foo,
L"Value pushed to Back does not match");
Assert::IsTrue(*footor.begin() == foo,
L"First value pushed Back is not equivalent to begin");
footor.PushBack(bar);
Assert::IsTrue(footor.Back() == bar,
L"Second value pushed Back is not equivalent to begin");
}
TEST_METHOD(TestReserve_Integer)
{
Assert::AreEqual(0u, intor.Capacity(),
L"Vector Capacity should be zero on Clear");
intor.Reserve(100);
Assert::AreEqual(100u, intor.Capacity(),
L"Vector Capacity not reserving specified value");
Assert::AreEqual(0u, intor.Size(),
L"Reserve changing vector Size erroneously");
intor.Reserve(10);
Assert::AreEqual(10u, intor.Capacity(),
L"Capacity not changing on Reserve when shrinking");
for (int i = 0; i < 10; i++)
{
intor.PushBack(i);
}
intor.Reserve(5);
Assert::AreEqual(10u, intor.Capacity(),
L"Reserving smaller than current Size should shrink to fit");
}
TEST_METHOD(TestReserve_Pointer)
{
Assert::AreEqual(0u, pointor.Capacity(),
L"Vector Capacity should be zero on Clear");
pointor.Reserve(100);
Assert::AreEqual(100u, pointor.Capacity(),
L"Vector Capacity not reserving specified value");
Assert::AreEqual(0u, pointor.Size(),
L"Reserve changing vector Size erroneously");
pointor.Reserve(10);
Assert::AreEqual(10u, pointor.Capacity(),
L"Capacity not changing on Reserve when shrinking");
int x[10];
for (int i = 0; i < 10; i++)
{
x[i] = i;
pointor.PushBack(&x[i]);
}
Assert::AreEqual(10u, pointor.Capacity(),
L"Reserving smaller than current Size should shrink to fit");
}
TEST_METHOD(TestReserve_Foo)
{
Assert::AreEqual(0u, footor.Capacity(),
L"Vector Capacity should be zero on Clear");
footor.Reserve(100);
Assert::AreEqual(100u, footor.Capacity(),
L"Vector Capacity not reserving specified value");
Assert::AreEqual(0u, footor.Size(),
L"Reserve changing vector Size erroneously");
footor.Reserve(10);
Assert::AreEqual(10u, footor.Capacity(),
L"Capacity not changing on Reserve when shrinking");
Foo foo(1);
for (int i = 0; i < 10; i++)
{
footor.PushBack(foo);
}
Assert::AreEqual(10u, footor.Capacity(),
L"Reserving smaller than current Size should shrink to fit");
}
TEST_METHOD(TestClear_Integer)
{
intor.PushBack(1);
Assert::AreEqual(1u, intor.Size(),
L"Size incorrect after pushing first value");
intor.Clear();
Assert::AreEqual(0u, intor.Size(),
L"Size not zero after Clear");
Assert::AreEqual(0u, intor.Capacity(),
L"Capacity not zero after Clear");
}
TEST_METHOD(TestClear_Pointer)
{
int x = 1;
pointor.PushBack(&x);
Assert::AreEqual(1u, pointor.Size(),
L"Size incorrect after pushing first value");
pointor.Clear();
Assert::AreEqual(0u, pointor.Size(),
L"Size not zero after Clear");
Assert::AreEqual(0u, pointor.Capacity(),
L"Capacity not zero after Clear");
}
TEST_METHOD(TestClear_Foo)
{
Foo foo(1);
footor.PushBack(foo);
Assert::AreEqual(1u, footor.Size(),
L"Size incorrect after pushing first value");
footor.Clear();
Assert::AreEqual(0u, footor.Size(),
L"Size not zero after Clear");
Assert::AreEqual(0u, footor.Capacity(),
L"Capacity not zero after Clear");
}
TEST_METHOD(TestRemove_Integer)
{
intor.PushBack(1);
intor.Remove(1);
Assert::AreEqual(0u, intor.Size(),
L"Size not reducing after removing a value");
intor.PushBack(2);
intor.Remove(1);
Assert::AreEqual(1u, intor.Size(),
L"Size changing after removing a nonexistent value");
}
TEST_METHOD(TestRemove_Pointer)
{
int x = 1;
int y = 2;
pointor.PushBack(&x);
pointor.Remove(&x);
Assert::AreEqual(0u, pointor.Size(),
L"Size not reducing after removing a value");
pointor.PushBack(&y);
pointor.Remove(&x);
Assert::AreEqual(1u, pointor.Size(),
L"Size changing after removing a nonexistent value");
}
TEST_METHOD(TestRemove_Foo)
{
Foo foo(1);
Foo bar(2);
footor.PushBack(foo);
footor.Remove(foo);
Assert::AreEqual(0u, footor.Size(),
L"Size not reducing after removing a value");
footor.PushBack(bar);
footor.Remove(foo);
Assert::AreEqual(1u, footor.Size(),
L"Size changing after removing a nonexistent value");
}
TEST_METHOD(TestShrinkToFit_Integer)
{
intor.PushBack(1);
intor.PushBack(2);
intor.PushBack(3);
Assert::AreEqual(10u, intor.Capacity(),
L"Default Capacity for vector should be 10");
intor.ShrinkToFit();
Assert::AreEqual(3u, intor.Capacity(),
L"Capacity should be 3 after shrinking to fit");
intor.Clear();
intor.ShrinkToFit();
Assert::AreEqual(0u, intor.Capacity(),
L"Capacity should be 0 after shrinking to fit on empty vector");
}
TEST_METHOD(TestShrinkToFit_Pointer)
{
int x = 1;
int y = 2;
int z = 3;
pointor.PushBack(&x);
pointor.PushBack(&y);
pointor.PushBack(&z);
Assert::AreEqual(10u, pointor.Capacity(),
L"Default Capacity for vector should be 10");
pointor.ShrinkToFit();
Assert::AreEqual(3u, pointor.Capacity(),
L"Capacity should be 3 after shrinking to fit");
pointor.Clear();
pointor.ShrinkToFit();
Assert::AreEqual(0u, pointor.Capacity(),
L"Capacity should be 3 after shrinking to fit on empty vector");
}
TEST_METHOD(TestShrinkToFit_Foo)
{
Foo foo(1);
Foo bar(2);
Foo gar(3);
footor.PushBack(foo);
footor.PushBack(bar);
footor.PushBack(gar);
Assert::AreEqual(10u, footor.Capacity(),
L"Default Capacity for vector should be 10");
footor.ShrinkToFit();
Assert::AreEqual(3u, footor.Capacity(),
L"Capacity should be 3 after shrinking to fit");
footor.Clear();
footor.ShrinkToFit();
Assert::AreEqual(0u, footor.Capacity(),
L"Capacity should be 3 after shrinking to fit on empty vector");
}
TEST_METHOD(TestIteratorComparisonOperator_Integer)
{
auto iter = intor.begin();
const auto iterCopy(iter);
Assert::IsTrue(iter == intor.begin(),
L"Iterator should be equivalent to the value it was assigned to");
Assert::IsTrue(iter == intor.end(),
L"Iterator should be equivalent to end when assigned to begin on an empty vector");
Assert::IsTrue(iterCopy == intor.begin());
Assert::IsTrue(iterCopy == intor.end());
intor.PushBack(1);
iter = intor.begin();
const auto secondIterCopy(iter);
Assert::IsFalse(iter == intor.end(),
L"Iterator assigned to begin should not be equivalent to end on a non-empty vector");
Assert::IsFalse(secondIterCopy == intor.end());
Library::Vector<int> newintvector;
auto newiter = newintvector.begin();
const auto newIterCopy(newiter);
Assert::IsFalse(iter == newiter,
L"Iterators with different owners should not be equivalent");
Assert::IsTrue(newIterCopy == newiter);
}
TEST_METHOD(TestIteratorComparisonOperator_Pointer)
{
auto piter = pointor.begin();
const auto piterCopy(piter);
Assert::IsTrue(piter == pointor.begin(),
L"Iterator should be equivalent to the value it was assigned to");
Assert::IsTrue(piter == pointor.end(),
L"Iterator should be equivalent to end when assigned to begin on an empty vector");
Assert::IsTrue(piterCopy == pointor.begin());
Assert::IsTrue(piterCopy == pointor.end());
int x = 1;
pointor.PushBack(&x);
piter = pointor.begin();
const auto piterSecondCopy(piter);
Assert::IsFalse(piter == pointor.end(),
L"Iterator assigned to begin should not be equivalent to end on a non-empty vector");
Assert::IsFalse(piterSecondCopy == pointor.end());
Library::Vector<int*> newptrvector;
auto newpiter = newptrvector.begin();
const auto newpiterCopy(newpiter);
Assert::IsFalse(piter == newpiter,
L"Iterators with different owners should not be equivalent");
Assert::IsTrue(newpiterCopy == newpiter);
}
TEST_METHOD(TestIteratorComparisonOperator_Foo)
{
auto fooiter = footor.begin();
const auto fooiterCopy(fooiter);
Assert::IsTrue(fooiter == footor.begin(),
L"Iterator should be equivalent to the value it was assigned to");
Assert::IsTrue(fooiter == footor.end(),
L"Iterator should be equivalent to end when assigned to begin on an empty vector");
Assert::IsTrue(fooiterCopy == footor.begin());
Assert::IsTrue(fooiterCopy == footor.end());
Foo foo(1);
footor.PushBack(foo);
fooiter = footor.begin();
const auto fooiterSecondCopy(fooiter);
Assert::IsFalse(fooiter == footor.end(),
L"Iterator assigned to begin should not be equivalent to end on a non-empty vector");
Assert::IsFalse(fooiterSecondCopy == footor.end());
Library::Vector<Foo> newfoovector;
auto newfooiter = newfoovector.begin();
const auto newfooiterCopy(newfooiter);
Assert::IsFalse(fooiter == newfooiter,
L"Iterators with different owners should not be equivalent");
Assert::IsTrue(newfooiterCopy == newfooiter);
}
TEST_METHOD(TestIteratorIncrement_Integer)
{
intor.PushBack(1);
auto iter = intor.begin();
Assert::IsFalse(iter == intor.end(),
L"Iterator assigned to begin on a non-empty vector should not be equivalent to end");
Assert::IsTrue(++iter == intor.end(),
L"Incrementing an iterator on a Size of one vector should be equivalent to end");
}
TEST_METHOD(TestIteratorIncrement_Pointer)
{
int x = 1;
pointor.PushBack(&x);
auto piter = pointor.begin();
Assert::IsFalse(piter == pointor.end(),
L"piterator assigned to begin on a non-empty vector should not be equivalent to end");
Assert::IsTrue(++piter == pointor.end(),
L"Incrementing an piterator on a Size of one vector should be equivalent to end");
}
TEST_METHOD(TestIteratorIncrement_Foo)
{
Foo foo(1);
footor.PushBack(foo);
auto fooiter = footor.begin();
Assert::IsFalse(fooiter == footor.end(),
L"fooiterator assigned to begin on a non-empty vector should not be equivalent to end");
Assert::IsTrue(++fooiter == footor.end(),
L"Incrementing an fooiterator on a Size of one vector should be equivalent to end");
}
TEST_METHOD(TestIteratorDereference_Integer)
{
auto iter = intor.begin();
auto func1 = [&] { *iter; };
Assert::ExpectException<std::exception>(func1,
L"Dereferencing begin on an empty vector should throw an exception");
intor.PushBack(1);
iter = intor.begin();
Assert::IsTrue(*iter == 1,
L"Dereferencing an iterator At begin should be equivalent to the first value pushed");
const auto constIntVector(intor);
Assert::IsTrue(*constIntVector.begin() == *intor.begin(),
L"Const copy begin not equivalent to original");
++iter;
Assert::ExpectException<std::exception>(func1,
L"Dereferencing end of a vector should throw an exception");
}
TEST_METHOD(TestIteratorDereference_Pointer)
{
auto piter = pointor.begin();
auto func2 = [&] { *piter; };
Assert::ExpectException<std::exception>(func2,
L"Dereferencing begin on an empty vector should throw an exception");
int x = 1;
pointor.PushBack(&x);
piter = pointor.begin();
Assert::IsTrue(*piter == &x,
L"Dereferencing an piterator At begin should be equivalent to the first value pushed");
const auto constPtrVector(pointor);
Assert::IsTrue(*constPtrVector.begin() == *pointor.begin(),
L"Const copy begin not equivalent to original");
++piter;
Assert::ExpectException<std::exception>(func2,
L"Dereferencing end of a vector should throw an exception");
}
TEST_METHOD(TestIteratorDereference_Foo)
{
auto fooiter = footor.begin();
auto func3 = [&] { *fooiter; };
Assert::ExpectException<std::exception>(func3,
L"Dereferencing begin on an empty vector should throw an exception");
Foo foo(1);
footor.PushBack(foo);
fooiter = footor.begin();
Assert::IsTrue(*fooiter == foo,
L"Dereferencing an fooiterator At begin should be equivalent to the first value pushed");
const auto constFooVector(footor);
Assert::IsTrue(*constFooVector.begin() == *footor.begin(),
L"Const copy begin not equivalent to original");
++fooiter;
Assert::ExpectException<std::exception>(func3,
L"Dereferencing end of a vector should throw an exception");
}
};
} | 36.899256 | 106 | 0.535823 | [
"vector"
] |
6c675a690bf74dacd0ec943c5110a3aa98d6386c | 3,151 | cpp | C++ | examples/scalapack2scalapack.cpp | aldubois/grid2grid | 99ef5af129cc3b55006acdf3eb64fe942f4f12de | [
"BSD-3-Clause"
] | 1 | 2019-05-10T08:49:02.000Z | 2019-05-10T08:49:02.000Z | examples/scalapack2scalapack.cpp | aldubois/grid2grid | 99ef5af129cc3b55006acdf3eb64fe942f4f12de | [
"BSD-3-Clause"
] | 6 | 2019-08-22T15:03:00.000Z | 2021-01-11T09:45:33.000Z | examples/scalapack2scalapack.cpp | aldubois/grid2grid | 99ef5af129cc3b55006acdf3eb64fe942f4f12de | [
"BSD-3-Clause"
] | 2 | 2020-05-15T22:52:31.000Z | 2020-09-11T17:12:54.000Z | #include <grid2grid/transform.hpp>
#include <grid2grid/cantor_mapping.hpp>
#include <mpi.h>
#include <options.hpp>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace grid2grid;
int main( int argc, char **argv ) {
options::initialize(argc, argv);
MPI_Init(&argc, &argv);
int P, rank;
MPI_Comm_size(MPI_COMM_WORLD, &P);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
auto m = options::next_int("-m", "--rows", "number of rows.", 10);
auto n = options::next_int("-n", "--cols", "number of columns.", 12);
auto bm1 = options::next_int("-ibm", "--init_block_rows", "Initial block size for rows.", 2);
auto bn1 = options::next_int("-ibn", "--init_block_cols", "Initial block size for columns.", 2);
auto bm2 = options::next_int("-fbm", "--final_block_rows", "Final block size for rows.", 4);
auto bn2 = options::next_int("-fbn", "--final_block_cols", "Final block size for columns.", 5);
auto pm = options::next_int("-pm", "--p_rows", "Processor grid rows.", 2);
auto pn = options::next_int("-pn", "--p_cols", "Processor grid column.", 2);
if (rank == 0) {
std::cout << "Matrix size = (" << m << ", " << n << ")" << std::endl;
std::cout << "Initial block size = (" << bm1 << ", " << bn1 << ")" << std::endl;
std::cout << "Final block size = (" << bm2 << ", " << bn2 << ")" << std::endl;
std::cout << "Processor grid = (" << pm << ", " << pn << ")" << std::endl;
}
auto values = [](int i, int j) {
return 1.0 * grid2grid::cantor_pairing(i, j);
};
scalapack::ordering ordering = scalapack::ordering::column_major;
scalapack::data_layout layout1({m, n}, {bm1, bn1}, {pm, pn}, ordering);
// initialize the local buffer as given by function values
// function 'values': maps global coordinates of the matrix to values
std::vector<double> buffer1(local_size(rank, layout1));
initialize_locally(buffer1.data(), values, rank, layout1);
// check if the values of buffer1 correspond to values
// given by argument function 'values'
bool ok = validate(values, buffer1, rank, layout1);
MPI_Barrier(MPI_COMM_WORLD);
grid_layout<double> scalapack_layout_1 = get_scalapack_grid(layout1, buffer1.data(), rank);
scalapack::data_layout layout2({m, n}, {bm2, bn2}, {pm, pn}, ordering);
// initialize the local buffer as given by function values
// function 'values': maps global coordinates of the matrix to values
std::vector<double> buffer2(local_size(rank, layout2));
initialize_locally(buffer2.data(), values, rank, layout2);
grid_layout<double> scalapack_layout_2 = get_scalapack_grid(layout2, buffer2.data(), rank);
// transform between two grid-like layouts
transform(scalapack_layout_1, scalapack_layout_2, MPI_COMM_WORLD);
// check if the values of buffer1 correspond to values
// given by argument function 'values'
ok = ok && validate(values, buffer2, rank, layout2);
std::cout << "Rank " << rank << ": result is" << (ok ? "" : " not") << " correct!" << std::endl;;
MPI_Finalize();
return !ok;
}
| 36.218391 | 101 | 0.633767 | [
"vector",
"transform"
] |
6c6a8627f3347816c67efbd7323aa83bdc9f81dd | 874 | cpp | C++ | lava/framework/core/options/shadermoduleoptions.cpp | BalderOdinson/LavaVk | f3241e1077bbfc8bbf14267d35e9c72272fceefa | [
"MIT"
] | null | null | null | lava/framework/core/options/shadermoduleoptions.cpp | BalderOdinson/LavaVk | f3241e1077bbfc8bbf14267d35e9c72272fceefa | [
"MIT"
] | null | null | null | lava/framework/core/options/shadermoduleoptions.cpp | BalderOdinson/LavaVk | f3241e1077bbfc8bbf14267d35e9c72272fceefa | [
"MIT"
] | null | null | null | //
// Created by dorian on 11. 12. 2019..
//
#include "shadermoduleoptions.h"
#include "lava/framework/gl_includer.h"
#include <utility>
LavaVk::Core::ShaderModuleOptions::ShaderModuleOptions(std::string filename, vk::ShaderStageFlagBits stage,
std::vector<ShaderResource> resources, std::string entryPoint)
: filename(std::move(filename)), stage(stage), resources(std::move(resources)),
entryPoint(std::move(entryPoint))
{
}
std::type_index LavaVk::Core::ShaderModuleOptions::getType() const
{
return typeid(ShaderModuleOptions);
}
size_t LavaVk::Core::ShaderModuleOptions::getHashCode() const
{
size_t result = 0;
glm::detail::hash_combine(result, std::hash<std::string>()(filename));
glm::detail::hash_combine(result, std::hash<std::string>()(entryPoint));
return result;
}
| 31.214286 | 117 | 0.675057 | [
"vector"
] |
6c72b32e3ed6a0cca1de3c6461af7defc46ccdc3 | 22,107 | cpp | C++ | src/qt/qtwebkit/Source/WebKit2/WebProcess/WebPage/WebFrame.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebKit2/WebProcess/WebPage/WebFrame.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebKit2/WebProcess/WebPage/WebFrame.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2022-02-18T10:41:38.000Z | 2022-02-18T10:41:38.000Z | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#include "WebFrame.h"
#include "DownloadManager.h"
#include "InjectedBundleHitTestResult.h"
#include "InjectedBundleNodeHandle.h"
#include "InjectedBundleRangeHandle.h"
#include "InjectedBundleScriptWorld.h"
#include "PluginView.h"
#include "WKAPICast.h"
#include "WKBundleAPICast.h"
#include "WebChromeClient.h"
#include "WebPage.h"
#include "WebPageProxyMessages.h"
#include "WebProcess.h"
#include <JavaScriptCore/APICast.h>
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSLock.h>
#include <JavaScriptCore/JSValueRef.h>
#include <WebCore/ArchiveResource.h>
#include <WebCore/Chrome.h>
#include <WebCore/DocumentLoader.h>
#include <WebCore/EventHandler.h>
#include <WebCore/Frame.h>
#include <WebCore/FrameView.h>
#include <WebCore/HTMLFormElement.h>
#include <WebCore/HTMLFrameOwnerElement.h>
#include <WebCore/HTMLInputElement.h>
#include <WebCore/HTMLNames.h>
#include <WebCore/HTMLTextAreaElement.h>
#include <WebCore/JSCSSStyleDeclaration.h>
#include <WebCore/JSElement.h>
#include <WebCore/JSRange.h>
#include <WebCore/NetworkingContext.h>
#include <WebCore/NodeTraversal.h>
#include <WebCore/Page.h>
#include <WebCore/PluginDocument.h>
#include <WebCore/RenderTreeAsText.h>
#include <WebCore/ResourceBuffer.h>
#include <WebCore/ResourceLoader.h>
#include <WebCore/ScriptController.h>
#include <WebCore/SecurityOrigin.h>
#include <WebCore/TextIterator.h>
#include <WebCore/TextResourceDecoder.h>
#include <wtf/text/StringBuilder.h>
#if PLATFORM(MAC)
#include <WebCore/LegacyWebArchive.h>
#endif
#if ENABLE(NETWORK_PROCESS)
#include "NetworkConnectionToWebProcessMessages.h"
#include "NetworkProcessConnection.h"
#include "WebCoreArgumentCoders.h"
#endif
#ifndef NDEBUG
#include <wtf/RefCountedLeakCounter.h>
#endif
using namespace JSC;
using namespace WebCore;
namespace WebKit {
DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webFrameCounter, ("WebFrame"));
static uint64_t generateFrameID()
{
static uint64_t uniqueFrameID = 1;
return uniqueFrameID++;
}
static uint64_t generateListenerID()
{
static uint64_t uniqueListenerID = 1;
return uniqueListenerID++;
}
PassRefPtr<WebFrame> WebFrame::createMainFrame(WebPage* page)
{
RefPtr<WebFrame> frame = create();
page->send(Messages::WebPageProxy::DidCreateMainFrame(frame->frameID()));
frame->init(page, String(), 0);
return frame.release();
}
PassRefPtr<WebFrame> WebFrame::createSubframe(WebPage* page, const String& frameName, HTMLFrameOwnerElement* ownerElement)
{
RefPtr<WebFrame> frame = create();
page->send(Messages::WebPageProxy::DidCreateSubframe(frame->frameID()));
frame->init(page, frameName, ownerElement);
return frame.release();
}
PassRefPtr<WebFrame> WebFrame::create()
{
RefPtr<WebFrame> frame = adoptRef(new WebFrame);
// Add explict ref() that will be balanced in WebFrameLoaderClient::frameLoaderDestroyed().
frame->ref();
return frame.release();
}
WebFrame::WebFrame()
: m_coreFrame(0)
, m_policyListenerID(0)
, m_policyFunction(0)
, m_policyDownloadID(0)
, m_frameLoaderClient(this)
, m_loadListener(0)
, m_frameID(generateFrameID())
{
WebProcess::shared().addWebFrame(m_frameID, this);
#ifndef NDEBUG
webFrameCounter.increment();
#endif
}
WebFrame::~WebFrame()
{
ASSERT(!m_coreFrame);
#ifndef NDEBUG
webFrameCounter.decrement();
#endif
}
void WebFrame::init(WebPage* page, const String& frameName, HTMLFrameOwnerElement* ownerElement)
{
RefPtr<Frame> frame = Frame::create(page->corePage(), ownerElement, &m_frameLoaderClient);
m_coreFrame = frame.get();
frame->tree()->setName(frameName);
if (ownerElement) {
ASSERT(ownerElement->document()->frame());
ownerElement->document()->frame()->tree()->appendChild(frame);
}
frame->init();
}
WebPage* WebFrame::page() const
{
if (!m_coreFrame)
return 0;
if (Page* page = m_coreFrame->page())
return WebPage::fromCorePage(page);
return 0;
}
void WebFrame::invalidate()
{
WebProcess::shared().removeWebFrame(m_frameID);
m_coreFrame = 0;
}
uint64_t WebFrame::setUpPolicyListener(WebCore::FramePolicyFunction policyFunction)
{
// FIXME: <rdar://5634381> We need to support multiple active policy listeners.
invalidatePolicyListener();
m_policyListenerID = generateListenerID();
m_policyFunction = policyFunction;
return m_policyListenerID;
}
void WebFrame::invalidatePolicyListener()
{
if (!m_policyListenerID)
return;
m_policyDownloadID = 0;
m_policyListenerID = 0;
m_policyFunction = 0;
}
void WebFrame::didReceivePolicyDecision(uint64_t listenerID, PolicyAction action, uint64_t downloadID)
{
if (!m_coreFrame)
return;
if (!m_policyListenerID)
return;
if (listenerID != m_policyListenerID)
return;
ASSERT(m_policyFunction);
FramePolicyFunction function = m_policyFunction;
invalidatePolicyListener();
m_policyDownloadID = downloadID;
(m_coreFrame->loader()->policyChecker()->*function)(action);
}
void WebFrame::startDownload(const WebCore::ResourceRequest& request)
{
ASSERT(m_policyDownloadID);
uint64_t policyDownloadID = m_policyDownloadID;
m_policyDownloadID = 0;
#if ENABLE(NETWORK_PROCESS)
if (WebProcess::shared().usesNetworkProcess()) {
bool privateBrowsingEnabled = m_coreFrame->loader()->networkingContext()->storageSession().isPrivateBrowsingSession();
WebProcess::shared().networkConnection()->connection()->send(Messages::NetworkConnectionToWebProcess::StartDownload(privateBrowsingEnabled, policyDownloadID, request), 0);
return;
}
#endif
WebProcess::shared().downloadManager().startDownload(policyDownloadID, request);
}
void WebFrame::convertMainResourceLoadToDownload(DocumentLoader* documentLoader, const ResourceRequest& request, const ResourceResponse& response)
{
ASSERT(m_policyDownloadID);
uint64_t policyDownloadID = m_policyDownloadID;
m_policyDownloadID = 0;
ResourceLoader* mainResourceLoader = documentLoader->mainResourceLoader();
#if ENABLE(NETWORK_PROCESS)
if (WebProcess::shared().usesNetworkProcess()) {
// Use 0 to indicate that there is no main resource loader.
// This can happen if the main resource is in the WebCore memory cache.
uint64_t mainResourceLoadIdentifier;
if (mainResourceLoader)
mainResourceLoadIdentifier = mainResourceLoader->identifier();
else
mainResourceLoadIdentifier = 0;
WebProcess::shared().networkConnection()->connection()->send(Messages::NetworkConnectionToWebProcess::ConvertMainResourceLoadToDownload(mainResourceLoadIdentifier, policyDownloadID, request, response), 0);
return;
}
#endif
if (!mainResourceLoader) {
// The main resource has already been loaded. Start a new download instead.
WebProcess::shared().downloadManager().startDownload(policyDownloadID, request);
return;
}
WebProcess::shared().downloadManager().convertHandleToDownload(policyDownloadID, documentLoader->mainResourceLoader()->handle(), request, response);
}
String WebFrame::source() const
{
if (!m_coreFrame)
return String();
Document* document = m_coreFrame->document();
if (!document)
return String();
TextResourceDecoder* decoder = document->decoder();
if (!decoder)
return String();
DocumentLoader* documentLoader = m_coreFrame->loader()->activeDocumentLoader();
if (!documentLoader)
return String();
RefPtr<ResourceBuffer> mainResourceData = documentLoader->mainResourceData();
if (!mainResourceData)
return String();
return decoder->encoding().decode(mainResourceData->data(), mainResourceData->size());
}
String WebFrame::contentsAsString() const
{
if (!m_coreFrame)
return String();
if (isFrameSet()) {
StringBuilder builder;
for (Frame* child = m_coreFrame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
if (!builder.isEmpty())
builder.append(' ');
WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(child->loader()->client());
WebFrame* webFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0;
ASSERT(webFrame);
builder.append(webFrame->contentsAsString());
}
// FIXME: It may make sense to use toStringPreserveCapacity() here.
return builder.toString();
}
Document* document = m_coreFrame->document();
if (!document)
return String();
RefPtr<Element> documentElement = document->documentElement();
if (!documentElement)
return String();
RefPtr<Range> range = document->createRange();
ExceptionCode ec = 0;
range->selectNode(documentElement.get(), ec);
if (ec)
return String();
return plainText(range.get());
}
String WebFrame::selectionAsString() const
{
if (!m_coreFrame)
return String();
return m_coreFrame->displayStringModifiedByEncoding(m_coreFrame->editor().selectedText());
}
IntSize WebFrame::size() const
{
if (!m_coreFrame)
return IntSize();
FrameView* frameView = m_coreFrame->view();
if (!frameView)
return IntSize();
return frameView->contentsSize();
}
bool WebFrame::isFrameSet() const
{
if (!m_coreFrame)
return false;
Document* document = m_coreFrame->document();
if (!document)
return false;
return document->isFrameSet();
}
bool WebFrame::isMainFrame() const
{
if (WebPage* p = page())
return p->mainWebFrame() == this;
return false;
}
String WebFrame::name() const
{
if (!m_coreFrame)
return String();
return m_coreFrame->tree()->uniqueName();
}
String WebFrame::url() const
{
if (!m_coreFrame)
return String();
DocumentLoader* documentLoader = m_coreFrame->loader()->documentLoader();
if (!documentLoader)
return String();
return documentLoader->url().string();
}
String WebFrame::innerText() const
{
if (!m_coreFrame)
return String();
if (!m_coreFrame->document()->documentElement())
return String();
return m_coreFrame->document()->documentElement()->innerText();
}
WebFrame* WebFrame::parentFrame() const
{
if (!m_coreFrame || !m_coreFrame->ownerElement() || !m_coreFrame->ownerElement()->document())
return 0;
WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(m_coreFrame->ownerElement()->document()->frame()->loader()->client());
return webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0;
}
PassRefPtr<ImmutableArray> WebFrame::childFrames()
{
if (!m_coreFrame)
return ImmutableArray::create();
size_t size = m_coreFrame->tree()->childCount();
if (!size)
return ImmutableArray::create();
Vector<RefPtr<APIObject> > vector;
vector.reserveInitialCapacity(size);
for (Frame* child = m_coreFrame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(child->loader()->client());
WebFrame* webFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0;
ASSERT(webFrame);
vector.uncheckedAppend(webFrame);
}
return ImmutableArray::adopt(vector);
}
String WebFrame::layerTreeAsText() const
{
if (!m_coreFrame)
return "";
return m_coreFrame->layerTreeAsText(0);
}
unsigned WebFrame::pendingUnloadCount() const
{
if (!m_coreFrame)
return 0;
return m_coreFrame->document()->domWindow()->pendingUnloadEventListeners();
}
bool WebFrame::allowsFollowingLink(const WebCore::KURL& url) const
{
if (!m_coreFrame)
return true;
return m_coreFrame->document()->securityOrigin()->canDisplay(url);
}
JSGlobalContextRef WebFrame::jsContext()
{
return toGlobalRef(m_coreFrame->script()->globalObject(mainThreadNormalWorld())->globalExec());
}
JSGlobalContextRef WebFrame::jsContextForWorld(InjectedBundleScriptWorld* world)
{
return toGlobalRef(m_coreFrame->script()->globalObject(world->coreWorld())->globalExec());
}
bool WebFrame::handlesPageScaleGesture() const
{
if (!m_coreFrame->document()->isPluginDocument())
return 0;
PluginDocument* pluginDocument = static_cast<PluginDocument*>(m_coreFrame->document());
PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
return pluginView && pluginView->handlesPageScaleFactor();
}
IntRect WebFrame::contentBounds() const
{
if (!m_coreFrame)
return IntRect();
FrameView* view = m_coreFrame->view();
if (!view)
return IntRect();
return IntRect(0, 0, view->contentsWidth(), view->contentsHeight());
}
IntRect WebFrame::visibleContentBounds() const
{
if (!m_coreFrame)
return IntRect();
FrameView* view = m_coreFrame->view();
if (!view)
return IntRect();
IntRect contentRect = view->visibleContentRect(ScrollableArea::IncludeScrollbars);
return IntRect(0, 0, contentRect.width(), contentRect.height());
}
IntRect WebFrame::visibleContentBoundsExcludingScrollbars() const
{
if (!m_coreFrame)
return IntRect();
FrameView* view = m_coreFrame->view();
if (!view)
return IntRect();
IntRect contentRect = view->visibleContentRect();
return IntRect(0, 0, contentRect.width(), contentRect.height());
}
IntSize WebFrame::scrollOffset() const
{
if (!m_coreFrame)
return IntSize();
FrameView* view = m_coreFrame->view();
if (!view)
return IntSize();
return view->scrollOffset();
}
bool WebFrame::hasHorizontalScrollbar() const
{
if (!m_coreFrame)
return false;
FrameView* view = m_coreFrame->view();
if (!view)
return false;
return view->horizontalScrollbar();
}
bool WebFrame::hasVerticalScrollbar() const
{
if (!m_coreFrame)
return false;
FrameView* view = m_coreFrame->view();
if (!view)
return false;
return view->verticalScrollbar();
}
PassRefPtr<InjectedBundleHitTestResult> WebFrame::hitTest(const IntPoint point) const
{
if (!m_coreFrame)
return 0;
return InjectedBundleHitTestResult::create(m_coreFrame->eventHandler()->hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent));
}
bool WebFrame::getDocumentBackgroundColor(double* red, double* green, double* blue, double* alpha)
{
if (!m_coreFrame)
return false;
FrameView* view = m_coreFrame->view();
if (!view)
return false;
Color bgColor = view->documentBackgroundColor();
if (!bgColor.isValid())
return false;
bgColor.getRGBA(*red, *green, *blue, *alpha);
return true;
}
bool WebFrame::containsAnyFormElements() const
{
if (!m_coreFrame)
return false;
Document* document = m_coreFrame->document();
if (!document)
return false;
for (Node* node = document->documentElement(); node; node = NodeTraversal::next(node)) {
if (!node->isElementNode())
continue;
if (isHTMLFormElement(node))
return true;
}
return false;
}
bool WebFrame::containsAnyFormControls() const
{
if (!m_coreFrame)
return false;
Document* document = m_coreFrame->document();
if (!document)
return false;
for (Node* node = document->documentElement(); node; node = NodeTraversal::next(node)) {
if (!node->isElementNode())
continue;
if (isHTMLInputElement(node) || toElement(node)->hasTagName(HTMLNames::selectTag) || isHTMLTextAreaElement(node))
return true;
}
return false;
}
void WebFrame::stopLoading()
{
if (!m_coreFrame)
return;
m_coreFrame->loader()->stopForUserCancel();
}
WebFrame* WebFrame::frameForContext(JSContextRef context)
{
JSObjectRef globalObjectRef = JSContextGetGlobalObject(context);
JSC::JSObject* globalObjectObj = toJS(globalObjectRef);
if (strcmp(globalObjectObj->classInfo()->className, "JSDOMWindowShell") != 0)
return 0;
Frame* coreFrame = static_cast<JSDOMWindowShell*>(globalObjectObj)->window()->impl()->frame();
WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(coreFrame->loader()->client());
return webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0;
}
JSValueRef WebFrame::jsWrapperForWorld(InjectedBundleNodeHandle* nodeHandle, InjectedBundleScriptWorld* world)
{
if (!m_coreFrame)
return 0;
JSDOMWindow* globalObject = m_coreFrame->script()->globalObject(world->coreWorld());
ExecState* exec = globalObject->globalExec();
JSLockHolder lock(exec);
return toRef(exec, toJS(exec, globalObject, nodeHandle->coreNode()));
}
JSValueRef WebFrame::jsWrapperForWorld(InjectedBundleRangeHandle* rangeHandle, InjectedBundleScriptWorld* world)
{
if (!m_coreFrame)
return 0;
JSDOMWindow* globalObject = m_coreFrame->script()->globalObject(world->coreWorld());
ExecState* exec = globalObject->globalExec();
JSLockHolder lock(exec);
return toRef(exec, toJS(exec, globalObject, rangeHandle->coreRange()));
}
String WebFrame::counterValue(JSObjectRef element)
{
if (!toJS(element)->inherits(&JSElement::s_info))
return String();
return counterValueForElement(static_cast<JSElement*>(toJS(element))->impl());
}
String WebFrame::provisionalURL() const
{
if (!m_coreFrame)
return String();
return m_coreFrame->loader()->provisionalDocumentLoader()->url().string();
}
String WebFrame::suggestedFilenameForResourceWithURL(const KURL& url) const
{
if (!m_coreFrame)
return String();
DocumentLoader* loader = m_coreFrame->loader()->documentLoader();
if (!loader)
return String();
// First, try the main resource.
if (loader->url() == url)
return loader->response().suggestedFilename();
// Next, try subresources.
RefPtr<ArchiveResource> resource = loader->subresource(url);
if (resource)
return resource->response().suggestedFilename();
return page()->cachedSuggestedFilenameForURL(url);
}
String WebFrame::mimeTypeForResourceWithURL(const KURL& url) const
{
if (!m_coreFrame)
return String();
DocumentLoader* loader = m_coreFrame->loader()->documentLoader();
if (!loader)
return String();
// First, try the main resource.
if (loader->url() == url)
return loader->response().mimeType();
// Next, try subresources.
RefPtr<ArchiveResource> resource = loader->subresource(url);
if (resource)
return resource->mimeType();
return page()->cachedResponseMIMETypeForURL(url);
}
void WebFrame::setTextDirection(const String& direction)
{
if (!m_coreFrame)
return;
if (direction == "auto")
m_coreFrame->editor().setBaseWritingDirection(NaturalWritingDirection);
else if (direction == "ltr")
m_coreFrame->editor().setBaseWritingDirection(LeftToRightWritingDirection);
else if (direction == "rtl")
m_coreFrame->editor().setBaseWritingDirection(RightToLeftWritingDirection);
}
#if PLATFORM(MAC)
class WebFrameFilter : public FrameFilter {
public:
WebFrameFilter(WebFrame*, WebFrame::FrameFilterFunction, void* context);
private:
virtual bool shouldIncludeSubframe(Frame*) const OVERRIDE;
WebFrame* m_topLevelWebFrame;
WebFrame::FrameFilterFunction m_callback;
void* m_context;
};
WebFrameFilter::WebFrameFilter(WebFrame* topLevelWebFrame, WebFrame::FrameFilterFunction callback, void* context)
: m_topLevelWebFrame(topLevelWebFrame)
, m_callback(callback)
, m_context(context)
{
}
bool WebFrameFilter::shouldIncludeSubframe(Frame* frame) const
{
if (!m_callback)
return true;
WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader()->client());
WebFrame* webFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0;
ASSERT(webFrame);
return m_callback(toAPI(m_topLevelWebFrame), toAPI(webFrame), m_context);
}
RetainPtr<CFDataRef> WebFrame::webArchiveData(FrameFilterFunction callback, void* context)
{
WebFrameFilter filter(this, callback, context);
if (RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(coreFrame()->document(), &filter))
return archive->rawDataRepresentation();
return 0;
}
#endif
} // namespace WebKit
| 28.090216 | 229 | 0.701316 | [
"vector"
] |
6c737cc83e3ee37cbbd69d148fa17e008fbd5bf2 | 31,439 | hh | C++ | src/usr.bin/dtc/fdt.hh | lastweek/source-freebsd | 0821950b0c40cbc891a27964b342e0202a3859ec | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/usr.bin/dtc/fdt.hh | lastweek/source-freebsd | 0821950b0c40cbc891a27964b342e0202a3859ec | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/usr.bin/dtc/fdt.hh | lastweek/source-freebsd | 0821950b0c40cbc891a27964b342e0202a3859ec | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | /*-
* SPDX-License-Identifier: BSD-2-Clause-FreeBSD
*
* Copyright (c) 2013 David Chisnall
* All rights reserved.
*
* This software was developed by SRI International and the University of
* Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237)
* ("CTSRD"), as part of the DARPA CRASH research programme.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $FreeBSD$
*/
#ifndef _FDT_HH_
#define _FDT_HH_
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <memory>
#include <string>
#include <functional>
#include "util.hh"
#include "input_buffer.hh"
namespace dtc
{
namespace dtb
{
struct output_writer;
class string_table;
}
namespace fdt
{
class property;
class node;
class device_tree;
/**
* Type for device tree write functions.
*/
typedef void (device_tree::* tree_write_fn_ptr)(int);
/**
* Type for device tree read functions.
*/
typedef void (device_tree::* tree_read_fn_ptr)(const std::string &, FILE *);
/**
* Type for (owned) pointers to properties.
*/
typedef std::shared_ptr<property> property_ptr;
/**
* Owning pointer to a node.
*/
typedef std::unique_ptr<node> node_ptr;
/**
* Map from macros to property pointers.
*/
typedef std::unordered_map<std::string, property_ptr> define_map;
/**
* Set of strings used for label names.
*/
typedef std::unordered_set<std::string> string_set;
/**
* Properties may contain a number of different value, each with a different
* label. This class encapsulates a single value.
*/
struct property_value
{
/**
* The label for this data. This is usually empty.
*/
std::string label;
/**
* If this value is a string, or something resolved from a string (a
* reference) then this contains the source string.
*/
std::string string_data;
/**
* The data that should be written to the final output.
*/
byte_buffer byte_data;
/**
* Enumeration describing the possible types of a value. Note that
* property-coded arrays will appear simply as binary (or possibly
* string, if they happen to be nul-terminated and printable), and must
* be checked separately.
*/
enum value_type
{
/**
* This is a list of strings. When read from source, string
* lists become one property value for each string, however
* when read from binary we have a single property value
* incorporating the entire text, with nul bytes separating the
* strings.
*/
STRING_LIST,
/**
* This property contains a single string.
*/
STRING,
/**
* This is a binary value. Check the size of byte_data to
* determine how many bytes this contains.
*/
BINARY,
/** This contains a short-form address that should be replaced
* by a fully-qualified version. This will only appear when
* the input is a device tree source. When parsed from a
* device tree blob, the cross reference will have already been
* resolved and the property value will be a string containing
* the full path of the target node. */
CROSS_REFERENCE,
/**
* This is a phandle reference. When parsed from source, the
* string_data will contain the node label for the target and,
* after cross references have been resolved, the binary data
* will contain a 32-bit integer that should match the phandle
* property of the target node.
*/
PHANDLE,
/**
* An empty property value. This will never appear on a real
* property value, it is used by checkers to indicate that no
* property values should exist for a property.
*/
EMPTY,
/**
* The type of this property has not yet been determined.
*/
UNKNOWN
};
/**
* The type of this property.
*/
value_type type;
/**
* Returns true if this value is a cross reference, false otherwise.
*/
inline bool is_cross_reference()
{
return is_type(CROSS_REFERENCE);
}
/**
* Returns true if this value is a phandle reference, false otherwise.
*/
inline bool is_phandle()
{
return is_type(PHANDLE);
}
/**
* Returns true if this value is a string, false otherwise.
*/
inline bool is_string()
{
return is_type(STRING);
}
/**
* Returns true if this value is a string list (a nul-separated
* sequence of strings), false otherwise.
*/
inline bool is_string_list()
{
return is_type(STRING_LIST);
}
/**
* Returns true if this value is binary, false otherwise.
*/
inline bool is_binary()
{
return is_type(BINARY);
}
/**
* Returns this property value as a 32-bit integer. Returns 0 if this
* property value is not 32 bits long. The bytes in the property value
* are assumed to be in big-endian format, but the return value is in
* the host native endian.
*/
uint32_t get_as_uint32();
/**
* Default constructor, specifying the label of the value.
*/
property_value(std::string l=std::string()) : label(l), type(UNKNOWN) {}
/**
* Writes the data for this value into an output buffer.
*/
void push_to_buffer(byte_buffer &buffer);
/**
* Writes the property value to the standard output. This uses the
* following heuristics for deciding how to print the output:
*
* - If the value is nul-terminated and only contains printable
* characters, it is written as a string.
* - If it is a multiple of 4 bytes long, then it is printed as cells.
* - Otherwise, it is printed as a byte buffer.
*/
void write_dts(FILE *file);
/**
* Tries to merge adjacent property values, returns true if it succeeds and
* false otherwise.
*/
bool try_to_merge(property_value &other);
/**
* Returns the size (in bytes) of this property value.
*/
size_t size();
private:
/**
* Returns whether the value is of the specified type. If the type of
* the value has not yet been determined, then this calculates it.
*/
inline bool is_type(value_type v)
{
if (type == UNKNOWN)
{
resolve_type();
}
return type == v;
}
/**
* Determines the type of the value based on its contents.
*/
void resolve_type();
/**
* Writes the property value to the specified file as a quoted string.
* This is used when generating DTS.
*/
void write_as_string(FILE *file);
/**
* Writes the property value to the specified file as a sequence of
* 32-bit big-endian cells. This is used when generating DTS.
*/
void write_as_cells(FILE *file);
/**
* Writes the property value to the specified file as a sequence of
* bytes. This is used when generating DTS.
*/
void write_as_bytes(FILE *file);
};
/**
* A value encapsulating a single property. This contains a key, optionally a
* label, and optionally one or more values.
*/
class property
{
/**
* The name of this property.
*/
std::string key;
/**
* Zero or more labels.
*/
string_set labels;
/**
* The values in this property.
*/
std::vector<property_value> values;
/**
* Value indicating that this is a valid property. If a parse error
* occurs, then this value is false.
*/
bool valid;
/**
* Parses a string property value, i.e. a value enclosed in double quotes.
*/
void parse_string(text_input_buffer &input);
/**
* Parses one or more 32-bit values enclosed in angle brackets.
*/
void parse_cells(text_input_buffer &input, int cell_size);
/**
* Parses an array of bytes, contained within square brackets.
*/
void parse_bytes(text_input_buffer &input);
/**
* Parses a reference. This is a node label preceded by an ampersand
* symbol, which should expand to the full path to that node.
*
* Note: The specification says that the target of such a reference is
* a node name, however dtc assumes that it is a label, and so we
* follow their interpretation for compatibility.
*/
void parse_reference(text_input_buffer &input);
/**
* Parse a predefined macro definition for a property.
*/
void parse_define(text_input_buffer &input, define_map *defines);
/**
* Constructs a new property from two input buffers, pointing to the
* struct and strings tables in the device tree blob, respectively.
* The structs input buffer is assumed to have just consumed the
* FDT_PROP token.
*/
property(input_buffer &structs, input_buffer &strings);
/**
* Parses a new property from the input buffer.
*/
property(text_input_buffer &input,
std::string &&k,
string_set &&l,
bool terminated,
define_map *defines);
public:
/**
* Creates an empty property.
*/
property(std::string &&k, string_set &&l=string_set())
: key(k), labels(l), valid(true) {}
/**
* Copy constructor.
*/
property(property &p) : key(p.key), labels(p.labels), values(p.values),
valid(p.valid) {}
/**
* Factory method for constructing a new property. Attempts to parse a
* property from the input, and returns it on success. On any parse
* error, this will return 0.
*/
static property_ptr parse_dtb(input_buffer &structs,
input_buffer &strings);
/**
* Factory method for constructing a new property. Attempts to parse a
* property from the input, and returns it on success. On any parse
* error, this will return 0.
*/
static property_ptr parse(text_input_buffer &input,
std::string &&key,
string_set &&labels=string_set(),
bool semicolonTerminated=true,
define_map *defines=0);
/**
* Iterator type used for accessing the values of a property.
*/
typedef std::vector<property_value>::iterator value_iterator;
/**
* Returns an iterator referring to the first value in this property.
*/
inline value_iterator begin()
{
return values.begin();
}
/**
* Returns an iterator referring to the last value in this property.
*/
inline value_iterator end()
{
return values.end();
}
/**
* Adds a new value to an existing property.
*/
inline void add_value(property_value v)
{
values.push_back(v);
}
/**
* Returns the key for this property.
*/
inline const std::string &get_key()
{
return key;
}
/**
* Writes the property to the specified writer. The property name is a
* reference into the strings table.
*/
void write(dtb::output_writer &writer, dtb::string_table &strings);
/**
* Writes in DTS format to the specified file, at the given indent
* level. This will begin the line with the number of tabs specified
* as the indent level and then write the property in the most
* applicable way that it can determine.
*/
void write_dts(FILE *file, int indent);
/**
* Returns the byte offset of the specified property value.
*/
size_t offset_of_value(property_value &val);
};
/**
* Class encapsulating a device tree node. Nodes may contain properties and
* other nodes.
*/
class node
{
public:
/**
* The labels for this node, if any. Node labels are used as the
* targets for cross references.
*/
std::unordered_set<std::string> labels;
/**
* The name of the node.
*/
std::string name;
/**
* The name of the node is a path reference.
*/
bool name_is_path_reference = false;
/**
* The unit address of the node, which is optionally written after the
* name followed by an at symbol.
*/
std::string unit_address;
/**
* A flag indicating that this node has been marked /omit-if-no-ref/ and
* will be omitted if it is not referenced, either directly or indirectly,
* by a node that is not similarly denoted.
*/
bool omit_if_no_ref = false;
/**
* A flag indicating that this node has been referenced, either directly
* or indirectly, by a node that is not marked /omit-if-no-ref/.
*/
bool used = false;
/**
* The type for the property vector.
*/
typedef std::vector<property_ptr> property_vector;
/**
* Iterator type for child nodes.
*/
typedef std::vector<node_ptr>::iterator child_iterator;
/**
* Recursion behavior to be observed for visiting
*/
enum visit_behavior
{
/**
* Recurse as normal through the rest of the tree.
*/
VISIT_RECURSE,
/**
* Continue recursing through the device tree, but do not
* recurse through this branch of the tree any further.
*/
VISIT_CONTINUE,
/**
* Immediately halt the visit. No further nodes will be visited.
*/
VISIT_BREAK
};
private:
/**
* Adaptor to use children in range-based for loops.
*/
struct child_range
{
child_range(node &nd) : n(nd) {}
child_iterator begin() { return n.child_begin(); }
child_iterator end() { return n.child_end(); }
private:
node &n;
};
/**
* Adaptor to use properties in range-based for loops.
*/
struct property_range
{
property_range(node &nd) : n(nd) {}
property_vector::iterator begin() { return n.property_begin(); }
property_vector::iterator end() { return n.property_end(); }
private:
node &n;
};
/**
* The properties contained within this node.
*/
property_vector props;
/**
* The children of this node.
*/
std::vector<node_ptr> children;
/**
* Children that should be deleted from this node when merging.
*/
std::unordered_set<std::string> deleted_children;
/**
* Properties that should be deleted from this node when merging.
*/
std::unordered_set<std::string> deleted_props;
/**
* A flag indicating whether this node is valid. This is set to false
* if an error occurs during parsing.
*/
bool valid;
/**
* Parses a name inside a node, writing the string passed as the last
* argument as an error if it fails.
*/
std::string parse_name(text_input_buffer &input,
bool &is_property,
const char *error);
/**
* Constructs a new node from two input buffers, pointing to the struct
* and strings tables in the device tree blob, respectively.
*/
node(input_buffer &structs, input_buffer &strings);
/**
* Parses a new node from the specified input buffer. This is called
* when the input cursor is on the open brace for the start of the
* node. The name, and optionally label and unit address, should have
* already been parsed.
*/
node(text_input_buffer &input,
device_tree &tree,
std::string &&n,
std::unordered_set<std::string> &&l,
std::string &&a,
define_map*);
/**
* Creates a special node with the specified name and properties.
*/
node(const std::string &n, const std::vector<property_ptr> &p);
/**
* Comparison function for properties, used when sorting the properties
* vector. Orders the properties based on their names.
*/
static inline bool cmp_properties(property_ptr &p1, property_ptr &p2);
/*
{
return p1->get_key() < p2->get_key();
}
*/
/**
* Comparison function for nodes, used when sorting the children
* vector. Orders the nodes based on their names or, if the names are
* the same, by the unit addresses.
*/
static inline bool cmp_children(node_ptr &c1, node_ptr &c2);
public:
/**
* Sorts the node's properties and children into alphabetical order and
* recursively sorts the children.
*/
void sort();
/**
* Returns an iterator for the first child of this node.
*/
inline child_iterator child_begin()
{
return children.begin();
}
/**
* Returns an iterator after the last child of this node.
*/
inline child_iterator child_end()
{
return children.end();
}
/**
* Returns a range suitable for use in a range-based for loop describing
* the children of this node.
*/
inline child_range child_nodes()
{
return child_range(*this);
}
/**
* Accessor for the deleted children.
*/
inline const std::unordered_set<std::string> &deleted_child_nodes()
{
return deleted_children;
}
/**
* Accessor for the deleted properties
*/
inline const std::unordered_set<std::string> &deleted_properties()
{
return deleted_props;
}
/**
* Returns a range suitable for use in a range-based for loop describing
* the properties of this node.
*/
inline property_range properties()
{
return property_range(*this);
}
/**
* Returns an iterator after the last property of this node.
*/
inline property_vector::iterator property_begin()
{
return props.begin();
}
/**
* Returns an iterator for the first property of this node.
*/
inline property_vector::iterator property_end()
{
return props.end();
}
/**
* Factory method for constructing a new node. Attempts to parse a
* node in DTS format from the input, and returns it on success. On
* any parse error, this will return 0. This should be called with the
* cursor on the open brace of the property, after the name and so on
* have been parsed.
*/
static node_ptr parse(text_input_buffer &input,
device_tree &tree,
std::string &&name,
std::unordered_set<std::string> &&label=std::unordered_set<std::string>(),
std::string &&address=std::string(),
define_map *defines=0);
/**
* Factory method for constructing a new node. Attempts to parse a
* node in DTB format from the input, and returns it on success. On
* any parse error, this will return 0. This should be called with the
* cursor on the open brace of the property, after the name and so on
* have been parsed.
*/
static node_ptr parse_dtb(input_buffer &structs, input_buffer &strings);
/**
* Construct a new special node from a name and set of properties.
*/
static node_ptr create_special_node(const std::string &name,
const std::vector<property_ptr> &props);
/**
* Returns a property corresponding to the specified key, or 0 if this
* node does not contain a property of that name.
*/
property_ptr get_property(const std::string &key);
/**
* Adds a new property to this node.
*/
inline void add_property(property_ptr &p)
{
props.push_back(p);
}
/**
* Adds a new child to this node.
*/
inline void add_child(node_ptr &&n)
{
children.push_back(std::move(n));
}
/**
* Deletes any children from this node.
*/
inline void delete_children_if(bool (*predicate)(node_ptr &))
{
children.erase(std::remove_if(children.begin(), children.end(), predicate), children.end());
}
/**
* Merges a node into this one. Any properties present in both are
* overridden, any properties present in only one are preserved.
*/
void merge_node(node_ptr &other);
/**
* Write this node to the specified output. Although nodes do not
* refer to a string table directly, their properties do. The string
* table passed as the second argument is used for the names of
* properties within this node and its children.
*/
void write(dtb::output_writer &writer, dtb::string_table &strings);
/**
* Writes the current node as DTS to the specified file. The second
* parameter is the indent level. This function will start every line
* with this number of tabs.
*/
void write_dts(FILE *file, int indent);
/**
* Recursively visit this node and then its children based on the
* callable's return value. The callable may return VISIT_BREAK
* immediately halt all recursion and end the visit, VISIT_CONTINUE to
* not recurse into the current node's children, or VISIT_RECURSE to recurse
* through children as expected. parent will be passed to the callable.
*/
visit_behavior visit(std::function<visit_behavior(node&, node*)>, node *parent);
};
/**
* Class encapsulating the entire parsed FDT. This is the top-level class,
* which parses the entire DTS representation and write out the finished
* version.
*/
class device_tree
{
public:
/**
* Type used for node paths. A node path is sequence of names and unit
* addresses.
*/
class node_path : public std::vector<std::pair<std::string,std::string>>
{
public:
/**
* Converts this to a string representation.
*/
std::string to_string() const;
};
/**
* Name that we should use for phandle nodes.
*/
enum phandle_format
{
/** linux,phandle */
LINUX,
/** phandle */
EPAPR,
/** Create both nodes. */
BOTH
};
private:
/**
* The format that we should use for writing phandles.
*/
phandle_format phandle_node_name = EPAPR;
/**
* Flag indicating that this tree is valid. This will be set to false
* on parse errors.
*/
bool valid = true;
/**
* Flag indicating that this tree requires garbage collection. This will be
* set to true if a node marked /omit-if-no-ref/ is encountered.
*/
bool garbage_collect = false;
/**
* Type used for memory reservations. A reservation is two 64-bit
* values indicating a base address and length in memory that the
* kernel should not use. The high 32 bits are ignored on 32-bit
* platforms.
*/
typedef std::pair<uint64_t, uint64_t> reservation;
/**
* The memory reserves table.
*/
std::vector<reservation> reservations;
/**
* Root node. All other nodes are children of this node.
*/
node_ptr root;
/**
* Mapping from names to nodes. Only unambiguous names are recorded,
* duplicate names are stored as (node*)-1.
*/
std::unordered_map<std::string, node*> node_names;
/**
* A map from labels to node paths. When resolving cross references,
* we look up referenced nodes in this and replace the cross reference
* with the full path to its target.
*/
std::unordered_map<std::string, node_path> node_paths;
/**
* All of the elements in `node_paths` in the order that they were
* created. This is used for emitting the `__symbols__` section, where
* we want to guarantee stable ordering.
*/
std::vector<std::pair<std::string, node_path>> ordered_node_paths;
/**
* A collection of property values that are references to other nodes.
* These should be expanded to the full path of their targets.
*/
std::vector<property_value*> cross_references;
/**
* The location of something requiring a fixup entry.
*/
struct fixup
{
/**
* The path to the node.
*/
node_path path;
/**
* The property containing the reference.
*/
property_ptr prop;
/**
* The property value that contains the reference.
*/
property_value &val;
};
/**
* A collection of property values that refer to phandles. These will
* be replaced by the value of the phandle property in their
* destination.
*/
std::vector<fixup> fixups;
/**
* The locations of all of the values that are supposed to become phandle
* references, but refer to things outside of this file.
*/
std::vector<std::reference_wrapper<fixup>> unresolved_fixups;
/**
* The names of nodes that target phandles.
*/
std::unordered_set<std::string> phandle_targets;
/**
* A collection of input buffers that we are using. These input
* buffers are the ones that own their memory, and so we must preserve
* them for the lifetime of the device tree.
*/
std::vector<std::unique_ptr<input_buffer>> buffers;
/**
* A map of used phandle values to nodes. All phandles must be unique,
* so we keep a set of ones that the user explicitly provides in the
* input to ensure that we don't reuse them.
*
* This is a map, rather than a set, because we also want to be able to
* find phandles that were provided by the user explicitly when we are
* doing checking.
*/
std::unordered_map<uint32_t, node*> used_phandles;
/**
* Paths to search for include files. This contains a set of
* nul-terminated strings, which are not owned by this class and so
* must be freed separately.
*/
std::vector<std::string> include_paths;
/**
* Dictionary of predefined macros provided on the command line.
*/
define_map defines;
/**
* The default boot CPU, specified in the device tree header.
*/
uint32_t boot_cpu = 0;
/**
* The number of empty reserve map entries to generate in the blob.
*/
uint32_t spare_reserve_map_entries = 0;
/**
* The minimum size in bytes of the blob.
*/
uint32_t minimum_blob_size = 0;
/**
* The number of bytes of padding to add to the end of the blob.
*/
uint32_t blob_padding = 0;
/**
* Is this tree a plugin?
*/
bool is_plugin = false;
/**
* Visit all of the nodes recursively, and if they have labels then add
* them to the node_paths and node_names vectors so that they can be
* used in resolving cross references. Also collects phandle
* properties that have been explicitly added.
*/
void collect_names_recursive(node_ptr &n, node_path &path);
/**
* Assign a phandle property to a single node. The next parameter
* holds the phandle to be assigned, and will be incremented upon
* assignment.
*/
property_ptr assign_phandle(node *n, uint32_t &next);
/**
* Assign phandle properties to all nodes that have been referenced and
* require one. This method will recursively visit the tree starting at
* the node that it is passed.
*/
void assign_phandles(node_ptr &n, uint32_t &next);
/**
* Calls the recursive version of this method on every root node.
*/
void collect_names();
/**
* Resolves all cross references. Any properties that refer to another
* node must have their values replaced by either the node path or
* phandle value. The phandle parameter holds the next phandle to be
* assigned, should the need arise. It will be incremented upon each
* assignment of a phandle. Garbage collection of unreferenced nodes
* marked for "delete if unreferenced" will also occur here.
*/
void resolve_cross_references(uint32_t &phandle);
/**
* Garbage collects nodes that have been marked /omit-if-no-ref/ and do not
* have any references to them from nodes that are similarly marked. This
* is a fairly expensive operation. The return value indicates whether the
* tree has been dirtied as a result of this operation, so that the caller
* may take appropriate measures to bring the device tree into a consistent
* state as needed.
*/
bool garbage_collect_marked_nodes();
/**
* Parses a dts file in the given buffer and adds the roots to the parsed
* set. The `read_header` argument indicates whether the header has
* already been read. Some dts files place the header in an include,
* rather than in the top-level file.
*/
void parse_file(text_input_buffer &input,
std::vector<node_ptr> &roots,
bool &read_header);
/**
* Template function that writes a dtb blob using the specified writer.
* The writer defines the output format (assembly, blob).
*/
template<class writer>
void write(int fd);
public:
/**
* Should we write the __symbols__ node (to allow overlays to be linked
* against this blob)?
*/
bool write_symbols = false;
/**
* Returns the node referenced by the property. If this is a tree that
* is in source form, then we have a string that we can use to index
* the cross_references array and so we can just look that up.
*/
node *referenced_node(property_value &v);
/**
* Writes this FDT as a DTB to the specified output.
*/
void write_binary(int fd);
/**
* Writes this FDT as an assembly representation of the DTB to the
* specified output. The result can then be assembled and linked into
* a program.
*/
void write_asm(int fd);
/**
* Writes the tree in DTS (source) format.
*/
void write_dts(int fd);
/**
* Default constructor. Creates a valid, but empty FDT.
*/
device_tree() {}
/**
* Constructs a device tree from the specified file name, referring to
* a file that contains a device tree blob.
*/
void parse_dtb(const std::string &fn, FILE *depfile);
/**
* Construct a fragment wrapper around node. This will assume that node's
* name may be used as the target of the fragment, and the contents are to
* be wrapped in an __overlay__ node. The fragment wrapper will be assigned
* fragnumas its fragment number, and fragment number will be incremented.
*/
node_ptr create_fragment_wrapper(node_ptr &node, int &fragnum);
/**
* Generate a root node from the node passed in. This is sensitive to
* whether we're in a plugin context or not, so that if we're in a plugin we
* can circumvent any errors that might normally arise from a non-/ root.
* fragnum will be assigned to any fragment wrapper generated as a result
* of the call, and fragnum will be incremented.
*/
node_ptr generate_root(node_ptr &node, int &fragnum);
/**
* Reassign any fragment numbers from this new node, based on the given
* delta.
*/
void reassign_fragment_numbers(node_ptr &node, int &delta);
/*
* Constructs a device tree from the specified file name, referring to
* a file that contains device tree source.
*/
void parse_dts(const std::string &fn, FILE *depfile);
/**
* Returns whether this tree is valid.
*/
inline bool is_valid()
{
return valid;
}
/**
* Mark this tree as needing garbage collection, because an /omit-if-no-ref/
* node has been encountered.
*/
void set_needs_garbage_collection()
{
garbage_collect = true;
}
/**
* Sets the format for writing phandle properties.
*/
inline void set_phandle_format(phandle_format f)
{
phandle_node_name = f;
}
/**
* Returns a pointer to the root node of this tree. No ownership
* transfer.
*/
inline const node_ptr &get_root() const
{
return root;
}
/**
* Sets the physical boot CPU.
*/
void set_boot_cpu(uint32_t cpu)
{
boot_cpu = cpu;
}
/**
* Sorts the tree. Useful for debugging device trees.
*/
void sort()
{
if (root)
{
root->sort();
}
}
/**
* Adds a path to search for include files. The argument must be a
* nul-terminated string representing the path. The device tree keeps
* a pointer to this string, but does not own it: the caller is
* responsible for freeing it if required.
*/
void add_include_path(const char *path)
{
std::string p(path);
include_paths.push_back(std::move(p));
}
/**
* Sets the number of empty reserve map entries to add.
*/
void set_empty_reserve_map_entries(uint32_t e)
{
spare_reserve_map_entries = e;
}
/**
* Sets the minimum size, in bytes, of the blob.
*/
void set_blob_minimum_size(uint32_t s)
{
minimum_blob_size = s;
}
/**
* Sets the amount of padding to add to the blob.
*/
void set_blob_padding(uint32_t p)
{
blob_padding = p;
}
/**
* Parses a predefined macro value.
*/
bool parse_define(const char *def);
};
} // namespace fdt
} // namespace dtc
#endif // !_FDT_HH_
| 29.409729 | 97 | 0.691275 | [
"vector"
] |
6c7426518723f8549322f6a34041411762b90b88 | 2,261 | cxx | C++ | PreemptiveSJF.cxx | scr1pti3/Algorithm | 2a350096cba8447fb9439fb54f79461b084be58f | [
"MIT"
] | null | null | null | PreemptiveSJF.cxx | scr1pti3/Algorithm | 2a350096cba8447fb9439fb54f79461b084be58f | [
"MIT"
] | null | null | null | PreemptiveSJF.cxx | scr1pti3/Algorithm | 2a350096cba8447fb9439fb54f79461b084be58f | [
"MIT"
] | null | null | null | #include "Process.cxx"
#include "tool.cxx"
#include <iostream>
#include <memory_resource>
#include <queue>
#include <vector>
float Process::get_wait_time() const {
return stop_time - execution_time - arrival_time;
}
int main() {
// Psuedo Processes
Process P1{"A", 12.0f, 0.0f};
Process P2{"B", 4.0f, 3.0f};
Process P3{"C", 9.0f, 5.0f};
Process P4{"D", 2.0f, 7.0f};
// Allocate a buffer on the stack
char buffer[sizeof(Process) * 3 * 2];
// assignable process alias
using process_reference = std::reference_wrapper<Process>;
// Assign pool
std::pmr::monotonic_buffer_resource pool{std::data(buffer),
std::size(buffer)};
// Task queue
std::pmr::deque<process_reference> processes{{P1, P2, P3, P4}, &pool};
decltype(processes) task_queue;
// Sort by arrival time
std::sort(processes.begin(), processes.end(), [&](Process a, Process b) {
return a.get_arrival_time() < b.get_arrival_time();
});
// Add the initial process with least arrival_time to task
task_queue.push_back(processes.front());
float time_accumulator{0.0f};
// Naive execution loop
while (1) {
++time_accumulator;
// Consume the queue
Process &active_process = task_queue.front();
active_process.execute();
// Remove from queue if the current process has finished
if (active_process.get_execution_time() >=
active_process.get_burst_time()) {
active_process.stop_time = time_accumulator;
task_queue.pop_front();
}
// Break from main loop once no more task is left
if (task_queue.empty())
break;
// Poll process arrival
auto result =
std::find_if(processes.begin(), processes.end(), [&](Process p) {
return p.get_arrival_time() == time_accumulator;
});
// Add process to task_queue if new process has arrived
if (result != std::end(processes))
task_queue.push_back(*result);
// Sort the task_queue by least burst_time
std::sort(task_queue.begin(), task_queue.end(), [&](Process a, Process b) {
return a.get_burst_time() - a.get_execution_time() <
b.get_burst_time() - b.get_execution_time();
});
}
print_process_table(processes);
return 0;
}
| 27.240964 | 79 | 0.650597 | [
"vector"
] |
6c758c31093b2d62dfad4eba08a9cd7ccc5a6499 | 2,903 | hpp | C++ | src/fwdmodel/gravmag.hpp | divad-nhok/obsidian_fork | e5bee2b706f78249564f06c88a18be086b17c895 | [
"MIT"
] | 7 | 2015-01-04T13:50:24.000Z | 2022-01-22T01:03:57.000Z | src/fwdmodel/gravmag.hpp | divad-nhok/obsidian_fork | e5bee2b706f78249564f06c88a18be086b17c895 | [
"MIT"
] | 1 | 2018-08-16T00:46:58.000Z | 2018-08-16T00:46:58.000Z | src/fwdmodel/gravmag.hpp | divad-nhok/obsidian_fork | e5bee2b706f78249564f06c88a18be086b17c895 | [
"MIT"
] | 9 | 2016-08-31T05:42:00.000Z | 2022-01-21T21:37:47.000Z | //!
//! Contains common interface used by both gravity and magnetic forward models.
//!
//! \file fwdmodel/gravmag.hpp
//! \author Darren Shen
//! \author Alistair Reid
//! \date 2014
//! \license Affero General Public License version 3 or later
//! \copyright (c) 2014, NICTA
//!
#pragma once
#include <Eigen/Dense>
#include "world/voxelise.hpp"
namespace obsidian
{
namespace fwd
{
//! Structure containing gravity and magnetic interpolation parameters.
//!
struct GravmagInterpolatorParams
{
//! The indices of each sensor.
Eigen::MatrixXi sensorIndices;
//! The weights of each sensor.
Eigen::MatrixXd sensorWeights;
//! The locations of each sensor.
Eigen::MatrixXd gridLocations;
};
//! Create a GravmagInterpolatorParams object.
//!
//! \param voxelisation The voxelised world.
//! \param locations The sensor locations.
//! \param worldSpec The world specifications.
//!
GravmagInterpolatorParams makeInterpParams(const VoxelSpec& voxelisation, const Eigen::MatrixXd& locations, const WorldSpec& worldSpec);
//! Computes the field values for either gravity or magnetic.
//!
//! \param sens The gravity or magnetic sensitivity matrix.
//! \param sensorIndices The indices of each of the sensors.
//! \param sensorWeights The weights of each of the sensors.
//! \param properties The rock property for the sensor type.
//!
Eigen::VectorXd computeField(const Eigen::MatrixXd &sens, const Eigen::MatrixXi sensorIndices, const Eigen::MatrixXd sensorWeights,
const Eigen::VectorXd &properties);
namespace detail
{
//! A small number added to denominators to prevent them from being zero.
//!
const double EPS = 1e-12;
//! Computes the sensitivity for either gravity or magnetic.
//!
//! \param xEdges, yEdges, zEdges The coordinates of the mesh grid in
//! the x, y, and z directions.
//! \param xField, yField, zField The geological field values at each of the
//! mesh grid points.
//! \param locations A Nx3 matrix containing the coordinates of each.
//! sensor observation location.
//! \param sensFunc The function to compute the sensitivity.
//!
Eigen::MatrixXd computeSensitivity(const Eigen::VectorXd &xEdges, const Eigen::VectorXd &yEdges, const Eigen::VectorXd &zEdges,
const Eigen::VectorXd &xField, const Eigen::VectorXd &yField, const Eigen::VectorXd &zField,
const Eigen::MatrixXd &locations,
double (*sensFunc)(double, double, double, double, double, double));
} // namespace detail
} // namespace fwd
} // namespace obsidian
| 38.197368 | 140 | 0.633827 | [
"mesh",
"object"
] |
6c77f5f3dd59d97d26325d84f228b9eaf23eb67e | 2,972 | cpp | C++ | tests/sandbox/SandboxApp.cpp | ChepChaf/TwoDE | f1dddc6522dd60b47c905c1441eb033de79f8a8d | [
"MIT"
] | null | null | null | tests/sandbox/SandboxApp.cpp | ChepChaf/TwoDE | f1dddc6522dd60b47c905c1441eb033de79f8a8d | [
"MIT"
] | null | null | null | tests/sandbox/SandboxApp.cpp | ChepChaf/TwoDE | f1dddc6522dd60b47c905c1441eb033de79f8a8d | [
"MIT"
] | null | null | null | #include "SandboxApp.h"
#include <iostream>
void SandboxApp::start()
{
TWODE_INFO("Hello from SandboxApp");
player = TwoDE::Locator::getLocator().getSceneManagerSystem().CreateEntity();
renderer->drawSprite(player, TwoDE::Sprite("resources/sprites/Character01.png"), TwoDE::Vector3{ 0.0f, 0.0f, 1.0f });
// 5 tiles
TwoDE::Sprite tile{ "resources/sprites/Tile01.png" };
renderer->drawSprite(tile, { { 0.f, 0.f, 0.f } });
renderer->drawSprite(tile, { { 10.f, 0.f, 0.f } });
renderer->drawSprite(tile, { { 20.f, 0.f, 0.f } });
renderer->drawSprite(tile, { { 30.f, 0.f, 0.f } });
renderer->drawSprite(tile, { { 40.f, 0.f, 0.f } });
onEvent("mouse_click", TwoDE::Event(std::function([=, this](TwoDE::Input::MouseEventInfo& params)
{
if (params.button == TwoDE::Input::MOUSE_BUTTON::LEFT_BUTTON)
{
TWODE_INFO("Mouse x position: {}", params.position.getX());
TWODE_INFO("Mouse y position: {}", params.position.getY());
dragging = true;
}
if (params.button == TwoDE::Input::MOUSE_BUTTON::RIGHT_BUTTON)
{
auto& transform = getEntityRegistry()->get<TwoDE::Transform>(player);
transform.rotate(-1);
}
}
)));
onEvent("mouse_release", TwoDE::Event(std::function([=, this](TwoDE::Input::MouseEventInfo& params)
{
if (params.button == TwoDE::Input::MOUSE_BUTTON::LEFT_BUTTON)
dragging = false;
}
)));
onEvent("mouse_scroll", TwoDE::Event(std::function([=, this](TwoDE::Input::ScrollEventInfo& params)
{
TwoDE::Vector2 scale = TwoDE::Vector2{ params.offset.getY(), params.offset.getY() };
auto& cam = getEntityRegistry()->get<TwoDE::Transform>(camera);
cam.scale(scale*TwoDE::EngineTime::deltaTime * 4.0f);
}
)));
}
void SandboxApp::update()
{
TwoDE::Application::update();
TwoDE::Vector2 right{ 1, 0 };
TwoDE::Vector2 up{ 0, 1 };
TwoDE::Input input = TwoDE::Locator::getLocator().getInputSystem();
auto& transform= getEntityRegistry()->get<TwoDE::Transform>(player);
if (input.buttonPressed(TwoDE::Input::BUTTON::RIGHT_KEY))
{
transform.translate(right * (speed * TwoDE::EngineTime::deltaTime));
}
if (input.buttonPressed(TwoDE::Input::BUTTON::LEFT_KEY))
{
transform.translate(right * (-1 * speed * TwoDE::EngineTime::deltaTime));
}
if (input.buttonPressed(TwoDE::Input::BUTTON::UP_KEY))
{
transform.translate(up * (speed * TwoDE::EngineTime::deltaTime));
}
if (input.buttonPressed(TwoDE::Input::BUTTON::DOWN_KEY))
{
transform.translate(up * (-1 * speed * TwoDE::EngineTime::deltaTime));
}
auto registry = getEntityRegistry();
if (dragging)
{
TwoDE::Vector2 position = TwoDE::Locator::getLocator().getInputSystem().getCursorPosition() - TwoDE::Vector2{ 0.5f, 0.5f };
auto& cam = registry->get<TwoDE::Transform>(camera);
cam.translate(position * -1.f * TwoDE::EngineTime::deltaTime * 200.f);
}
renderer->clear(TwoDE::Color(0.2f, 0.4f, 0.6f, 1.0f));
} | 30.958333 | 126 | 0.646703 | [
"transform"
] |
6c78f406b2ea2f8505461d0d88f07aa628c252e5 | 896 | hpp | C++ | TestFreeLicense/Renderer/RenderRoutine.hpp | darktemplar216/PhysicsTest_Chapter2 | ca1a6ed2b9b4e8f6e7bbc76225c3b7e2c2732680 | [
"Apache-2.0"
] | 4 | 2020-07-22T06:58:20.000Z | 2021-12-09T13:49:10.000Z | TestFreeLicense/Renderer/RenderRoutine.hpp | darktemplar216/PhysicsTest_Chapter2 | ca1a6ed2b9b4e8f6e7bbc76225c3b7e2c2732680 | [
"Apache-2.0"
] | null | null | null | TestFreeLicense/Renderer/RenderRoutine.hpp | darktemplar216/PhysicsTest_Chapter2 | ca1a6ed2b9b4e8f6e7bbc76225c3b7e2c2732680 | [
"Apache-2.0"
] | 3 | 2019-11-03T19:03:41.000Z | 2020-12-02T07:08:00.000Z | //
// RenderRoutine.hpp
// PhysicsTest
//
// Created by TaoweisMac on 2017/5/29.
// Copyright © 2017年 TaoweisMac. All rights reserved.
//
#ifndef RenderRoutine_hpp
#define RenderRoutine_hpp
#include <stdio.h>
#include "GMath.h"
class ShaderProgram;
class SceneMgr;
class RenderRoutine
{
friend class SceneMgr;
public:
RenderRoutine();
virtual ~RenderRoutine();
void InitParams();
void Uninit();
private:
ShaderProgram* m_cubeShaderProgram = nullptr;
SceneMgr* m_sceneMgr = nullptr;
public:
void Update(double deltaTime);
void Render();
private:
bool LightsOn(ShaderProgram* program);
bool LightsOff(ShaderProgram* program);
void GroupEntitiesGo();
void GroupRigidBodiesGo();
private:
bool isPassTransparent = false;
};
#endif /* RenderRoutine_hpp */
| 15.186441 | 54 | 0.646205 | [
"render"
] |
6c7aa181c246fee577d6d6ca6d102154a303fcf7 | 3,909 | cc | C++ | src/pass/unroll_nonconstant_extent.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 286 | 2020-06-23T06:40:44.000Z | 2022-03-30T01:27:49.000Z | src/pass/unroll_nonconstant_extent.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 10 | 2020-07-31T03:26:59.000Z | 2021-12-27T15:00:54.000Z | src/pass/unroll_nonconstant_extent.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 30 | 2020-07-17T01:04:14.000Z | 2021-12-27T14:05:19.000Z | /**
* Copyright 2019-2021 Huawei Technologies Co., Ltd
*
* 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 <tvm/ir.h>
#include <tvm/ir_visitor.h>
#include <tvm/ir_mutator.h>
#include <tvm/ir_pass.h>
#include <tvm.h>
#include "ir_pass.h"
namespace akg {
namespace ir {
namespace {
/* Visits the Stmt to find loops with non-constant extents. */
class NonConstantExtFinder : public IRVisitor {
public:
void Visit_(const Variable *ex) final {
if (find_var) {
found_var = ex;
}
}
void Visit_(const For *op) final {
if (mutate) return;
visited_loops.push_back(op);
if (!is_const(op->extent)) {
auto extent = op->extent;
find_var = true;
Visit(extent);
find_var = false;
if (found_var != nullptr) {
int item = GetLoopOfVar(found_var->name_hint);
if (item != -1) {
unrollCand = visited_loops[item];
mutate = true;
}
}
}
Visit(op->body);
visited_loops.pop_back();
}
int GetLoopOfVar(const std::string &var_hint) {
for (int i = static_cast<int>(visited_loops.size()) - 1; i >= 0; --i) {
if (visited_loops[i]->loop_var->name_hint == var_hint) {
return i;
}
}
return -1;
}
/* Auxiliary function to restart everything and start finding loops again */
void restart() {
mutate = false;
visited_loops = std::vector<const For *>();
find_var = false;
}
bool Mutate() const { return mutate; }
const For *getUnrollCandidate() const { return unrollCand; }
private:
bool find_var{false};
const Variable *found_var{nullptr};
bool mutate{false};
std::vector<const For *> visited_loops;
const For *unrollCand{nullptr};
};
/* Class that unrolls a loop which loop_var is being using as part of an extent of an internal loop */
class NonConstantExtentUnroller : public IRMutator {
public:
NonConstantExtentUnroller() : loopFinder(), replace_value(0) {}
~NonConstantExtentUnroller() override = default;
Stmt VisitAndMutate(Stmt stmt) {
loopFinder.Visit(stmt);
while (loopFinder.Mutate()) {
auto ret = Mutate(stmt);
if (ret.same_as(stmt)) break;
stmt = ret;
loopFinder.restart();
loopFinder.Visit(stmt);
}
return stmt;
}
Stmt Mutate_(const For *op, const Stmt &s) final {
if (op == loopFinder.getUnrollCandidate()) {
auto min = op->min.as<IntImm>();
auto extent = op->extent.as<IntImm>();
Stmt new_loop;
if (min && extent) {
std::vector<Stmt> inner_loops;
for (int64_t i = min->value; i < min->value + extent->value; ++i) {
replace_value = static_cast<int>(i);
auto ret = air::ir::Substitute(op->body, {{Var{op->loop_var}, make_const(Int(32), replace_value)}});
ret = Simplify_cce(ret);
inner_loops.push_back(ret);
}
new_loop = Block::make(inner_loops);
}
if (new_loop.defined()) {
return new_loop;
}
}
auto body = Mutate(op->body);
if (!body.same_as(op->body)) {
return For::make(op->loop_var, op->min, op->extent, op->for_type, op->device_api, body);
}
return s;
}
private:
NonConstantExtFinder loopFinder;
int replace_value;
};
} // namespace
Stmt UnrollNonConstantExtent(const Stmt s) { return NonConstantExtentUnroller().VisitAndMutate(s); }
} // namespace ir
} // namespace akg
| 26.412162 | 110 | 0.640061 | [
"vector"
] |
6c7ae601adf0febe1fbf95e157f46e684c20f54c | 1,693 | cpp | C++ | components/xtl/tests/tr1/smart_ptr/mt-tests/weak_ptr_mt.cpp | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/xtl/tests/tr1/smart_ptr/mt-tests/weak_ptr_mt.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/xtl/tests/tr1/smart_ptr/mt-tests/weak_ptr_mt.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #include "shared.h"
int const n = 16384;
int const k = 512; // vector size
int const m = 16; // threads
void test( stl::vector< xtl::shared_ptr<int> > & v )
{
using namespace std; // printf, rand
stl::vector< xtl::weak_ptr<int> > w( v.begin(), v.end() );
int s = 0, f = 0, r = 0;
for( int i = 0; i < n; ++i )
{
// randomly kill a pointer
v[ rand() % k ].reset();
++s;
for( int j = 0; j < k; ++j )
{
if( xtl::shared_ptr<int> px = w[ j ].lock() )
{
++s;
if( rand() & 4 )
{
continue;
}
// rebind anyway with prob. 50% for add_ref_lock() against weak_release() contention
++f;
}
else
{
++r;
}
w[ j ] = v[ rand() % k ];
}
}
printf( "\n%d locks, %d forced rebinds, %d normal rebinds.", s, f, r );
}
int main()
{
printf ("Results of weak_ptr_mt_test:\n");
using namespace std; // printf, clock_t, clock
printf("%s: %d threads, %d * %d iterations: ", title, m, n, k );
stl::vector< xtl::shared_ptr<int> > v( k );
for( int i = 0; i < k; ++i )
{
v[ i ].reset( new int( 0 ) );
}
clock_t t = clock();
pthread_t a[m];
for(int i = 0; i < m; ++i)
{
a[i] = createThread( xtl::bind( test, v ) );
}
v.resize( 0 ); // kill original copies
for(int j = 0; j < m; ++j)
{
pthread_join( a[j], 0 );
}
t = clock() - t;
printf("\n\n%.3f seconds.\n", static_cast<double>(t) / CLOCKS_PER_SEC);
return 0;
}
| 19.917647 | 100 | 0.431187 | [
"vector"
] |
6c7f73e3e62344e66390bf54491b0a9d00be6f64 | 10,087 | cpp | C++ | src/cc/Books/CormenIntroductionToAlgorithms/Graph-test.cpp | nuggetwheat/study | 1e438a995c3c6ce783af9ae6a537c349afeedbb8 | [
"MIT"
] | null | null | null | src/cc/Books/CormenIntroductionToAlgorithms/Graph-test.cpp | nuggetwheat/study | 1e438a995c3c6ce783af9ae6a537c349afeedbb8 | [
"MIT"
] | null | null | null | src/cc/Books/CormenIntroductionToAlgorithms/Graph-test.cpp | nuggetwheat/study | 1e438a995c3c6ce783af9ae6a537c349afeedbb8 | [
"MIT"
] | null | null | null |
#include <algorithm>
#include <cassert>
#include <functional>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <random>
#include <sstream>
#include <vector>
#include "Graph.hpp"
using namespace std;
namespace {
// BFS
const initializer_list<char> test_bfs_nodes {
'r', 's', 't', 'u', 'v', 'w', 'x', 'y'
};
const vector<study::Edge<char>> test_bfs_edges {
{'r', 's'}, {'r', 'v'}, {'s', 'w'}, {'t', 'u'}, {'u', 'y'},
{'w', 't'}, {'w', 'x'}, {'x', 't'}, {'x', 'u'}, {'x', 'y'}
};
const map<char,char> test_bfs_expected_parent {
{ 'r', 's' }, { 's', (char)0 }, { 't', 'w' }, { 'u', 't' }, { 'v', 'r' },
{ 'w', 's' }, { 'x', 'w' }, { 'y', 'x' }
};
// DFS
const initializer_list<char> test_dfs_nodes { 'u', 'v', 'w', 'x', 'y', 'z' };
const vector<study::Edge<char>> test_dfs_edges {
{'u', 'v'}, {'u', 'x'}, {'x', 'v'}, {'v', 'y'},
{'y', 'x'}, {'w', 'y'}, {'w', 'z'}, {'z', 'z'}
};
const map<char,char> test_dfs_expected_parent {
{ 'u', (char)0 }, { 'v', 'u' }, { 'y', 'v' }, { 'x', 'y' },
{ 'w', (char)0 }, { 'z', 'w' }
};
// TS
initializer_list<string> test_ts_nodes{"undershorts", "pants", "belt", "shirt", "tie", "jacket", "socks", "shoes", "watch" };
const vector<study::Edge<string>> test_ts_edges {
{"undershorts", "pants"},
{"undershorts", "shoes"},
{"pants", "belt"},
{"pants", "shoes"},
{"belt", "jacket"},
{"shirt", "belt"},
{"shirt", "tie"},
{"tie", "jacket"},
{"socks", "shoes"}
};
// SCC
const initializer_list<char> test_scc_nodes{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
const vector<study::Edge<char>> test_scc_edges {
{'a', 'b'},
{'b', 'c'},
{'b', 'e'},
{'b', 'f'},
{'c', 'd'},
{'c', 'g'},
{'d', 'c'},
{'d', 'h'},
{'e', 'a'},
{'e', 'f'},
{'f', 'g'},
{'g', 'f'},
{'g', 'h'},
{'h', 'h'}
};
const char *test_scc_groups[] = {
" a b e",
" c d",
" f g",
" h",
(const char *)0
};
// MST
const initializer_list<char> test_mst_nodes{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' };
const vector<study::Edge<char>> test_mst_edges {
{'a', 'b'}, {'a', 'h'}, {'b', 'c'}, {'c', 'd'}, {'d', 'e'}, {'e', 'f'},
{'f', 'c'}, {'f', 'd'}, {'f', 'g'}, {'g', 'h'}, {'g', 'i'}, {'h', 'b'},
{'h', 'i'}, {'i', 'c'}
};
const int test_mst_weight[14] = { 4, 8, 8, 7, 9, 10, 4, 14, 2, 1, 6, 11, 7, 2 };
// MST-Kruskal
const vector<study::Edge<char>> test_mst_kruskal_edges_expected {
{'a', 'b'},
{'a', 'h'},
{'c', 'd'},
{'d', 'e'},
{'f', 'c'},
{'f', 'g'},
{'g', 'h'},
{'i', 'c'}
};
// MST-Prim
const vector<study::Edge<char>> test_mst_prim_edges_expected {
{'a', 'b'},
{'b', 'c'},
{'c', 'd'},
{'c', 'f'},
{'c', 'i'},
{'d', 'e'},
{'f', 'g'},
{'g', 'h'}
};
// SSSP
const initializer_list<char> test_sssp_nodes{ 's', 't', 'x', 'y', 'z' };
// Bellman-Ford
const vector<study::Edge<char>> test_bellman_ford_edges {
{'s', 't'},
{'s', 'y'},
{'t', 'x'},
{'t', 'y'},
{'t', 'z'},
{'x', 't'},
{'y', 'x'},
{'y', 'z'},
{'z', 's'},
{'z', 'x'}
};
const int test_bellman_ford_weight[10] = { 6, 7, 5, 8, -4, -2, -3, 9, 2, 7 };
const vector<char> test_bellman_ford_parent_expected { (char)0, 'x', 'y', 's', 't' };
const vector<int> test_bellman_ford_distance_expected { 0, 2, 4, 7, -2 };
// DAG Shortest Paths
const initializer_list<char> test_dag_sp_nodes{ 'r', 's', 't', 'x', 'y', 'z' };
const vector<study::Edge<char>> test_dag_sp_edges {
{'r', 's'},
{'r', 't'},
{'s', 't'},
{'s', 'x'},
{'t', 'x'},
{'t', 'y'},
{'t', 'z'},
{'x', 'y'},
{'x', 'z'},
{'y', 'z'}
};
const int test_dag_sp_weight[10] = { 5, 3, 2, 6, 7, 4, 2, -1, 1, -2 };
const vector<char> test_dag_sp_parent_expected { (char)0, (char)0, 's', 's', 'x', 'y' };
const vector<int> test_dag_sp_distance_expected { numeric_limits<int>::max(), 0, 2, 6, 5, 3 };
// All Pairs Shortest Paths
constexpr const int INF = numeric_limits<int>::max();
int apsp_weight[5][5] = {
{ 0, 3, 8, INF, -4 },
{ INF, 0, INF, 1, 7 },
{ INF, 4, 0, INF, INF },
{ 2, INF, -5, 0, INF },
{ INF, INF, INF, 6, 0 }
};
const int apsp_expected[5][5] = {
{0, 1, -3, 2, -4},
{3, 0, -4, 1, -1},
{7, 4, 0, 5, 3},
{2, -1, -5, 0, -2},
{8, 5, 1, 6, 0}
};
}
namespace study {
void test_Graph() {
// BFS
{
Graph<char> g { EdgeType::UNDIRECTED, test_bfs_nodes };
g.add_edges(test_bfs_edges);
map<char, char> parent;
map<char, int> distance;
bfs(g, 's', parent, distance);
stringstream ss;
for (auto &elem : distance)
ss << elem.first << "=" << elem.second << " ";
assert(ss.str() == "r=1 s=0 t=2 u=3 v=2 w=1 x=2 y=3 ");
assert(parent == test_bfs_expected_parent);
}
// DFS
{
Graph<char> g { EdgeType::DIRECTED, test_dfs_nodes };
g.add_edges(test_dfs_edges);
map<char, char> parent;
map<char, pair<int,int>> time;
dfs(g, parent, time);
stringstream ss;
for (auto &elem : time)
ss << elem.first << "=" << elem.second.first << "/" << elem.second.second << " ";
assert(ss.str() == "u=1/8 v=2/7 w=9/12 x=4/5 y=3/6 z=10/11 ");
assert(parent == test_dfs_expected_parent);
}
// TS
{
Graph<string> g { EdgeType::DIRECTED, test_ts_nodes };
g.add_edges(test_ts_edges);
list<string> order;
topological_sort(g, order);
stringstream ss;
for (auto elem : order)
ss << " -> " << elem;
assert(ss.str() == " -> watch -> undershorts -> socks -> shirt -> tie -> pants -> shoes -> belt -> jacket");
}
// SCC
{
Graph<char> g { EdgeType::DIRECTED, test_scc_nodes };
g.add_edges(test_scc_edges);
vector<set<char>> components;
strongly_connected_components(g, components);
for (size_t i=0; i<components.size(); ++i) {
stringstream ss;
for (const auto elem : components[i])
ss << " " << elem;
assert(ss.str() == test_scc_groups[i]);
}
}
// MST-Kruskal
{
Graph<char> g { EdgeType::UNDIRECTED, test_mst_nodes };
Graph<char> mst;
g.add_edges(test_mst_edges);
map<Edge<char>, int> weight;
for (size_t i=0; i<14; ++i) {
Edge<char> edge = test_mst_edges[i];
weight[edge] = test_mst_weight[i];
edge.reverse();
weight[edge] = test_mst_weight[i];
}
mst_kruskal(g, weight, mst);
auto edges = mst.edges();
sort(edges.begin(), edges.end());
assert(edges == test_mst_kruskal_edges_expected);
}
// MST-Prim
{
Graph<char> g { EdgeType::UNDIRECTED, test_mst_nodes };
Graph<char> mst;
g.add_edges(test_mst_edges);
map<Edge<char>, int> weight;
for (size_t i=0; i<14; ++i) {
Edge<char> edge = test_mst_edges[i];
weight[edge] = test_mst_weight[i];
edge.reverse();
weight[edge] = test_mst_weight[i];
}
mst_prim(g, 'a', weight, mst);
auto edges = mst.edges();
sort(edges.begin(), edges.end());
assert(edges == test_mst_prim_edges_expected);
}
// Bellman-Ford
{
Graph<char> g { EdgeType::DIRECTED, test_sssp_nodes };
std::map<char, char> parent;
std::map<char, int> distance;
g.add_edges(test_bellman_ford_edges);
map<Edge<char>, int> weight;
for (size_t i=0; i<10; ++i)
weight[test_bellman_ford_edges[i]] = test_bellman_ford_weight[i];
auto valid = bellman_ford(g, 's', weight, parent, distance);
assert(valid);
assert (std::search(parent.begin(), parent.end(),
test_bellman_ford_parent_expected.begin(),
test_bellman_ford_parent_expected.end(),
[](std::pair<char, char> lhs, char rhs) {
return lhs.second == rhs;
}) == parent.begin());
assert (std::search(distance.begin(), distance.end(),
test_bellman_ford_distance_expected.begin(),
test_bellman_ford_distance_expected.end(),
[](std::pair<char, int> lhs, int rhs) {
return lhs.second == rhs;
}) == distance.begin());
}
// DAG Shortest Paths
{
Graph<char> g { EdgeType::DIRECTED, test_dag_sp_nodes };
std::map<char, char> parent;
std::map<char, int> distance;
g.add_edges(test_dag_sp_edges);
map<Edge<char>, int> weight;
for (size_t i=0; i<10; ++i)
weight[test_dag_sp_edges[i]] = test_dag_sp_weight[i];
dag_shortest_paths(g, 's', weight, parent, distance);
assert (std::search(parent.begin(), parent.end(),
test_dag_sp_parent_expected.begin(),
test_dag_sp_parent_expected.end(),
[](std::pair<char, char> lhs, char rhs) {
return lhs.second == rhs;
}) == parent.begin());
assert (std::search(distance.begin(), distance.end(),
test_dag_sp_distance_expected.begin(),
test_dag_sp_distance_expected.end(),
[](std::pair<char, int> lhs, int rhs) {
return lhs.second == rhs;
}) == distance.begin());
}
// All Pairs Shortest Paths (V^4)
{
int sp[5][5];
slow_all_pairs_shortest_paths<5>(apsp_weight, sp);
for (size_t i=0; i<5; ++i)
for (size_t j=0; j<5; ++j)
assert(sp[i][j] == apsp_expected[i][j]);
}
// All Pairs Shortest Paths (V^3logV)
{
int sp[5][5];
faster_all_pairs_shortest_paths<5>(apsp_weight, sp);
for (size_t i=0; i<5; ++i)
for (size_t j=0; j<5; ++j)
assert(sp[i][j] == apsp_expected[i][j]);
}
}
}
| 30.38253 | 127 | 0.490037 | [
"vector"
] |
6c81d51615651742504f594936fb847da8592d8f | 20,795 | cpp | C++ | Engine/Plugins/Media/PixelStreaming/Source/PixelStreaming/Private/Streamer.cpp | denfrost/UE5MainStreaming | b16e03a9bf01987d390f066f500bcff4b75ea790 | [
"MIT"
] | 2 | 2021-11-26T13:33:32.000Z | 2021-12-31T08:52:21.000Z | Engine/Plugins/Media/PixelStreaming/Source/PixelStreaming/Private/Streamer.cpp | denfrost/UE5MainStreaming | b16e03a9bf01987d390f066f500bcff4b75ea790 | [
"MIT"
] | null | null | null | Engine/Plugins/Media/PixelStreaming/Source/PixelStreaming/Private/Streamer.cpp | denfrost/UE5MainStreaming | b16e03a9bf01987d390f066f500bcff4b75ea790 | [
"MIT"
] | 1 | 2021-10-11T10:05:52.000Z | 2021-10-11T10:05:52.000Z | // Copyright Epic Games, Inc. All Rights Reserved.
#include "Streamer.h"
#include "AudioCapturer.h"
#include "VideoCapturer.h"
#include "PlayerSession.h"
#include "VideoEncoderFactory.h"
#include "PixelStreamerDelegates.h"
#include "PixelStreamingEncoderFactory.h"
#include "PixelStreamingSettings.h"
#include "WebRTCLogging.h"
#include "WebSocketsModule.h"
#include "PixelStreamingAudioDeviceModule.h"
#include "PixelStreamingAudioSink.h"
#include "WebRtcObservers.h"
#include "PixelStreamingVideoSources.h"
DEFINE_LOG_CATEGORY(PixelStreamer);
bool FStreamer::CheckPlatformCompatibility()
{
return AVEncoder::FVideoEncoderFactory::Get().HasEncoderForCodec(AVEncoder::ECodecType::H264);
}
FStreamer::FStreamer(const FString& InSignallingServerUrl, const FString& InStreamerId)
: SignallingServerUrl(InSignallingServerUrl)
, StreamerId(InStreamerId)
, WebRtcSignallingThread(MakeUnique<rtc::Thread>(rtc::SocketServer::CreateDefault()))
, SignallingServerConnection(MakeUnique<FSignallingServerConnection>(*this, InStreamerId))
, PlayerSessions(WebRtcSignallingThread.Get())
{
RedirectWebRtcLogsToUnreal(rtc::LoggingSeverity::LS_VERBOSE);
FModuleManager::LoadModuleChecked<IModuleInterface>(TEXT("AVEncoder"));
// required for communication with Signalling Server and must be called in the game thread, while it's used in signalling thread
FModuleManager::LoadModuleChecked<FWebSocketsModule>("WebSockets");
StartWebRtcSignallingThread();
ConnectToSignallingServer();
this->PlayerSessions.OnQualityControllerChanged.AddRaw(this, &FStreamer::OnQualityControllerChanged);
this->PlayerSessions.OnPlayerDeleted.AddRaw(this, &FStreamer::PostPlayerDeleted);
}
FStreamer::~FStreamer()
{
DeleteAllPlayerSessions();
PeerConnectionFactory = nullptr;
WebRtcSignallingThread->Stop();
rtc::CleanupSSL();
}
void FStreamer::StartWebRtcSignallingThread()
{
// initialisation of WebRTC stuff and things that depends on it should happen in WebRTC signalling thread
// Create our own WebRTC thread for signalling
WebRtcSignallingThread->SetName("WebRtcSignallingThread", nullptr);
WebRtcSignallingThread->Start();
rtc::InitializeSSL();
PeerConnectionConfig = {};
std::unique_ptr<FPixelStreamingVideoEncoderFactory> videoEncoderFactory = std::make_unique<FPixelStreamingVideoEncoderFactory>(this);
this->VideoEncoderFactory = videoEncoderFactory.get();
bool bUseLegacyAudioDeviceModule = PixelStreamingSettings::CVarPixelStreamingWebRTCUseLegacyAudioDevice.GetValueOnAnyThread();
rtc::scoped_refptr<webrtc::AudioDeviceModule> AudioDeviceModule;
if(bUseLegacyAudioDeviceModule)
{
AudioDeviceModule = new rtc::RefCountedObject<FAudioCapturer>();
}
else
{
AudioDeviceModule = new rtc::RefCountedObject<FPixelStreamingAudioDeviceModule>();
}
PeerConnectionFactory = webrtc::CreatePeerConnectionFactory(
nullptr, // network_thread
nullptr, // worker_thread
WebRtcSignallingThread.Get(), // signal_thread
AudioDeviceModule, // audio device manager
webrtc::CreateAudioEncoderFactory<webrtc::AudioEncoderOpus>(),
webrtc::CreateAudioDecoderFactory<webrtc::AudioDecoderOpus>(),
std::move(videoEncoderFactory),
std::make_unique<webrtc::InternalDecoderFactory>(),
nullptr, // audio_mixer
this->SetupAudioProcessingModule()); // audio_processing
check(PeerConnectionFactory);
}
webrtc::AudioProcessing* FStreamer::SetupAudioProcessingModule()
{
webrtc::AudioProcessing* AudioProcessingModule = webrtc::AudioProcessingBuilder().Create();
webrtc::AudioProcessing::Config Config;
// Enabled multi channel audio capture/render
Config.pipeline.multi_channel_capture = true;
Config.pipeline.multi_channel_render = true;
Config.pipeline.maximum_internal_processing_rate = 48000;
// Turn off all other audio processing effects in UE's WebRTC. We want to stream audio from UE as pure as possible.
Config.pre_amplifier.enabled = false;
Config.high_pass_filter.enabled = false;
Config.echo_canceller.enabled = false;
Config.noise_suppression.enabled = false;
Config.transient_suppression.enabled = false;
Config.voice_detection.enabled = false;
Config.gain_controller1.enabled = false;
Config.gain_controller2.enabled = false;
Config.residual_echo_detector.enabled = false;
Config.level_estimation.enabled = false;
// Apply the config.
AudioProcessingModule->ApplyConfig(Config);
return AudioProcessingModule;
}
void FStreamer::ConnectToSignallingServer()
{
this->SignallingServerConnection->Connect(SignallingServerUrl);
}
void FStreamer::OnFrameBufferReady(const FTexture2DRHIRef& FrameBuffer)
{
if (bStreamingStarted)
{
this->VideoSources.OnFrameReady(FrameBuffer);
}
}
void FStreamer::OnQualityControllerChanged(FPlayerId PlayerId)
{
this->VideoSources.SetQualityController(PlayerId);
}
void FStreamer::PostPlayerDeleted(FPlayerId PlayerId)
{
this->VideoSources.DeleteVideoSource(PlayerId);
}
void FStreamer::OnConfig(const webrtc::PeerConnectionInterface::RTCConfiguration& Config)
{
this->PeerConnectionConfig = Config;
}
void FStreamer::OnDataChannelOpen(FPlayerId PlayerId, webrtc::DataChannelInterface* DataChannel)
{
if(DataChannel)
{
// When data channel is open, try to send cached freeze frame (if we have one)
this->SendCachedFreezeFrameTo(PlayerId);
}
}
void FStreamer::OnOffer(FPlayerId PlayerId, TUniquePtr<webrtc::SessionDescriptionInterface> Sdp)
{
webrtc::PeerConnectionInterface* PeerConnection = this->PlayerSessions.CreatePlayerSession(PlayerId,
this->PeerConnectionFactory,
this->PeerConnectionConfig,
this->SignallingServerConnection.Get());
if(PeerConnection != nullptr)
{
// Bind to the OnDataChannelOpen delegate (we use this as the earliest time peer is ready for freeze frame)
FPixelStreamingDataChannelObserver* DataChannelObserver = this->PlayerSessions.GetDataChannelObserver(PlayerId);
check(DataChannelObserver);
DataChannelObserver->OnDataChannelOpen.AddRaw(this, &FStreamer::OnDataChannelOpen );
this->AddStreams(PlayerId, PeerConnection);
this->HandleOffer(PlayerId, PeerConnection, MoveTemp(Sdp));
this->ForceKeyFrame();
}
}
void FStreamer::HandleOffer(FPlayerId PlayerId, webrtc::PeerConnectionInterface* PeerConnection, TUniquePtr<webrtc::SessionDescriptionInterface> Sdp)
{
// below is async execution (with error handling) of:
// PeerConnection.SetRemoteDescription(SDP);
// Answer = PeerConnection.CreateAnswer();
// PeerConnection.SetLocalDescription(Answer);
// SignallingServerConnection.SendAnswer(Answer);
FSetSessionDescriptionObserver* SetLocalDescriptionObserver = FSetSessionDescriptionObserver::Create
(
[this, PlayerId, PeerConnection]() // on success
{
this->GetSignallingServerConnection()->SendAnswer(PlayerId, *PeerConnection->local_description());
this->SetStreamingStarted(true);
},
[this, PlayerId](const FString& Error) // on failure
{
UE_LOG(PixelStreamer, Error, TEXT("Failed to set local description: %s"), *Error);
this->PlayerSessions.DisconnectPlayer(PlayerId, Error);
}
);
auto OnCreateAnswerSuccess = [this, PlayerId, PeerConnection, SetLocalDescriptionObserver](webrtc::SessionDescriptionInterface* SDP)
{
// Note from Luke about WebRTC: the sink of video capturer will be added as a direct result
// of `PeerConnection->SetLocalDescription()` call but video encoder will be created later on
// when the first frame is pushed into the WebRTC pipeline (by the capturer calling `OnFrame`).
// Note from Luke about Pixel Streaming: Internally we associate `FPlayerId` with each `FVideoCapturer` and
// pass an "initialisation frame" that contains `FPlayerId` through `OnFrame` to the encoder.
// This initialization frame establishes the correct association between the player and `FPixelStreamingVideoEncoder`.
// The reason we want this association between encoder<->peer is is so that the quality controlling peer
// can change encoder bitrate etc, while the other peers cannot.
PeerConnection->SetLocalDescription(SetLocalDescriptionObserver, SDP);
// Once local description has been set we can start setting some encoding information for the video stream rtp sender
std::vector<rtc::scoped_refptr<webrtc::RtpSenderInterface>> SendersArr = PeerConnection->GetSenders();
for(rtc::scoped_refptr<webrtc::RtpSenderInterface> Sender : SendersArr)
{
cricket::MediaType MediaType = Sender->media_type();
if(MediaType == cricket::MediaType::MEDIA_TYPE_VIDEO)
{
webrtc::RtpParameters ExistingParams = Sender->GetParameters();
// Set the start min/max bitrate and max framerate for the codec.
for (webrtc::RtpEncodingParameters& codec_params : ExistingParams.encodings)
{
codec_params.max_bitrate_bps = PixelStreamingSettings::CVarPixelStreamingWebRTCMaxBitrate.GetValueOnAnyThread();
codec_params.min_bitrate_bps = PixelStreamingSettings::CVarPixelStreamingWebRTCMinBitrate.GetValueOnAnyThread();
codec_params.max_framerate = PixelStreamingSettings::CVarPixelStreamingWebRTCMaxFps.GetValueOnAnyThread();
}
// Set the degradation preference based on our CVar for it.
webrtc::DegradationPreference DegradationPref = PixelStreamingSettings::GetDegradationPreference();
ExistingParams.degradation_preference = DegradationPref;
webrtc::RTCError Err = Sender->SetParameters(ExistingParams);
if(!Err.ok())
{
const char* ErrMsg = Err.message();
FString ErrorStr(ErrMsg);
UE_LOG(PixelStreamer, Error, TEXT("Failed to set RTP Sender params: %s"), *ErrorStr);
}
}
}
// Note: if desired, manually limiting total bitrate for a peer is possible in PeerConnection::SetBitrate(const BitrateSettings& bitrate)
};
FCreateSessionDescriptionObserver* CreateAnswerObserver = FCreateSessionDescriptionObserver::Create
(
MoveTemp(OnCreateAnswerSuccess),
[this, PlayerId](const FString& Error) // on failure
{
UE_LOG(PixelStreamer, Error, TEXT("Failed to create answer: %s"), *Error);
this->PlayerSessions.DisconnectPlayer(PlayerId, Error);
}
);
auto OnSetRemoteDescriptionSuccess = [this, PeerConnection, CreateAnswerObserver]()
{
// Note: these offer to receive at superseded now we are use transceivers to setup our peer connection media
int offer_to_receive_video = 0;
int offer_to_receive_audio = PixelStreamingSettings::CVarPixelStreamingWebRTCDisableReceiveAudio.GetValueOnAnyThread() ? 0 : 1;
bool voice_activity_detection = false;
bool ice_restart = true;
bool use_rtp_mux = true;
webrtc::PeerConnectionInterface::RTCOfferAnswerOptions AnswerOption{
offer_to_receive_video,
offer_to_receive_audio,
voice_activity_detection,
ice_restart,
use_rtp_mux
};
// modify audio transceiver direction based on CVars just before creating answer
this->ModifyAudioTransceiverDirection(PeerConnection);
PeerConnection->CreateAnswer(CreateAnswerObserver, AnswerOption);
};
FSetSessionDescriptionObserver* SetRemoteDescriptionObserver = FSetSessionDescriptionObserver::Create(
MoveTemp(OnSetRemoteDescriptionSuccess),
[this, PlayerId](const FString& Error) // on failure
{
UE_LOG(PixelStreamer, Error, TEXT("Failed to set remote description: %s"), *Error);
this->PlayerSessions.DisconnectPlayer(PlayerId, Error);
}
);
PeerConnection->SetRemoteDescription(SetRemoteDescriptionObserver, Sdp.Release());
}
void FStreamer::ModifyAudioTransceiverDirection(webrtc::PeerConnectionInterface* PeerConnection)
{
//virtual std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>GetTransceivers()
std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> Transceivers = PeerConnection->GetTransceivers();
for(auto& Transceiver : Transceivers)
{
if(Transceiver->media_type() == cricket::MediaType::MEDIA_TYPE_AUDIO)
{
bool bTransmitUEAudio = !PixelStreamingSettings::CVarPixelStreamingWebRTCDisableTransmitAudio.GetValueOnAnyThread();
bool bReceiveBrowserAudio = !PixelStreamingSettings::CVarPixelStreamingWebRTCDisableReceiveAudio.GetValueOnAnyThread();
// Determine the direction of the transceiver
webrtc::RtpTransceiverDirection AudioTransceiverDirection;
if(bTransmitUEAudio && bReceiveBrowserAudio)
{
AudioTransceiverDirection = webrtc::RtpTransceiverDirection::kSendRecv;
}
else if(bTransmitUEAudio)
{
AudioTransceiverDirection = webrtc::RtpTransceiverDirection::kSendOnly;
}
else if(bReceiveBrowserAudio)
{
AudioTransceiverDirection = webrtc::RtpTransceiverDirection::kRecvOnly;
}
else
{
AudioTransceiverDirection = webrtc::RtpTransceiverDirection::kInactive;
}
Transceiver->SetDirection(AudioTransceiverDirection);
}
}
}
void FStreamer::OnRemoteIceCandidate(FPlayerId PlayerId, const std::string& SdpMid, int SdpMLineIndex, const std::string& Sdp)
{
this->PlayerSessions.OnRemoteIceCandidate(PlayerId, SdpMid, SdpMLineIndex, Sdp);
}
void FStreamer::OnPlayerDisconnected(FPlayerId PlayerId)
{
UE_LOG(PixelStreamer, Log, TEXT("player %s disconnected"), *PlayerId);
DeletePlayerSession(PlayerId);
}
void FStreamer::OnSignallingServerDisconnected()
{
DeleteAllPlayerSessions();
// Call disconnect here makes sure any other websocket callbacks etc are cleared
this->SignallingServerConnection->Disconnect();
ConnectToSignallingServer();
}
void FStreamer::SendLatestQPAllPlayers() const
{
if(this->VideoEncoderFactory)
{
double LatestQP = this->VideoEncoderFactory->GetLatestQP();
this->PlayerSessions.SendLatestQPAllPlayers( (int)LatestQP );
}
}
int FStreamer::GetNumPlayers() const
{
return this->PlayerSessions.GetNumPlayers();
}
void FStreamer::ForceKeyFrame()
{
if(this->VideoEncoderFactory)
{
this->VideoEncoderFactory->ForceKeyFrame();
}
else
{
UE_LOG(PixelStreamer, Log, TEXT("Cannot force a key frame - video encoder factory is nullptr."));
}
}
void FStreamer::SetQualityController(FPlayerId PlayerId)
{
this->PlayerSessions.SetQualityController(PlayerId);
}
bool FStreamer::IsQualityController(FPlayerId PlayerId) const
{
return this->PlayerSessions.IsQualityController(PlayerId);
}
IPixelStreamingAudioSink* FStreamer::GetAudioSink(FPlayerId PlayerId) const
{
return this->PlayerSessions.GetAudioSink(PlayerId);
}
IPixelStreamingAudioSink* FStreamer::GetUnlistenedAudioSink() const
{
return this->PlayerSessions.GetUnlistenedAudioSink();
}
bool FStreamer::SendMessage(FPlayerId PlayerId, PixelStreamingProtocol::EToPlayerMsg Type, const FString& Descriptor) const
{
return this->PlayerSessions.SendMessage(PlayerId, Type, Descriptor);
}
void FStreamer::SendLatestQP(FPlayerId PlayerId, int LatestQP) const
{
this->PlayerSessions.SendLatestQP(PlayerId, LatestQP);
}
void FStreamer::DeleteAllPlayerSessions()
{
this->PlayerSessions.DeleteAllPlayerSessions();
this->bStreamingStarted = false;
}
void FStreamer::DeletePlayerSession(FPlayerId PlayerId)
{
int NumRemainingPlayers = this->PlayerSessions.DeletePlayerSession(PlayerId);
if(NumRemainingPlayers == 0)
{
this->bStreamingStarted = false;
}
}
void FStreamer::AddStreams(FPlayerId PlayerId, webrtc::PeerConnectionInterface* PeerConnection)
{
check(PeerConnection);
bool bSyncVideoAndAudio = !PixelStreamingSettings::CVarPixelStreamingWebRTCDisableAudioSync.GetValueOnAnyThread();
FString const AudioStreamId = bSyncVideoAndAudio ? TEXT("pixelstreaming_av_stream_id") : TEXT("pixelstreaming_audio_stream_id");
FString const VideoStreamId = bSyncVideoAndAudio ? TEXT("pixelstreaming_av_stream_id") : TEXT("pixelstreaming_video_stream_id");
FString const AudioTrackLabel = TEXT("pixelstreaming_audio_track_label");
FString const VideoTrackLabel = TEXT("pixelstreaming_video_track_label");
if (!PeerConnection->GetSenders().empty())
{
return; // Already added tracks
}
// Use PeerConnection's transceiver API to add create audio/video tracks will correct directionality.
// These tracks are only thin wrappers around the underlying sources (the sources are shared among all peer's tracks).
// As per the WebRTC source: "The same source can be used by multiple VideoTracks."
this->SetupVideoTrack(PlayerId, PeerConnection, VideoStreamId, VideoTrackLabel);
this->SetupAudioTrack(PeerConnection, AudioStreamId, AudioTrackLabel);
}
void FStreamer::SetupVideoTrack(FPlayerId PlayerId, webrtc::PeerConnectionInterface* PeerConnection, FString const VideoStreamId, FString const VideoTrackLabel)
{
// Create a video source for this player
webrtc::VideoTrackSourceInterface* VideoSource = this->VideoSources.CreateVideoSource(PlayerId);
// Create video track
rtc::scoped_refptr<webrtc::VideoTrackInterface> VideoTrack = PeerConnectionFactory->CreateVideoTrack(TCHAR_TO_UTF8(*VideoTrackLabel), VideoSource);
// Add the track
webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpSenderInterface>> Result = PeerConnection->AddTrack(VideoTrack, { TCHAR_TO_UTF8(*VideoStreamId) });
if (Result.ok())
{
// Set some content hints based on degradation prefs, WebRTC uses these internally.
webrtc::DegradationPreference DegradationPref = PixelStreamingSettings::GetDegradationPreference();
switch (DegradationPref)
{
case webrtc::DegradationPreference::MAINTAIN_FRAMERATE:
VideoTrack->set_content_hint(webrtc::VideoTrackInterface::ContentHint::kFluid);
break;
case webrtc::DegradationPreference::MAINTAIN_RESOLUTION:
VideoTrack->set_content_hint(webrtc::VideoTrackInterface::ContentHint::kDetailed);
break;
default:
break;
}
}
else
{
UE_LOG(PixelStreamer, Error, TEXT("Failed to add Video transceiver to PeerConnection. Msg=%s"), TCHAR_TO_UTF8(Result.error().message()));
}
}
void FStreamer::SetupAudioTrack(webrtc::PeerConnectionInterface* PeerConnection, FString const AudioStreamId, FString const AudioTrackLabel)
{
bool bTransmitUEAudio = !PixelStreamingSettings::CVarPixelStreamingWebRTCDisableTransmitAudio.GetValueOnAnyThread();
bool bReceiveBrowserAudio = !PixelStreamingSettings::CVarPixelStreamingWebRTCDisableReceiveAudio.GetValueOnAnyThread();
// Create one and only one audio source for Pixel Streaming.
if (!AudioSource && bTransmitUEAudio)
{
// Setup audio source options, we turn off many of the "nice" audio settings that
// would traditionally be used in a conference call because the audio source we are
// transmitting is UE application audio (not some unknown microphone).
this->AudioSourceOptions.echo_cancellation = false;
this->AudioSourceOptions.auto_gain_control = false;
this->AudioSourceOptions.noise_suppression = false;
this->AudioSourceOptions.highpass_filter = false;
this->AudioSourceOptions.stereo_swapping = false;
this->AudioSourceOptions.audio_jitter_buffer_max_packets = 1000;
this->AudioSourceOptions.audio_jitter_buffer_fast_accelerate = false;
this->AudioSourceOptions.audio_jitter_buffer_min_delay_ms = 0;
this->AudioSourceOptions.audio_jitter_buffer_enable_rtx_handling = false;
this->AudioSourceOptions.typing_detection = false;
this->AudioSourceOptions.experimental_agc = false;
this->AudioSourceOptions.experimental_ns = false;
this->AudioSourceOptions.residual_echo_detector = false;
// Create audio source
AudioSource = PeerConnectionFactory->CreateAudioSource(this->AudioSourceOptions);
}
// Add the audio track to the audio transceiver's sender if we are transmitting audio
if(bTransmitUEAudio)
{
rtc::scoped_refptr<webrtc::AudioTrackInterface> AudioTrack = PeerConnectionFactory->CreateAudioTrack(TCHAR_TO_UTF8(*AudioTrackLabel), AudioSource);
// Add the track
webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpSenderInterface>> Result = PeerConnection->AddTrack(AudioTrack, { TCHAR_TO_UTF8(*AudioStreamId) });
if(!Result.ok())
{
UE_LOG(PixelStreamer, Error, TEXT("Failed to add audio track to PeerConnection. Msg=%s"), TCHAR_TO_UTF8(Result.error().message()));
}
}
}
void FStreamer::SendPlayerMessage(PixelStreamingProtocol::EToPlayerMsg Type, const FString& Descriptor)
{
this->PlayerSessions.SendMessageAll(Type, Descriptor);
}
void FStreamer::SendFreezeFrame(const TArray64<uint8>& JpegBytes)
{
if(!this->bStreamingStarted)
{
return;
}
this->PlayerSessions.SendFreezeFrame(JpegBytes);
CachedJpegBytes = JpegBytes;
}
void FStreamer::SendCachedFreezeFrameTo(FPlayerId PlayerId) const
{
if (this->CachedJpegBytes.Num() > 0)
{
this->PlayerSessions.SendFreezeFrameTo(PlayerId, this->CachedJpegBytes);
}
}
void FStreamer::SendFreezeFrameTo(FPlayerId PlayerId, const TArray64<uint8>& JpegBytes) const
{
this->PlayerSessions.SendFreezeFrameTo(PlayerId, JpegBytes);
}
void FStreamer::SendUnfreezeFrame()
{
// Force a keyframe so when stream unfreezes if player has never received a h.264 frame before they can still connect.
this->ForceKeyFrame();
this->PlayerSessions.SendUnfreezeFrame();
CachedJpegBytes.Empty();
}
| 36.610915 | 160 | 0.788651 | [
"render",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.