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
0bfc580bee5812b143ee78ab03d0480bdd40361a
4,155
cxx
C++
smtk/extension/qt/MembershipBadge.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
40
2015-02-21T19:55:54.000Z
2022-01-06T13:13:05.000Z
smtk/extension/qt/MembershipBadge.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
127
2015-01-15T20:55:45.000Z
2021-08-19T17:34:15.000Z
smtk/extension/qt/MembershipBadge.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
27
2015-03-04T14:17:51.000Z
2021-12-23T01:05:42.000Z
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/extension/qt/MembershipBadge.h" #include "smtk/extension/qt/qtDescriptivePhraseModel.h" #include "smtk/attribute/Attribute.h" #include "smtk/attribute/DoubleItem.h" #include "smtk/attribute/IntItem.h" #include "smtk/attribute/StringItem.h" #include "smtk/common/Color.h" #include "smtk/io/Logger.h" #include "smtk/model/Entity.h" #include "smtk/model/EntityRef.h" #include "smtk/model/FloatData.h" #include "smtk/operation/Manager.h" #include "smtk/operation/Operation.h" #include "smtk/operation/operators/SetProperty.h" #include "smtk/view/Badge.h" #include "smtk/view/BadgeSet.h" #include "smtk/view/DescriptivePhrase.h" #include "smtk/view/Manager.h" #include "smtk/view/icons/selected_svg.h" #include "smtk/view/icons/unselected_svg.h" #include <regex> namespace smtk { namespace extension { namespace qt { MembershipBadge::MembershipBadge() : m_iconOn(selected_svg) , m_iconOff(unselected_svg) { } MembershipBadge::MembershipBadge( smtk::view::BadgeSet& parent, const smtk::view::Configuration::Component& config) : m_iconOn(selected_svg) , m_iconOff(unselected_svg) , m_parent(&parent) { config.attributeAsBool("SingleSelect", m_singleSelect); if (config.attribute("MemberIcon")) { config.attribute("MemberIcon", m_iconOn); } if (config.attribute("NonMemberIcon")) { config.attribute("NonMemberIcon", m_iconOff); } } MembershipBadge::~MembershipBadge() = default; std::string MembershipBadge::icon( const DescriptivePhrase* phrase, const std::array<float, 4>& background) const { auto persistentObj = phrase->relatedObject(); auto valIt = m_members.find(persistentObj); int member = 0; if (valIt != m_members.end()) { member = valIt->second; } float lightness = smtk::common::Color::floatRGBToLightness(background.data()); const std::string& icon = member ? m_iconOn : m_iconOff; return lightness >= 0.5 ? icon : std::regex_replace(icon, std::regex("black"), "white"); } bool MembershipBadge::action( const smtk::view::DescriptivePhrase* phrase, const smtk::view::BadgeAction& act) { using smtk::view::DescriptivePhrase; if (!dynamic_cast<const smtk::view::BadgeActionToggle*>(&act)) { return false; // we only support toggling. } auto persistentObj = phrase->relatedObject(); if (phrase->content() == nullptr || !persistentObj) { smtkWarningMacro( smtk::io::Logger::instance(), "Can not access content or object for membership!"); return false; } auto valIt = m_members.find(persistentObj); int newValue = (valIt == m_members.end()) ? 1 : !valIt->second; if (m_singleSelect) { // Selecting a new item when only 1 is allowed should reset all other membership // and ignore any multiple-selection passed via the action. if (newValue && !m_members.empty()) { m_members.clear(); } m_members[persistentObj] = newValue; emit membershipChange(newValue); return true; } bool didVisit = false; act.visitRelatedPhrases([this, newValue, &didVisit](const DescriptivePhrase* related) -> bool { auto obj = related->relatedObject(); if (obj) { auto it = m_members.find(obj); if (it == m_members.end()) { if (newValue) { m_members[obj] = newValue; didVisit = true; } } else { if (it->second != newValue) { it->second = newValue; didVisit = true; } } } return false; // do not terminate early }); if (!didVisit) { m_members[persistentObj] = newValue; } emit membershipChange(newValue); return true; } } // namespace qt } // namespace extension } // namespace smtk
26.806452
97
0.658965
[ "object", "model" ]
040286dec1cd5fe7e8258cdec97bc68e31ea3920
2,174
cc
C++
Core/base/string_utils.cc
InfiniteSynthesis/starlight
478d5a78a8277b83ad93b56b6ab1744536193c87
[ "MIT" ]
4
2020-11-29T15:45:22.000Z
2021-12-25T13:35:57.000Z
Core/base/string_utils.cc
InfiniteSynthesis/StarLight
478d5a78a8277b83ad93b56b6ab1744536193c87
[ "MIT" ]
null
null
null
Core/base/string_utils.cc
InfiniteSynthesis/StarLight
478d5a78a8277b83ad93b56b6ab1744536193c87
[ "MIT" ]
1
2020-12-29T21:42:18.000Z
2020-12-29T21:42:18.000Z
// Copyright 2020 Infinite Synthesis(T.C.V.). All rights reserved. #include <ctype.h> #include <errno.h> #include <limits> #include <cstdint> #include <stdint.h> #include <limits.h> #include "base/string_utils.h" #ifdef __cplusplus namespace base { #endif bool SplitString(const std::string& target, char separator, std::vector<std::string>& result) { typedef std::string::size_type size_t; size_t i = 0; size_t value_start = INT_MAX; while (i < target.size()) { bool last_c = i == target.size() - 1; if (target[i] != separator && value_start == INT_MAX) { value_start = i; } else if (target[i] == separator || i == target.size() - 1) { size_t sub_num = last_c ? target.size() - value_start : i - value_start; if (value_start != INT_MAX) { result.push_back(target.substr(value_start, sub_num)); value_start = INT_MAX; } } i++; } return !result.empty(); } bool StringToFloat(const std::string& input, float& output) { int old_error = errno; errno = 0; char* endptr = NULL; float d = strtof(input.c_str(), &endptr); bool valid = (errno == 0 && !input.empty() && input.c_str() + input.length() == endptr && !isspace(input[0])); if (errno == 0) errno = old_error; if (valid) output = d; return valid; } bool StringToDouble(const std::string& input, double& output) { int old_error = errno; errno = 0; char* endptr = NULL; double d = strtod(input.c_str(), &endptr); bool valid = (errno == 0 && !input.empty() && input.c_str() + input.length() == endptr && !isspace(input[0])); if (errno == 0) errno = old_error; if (valid) output = d; return valid; } bool StringToInt(const std::string& input, int64_t& output, uint8_t base) { int old_error = errno; errno = 0; char* endptr = NULL; int64_t i = strtoll(input.c_str(), &endptr, base); bool valid = (errno == 0 && !input.empty() && input.c_str() + input.length() == endptr && !isspace(input[0])); if (errno == 0) errno = old_error; if (valid) output = i; return valid; } #ifdef __cplusplus } #endif
26.512195
80
0.603036
[ "vector" ]
040463131c8610932a9e44b126e6aeafed20575d
50,584
cpp
C++
XUSGMachineLearning/MachineLearning/XUSGMachineLearning_DML.cpp
StarsX/XUSG
85838d2ab1efde1926ff4cff2cbe5f5e55609bd5
[ "MIT" ]
31
2020-04-16T02:36:55.000Z
2022-03-30T13:14:27.000Z
XUSGMachineLearning/MachineLearning/XUSGMachineLearning_DML.cpp
StarsX/XUSGCore
659fd75666c05184cafc18d6c398b31c05c59051
[ "MIT" ]
null
null
null
XUSGMachineLearning/MachineLearning/XUSGMachineLearning_DML.cpp
StarsX/XUSGCore
659fd75666c05184cafc18d6c398b31c05c59051
[ "MIT" ]
1
2021-12-11T16:26:39.000Z
2021-12-11T16:26:39.000Z
//-------------------------------------------------------------------------------------- // Copyright (c) XU, Tianchen. All rights reserved. //-------------------------------------------------------------------------------------- #include "XUSGMachineLearning_DML.h" #include "Core/XUSG_DX12.h" using namespace std; using namespace XUSG; #define APPEND_FLAG(type, dmlType, flags, flag, none) ((flags & type::flag) == type::flag ? dmlType##_##flag : dmlType##_##none) #define APPEND_EXECUTION_FLAG(flags, flag) APPEND_FLAG(ExecutionFlag, DML_EXECUTION_FLAG, flags, flag, NONE) DML_TENSOR_DATA_TYPE ML::GetDMLTensorDataType(TensorDataType dataType) { static const DML_TENSOR_DATA_TYPE dataTypes[] = { DML_TENSOR_DATA_TYPE_UNKNOWN, DML_TENSOR_DATA_TYPE_FLOAT32, DML_TENSOR_DATA_TYPE_FLOAT16, DML_TENSOR_DATA_TYPE_UINT32, DML_TENSOR_DATA_TYPE_UINT16, DML_TENSOR_DATA_TYPE_UINT8, DML_TENSOR_DATA_TYPE_INT32, DML_TENSOR_DATA_TYPE_INT16, DML_TENSOR_DATA_TYPE_INT8 }; return dataTypes[static_cast<uint32_t>(dataType)]; } DML_OPERATOR_TYPE ML::GetDMLOpteratorType(OperatorType operatorType) { static const DML_OPERATOR_TYPE operatorTypes[] = { DML_OPERATOR_INVALID, DML_OPERATOR_ELEMENT_WISE_IDENTITY, DML_OPERATOR_ELEMENT_WISE_ABS, DML_OPERATOR_ELEMENT_WISE_ACOS, DML_OPERATOR_ELEMENT_WISE_ADD, DML_OPERATOR_ELEMENT_WISE_ASIN, DML_OPERATOR_ELEMENT_WISE_ATAN, DML_OPERATOR_ELEMENT_WISE_CEIL, DML_OPERATOR_ELEMENT_WISE_CLIP, DML_OPERATOR_ELEMENT_WISE_COS, DML_OPERATOR_ELEMENT_WISE_DIVIDE, DML_OPERATOR_ELEMENT_WISE_EXP, DML_OPERATOR_ELEMENT_WISE_FLOOR, DML_OPERATOR_ELEMENT_WISE_LOG, DML_OPERATOR_ELEMENT_WISE_LOGICAL_AND, DML_OPERATOR_ELEMENT_WISE_LOGICAL_EQUALS, DML_OPERATOR_ELEMENT_WISE_LOGICAL_GREATER_THAN, DML_OPERATOR_ELEMENT_WISE_LOGICAL_LESS_THAN, DML_OPERATOR_ELEMENT_WISE_LOGICAL_NOT, DML_OPERATOR_ELEMENT_WISE_LOGICAL_OR, DML_OPERATOR_ELEMENT_WISE_LOGICAL_XOR, DML_OPERATOR_ELEMENT_WISE_MAX, DML_OPERATOR_ELEMENT_WISE_MEAN, DML_OPERATOR_ELEMENT_WISE_MIN, DML_OPERATOR_ELEMENT_WISE_MULTIPLY, DML_OPERATOR_ELEMENT_WISE_POW, DML_OPERATOR_ELEMENT_WISE_CONSTANT_POW, DML_OPERATOR_ELEMENT_WISE_RECIP, DML_OPERATOR_ELEMENT_WISE_SIN, DML_OPERATOR_ELEMENT_WISE_SQRT, DML_OPERATOR_ELEMENT_WISE_SUBTRACT, DML_OPERATOR_ELEMENT_WISE_TAN, DML_OPERATOR_ELEMENT_WISE_THRESHOLD, DML_OPERATOR_ELEMENT_WISE_QUANTIZE_LINEAR, DML_OPERATOR_ELEMENT_WISE_DEQUANTIZE_LINEAR, DML_OPERATOR_ACTIVATION_ELU, DML_OPERATOR_ACTIVATION_HARDMAX, DML_OPERATOR_ACTIVATION_HARD_SIGMOID, DML_OPERATOR_ACTIVATION_IDENTITY, DML_OPERATOR_ACTIVATION_LEAKY_RELU, DML_OPERATOR_ACTIVATION_LINEAR, DML_OPERATOR_ACTIVATION_LOG_SOFTMAX, DML_OPERATOR_ACTIVATION_PARAMETERIZED_RELU, DML_OPERATOR_ACTIVATION_PARAMETRIC_SOFTPLUS, DML_OPERATOR_ACTIVATION_RELU, DML_OPERATOR_ACTIVATION_SCALED_ELU, DML_OPERATOR_ACTIVATION_SCALED_TANH, DML_OPERATOR_ACTIVATION_SIGMOID, DML_OPERATOR_ACTIVATION_SOFTMAX, DML_OPERATOR_ACTIVATION_SOFTPLUS, DML_OPERATOR_ACTIVATION_SOFTSIGN, DML_OPERATOR_ACTIVATION_TANH, DML_OPERATOR_ACTIVATION_THRESHOLDED_RELU, DML_OPERATOR_CONVOLUTION, DML_OPERATOR_GEMM, DML_OPERATOR_REDUCE, DML_OPERATOR_AVERAGE_POOLING, DML_OPERATOR_LP_POOLING, DML_OPERATOR_MAX_POOLING, DML_OPERATOR_ROI_POOLING, DML_OPERATOR_SLICE, DML_OPERATOR_CAST, DML_OPERATOR_SPLIT, DML_OPERATOR_JOIN, DML_OPERATOR_PADDING, DML_OPERATOR_VALUE_SCALE_2D, DML_OPERATOR_UPSAMPLE_2D, DML_OPERATOR_GATHER, DML_OPERATOR_SPACE_TO_DEPTH, DML_OPERATOR_DEPTH_TO_SPACE, DML_OPERATOR_TILE, DML_OPERATOR_TOP_K, DML_OPERATOR_BATCH_NORMALIZATION, DML_OPERATOR_MEAN_VARIANCE_NORMALIZATION, DML_OPERATOR_LOCAL_RESPONSE_NORMALIZATION, DML_OPERATOR_LP_NORMALIZATION, DML_OPERATOR_RNN, DML_OPERATOR_LSTM, DML_OPERATOR_GRU }; return operatorTypes[static_cast<uint32_t>(operatorType)]; } DML_TENSOR_FLAGS ML::GetDMLTensorFlag(TensorFlag tensorFlag) { static const DML_TENSOR_FLAGS tensorFlags[] = { DML_TENSOR_FLAG_OWNED_BY_DML }; if (tensorFlag == TensorFlag::NONE) return DML_TENSOR_FLAG_NONE; const auto index = Log2(static_cast<uint32_t>(tensorFlag)); return tensorFlags[index]; } DML_TENSOR_FLAGS ML::GetDMLTensorFlags(TensorFlag tensorFlags) { auto flags = DML_TENSOR_FLAG_NONE; flags |= (tensorFlags & TensorFlag::MANAGED) == TensorFlag::MANAGED ? DML_TENSOR_FLAG_OWNED_BY_DML : DML_TENSOR_FLAG_NONE; return flags; } DML_EXECUTION_FLAGS ML::GetDMLExecutionFlag(ExecutionFlag executionFlag) { static const DML_EXECUTION_FLAGS executionFlags[] = { DML_EXECUTION_FLAG_ALLOW_HALF_PRECISION_COMPUTATION, DML_EXECUTION_FLAG_DISABLE_META_COMMANDS, DML_EXECUTION_FLAG_DESCRIPTORS_VOLATILE }; if (executionFlag == ExecutionFlag::NONE) return DML_EXECUTION_FLAG_NONE; const auto index = Log2(static_cast<uint32_t>(executionFlag)); return executionFlags[index]; } DML_EXECUTION_FLAGS ML::GetDMLExecutionFlags(ExecutionFlag executionFlags) { auto flags = DML_EXECUTION_FLAG_NONE; flags |= APPEND_EXECUTION_FLAG(executionFlags, ALLOW_HALF_PRECISION_COMPUTATION); flags |= APPEND_EXECUTION_FLAG(executionFlags, DISABLE_META_COMMANDS); flags |= APPEND_EXECUTION_FLAG(executionFlags, DESCRIPTORS_VOLATILE); return flags; } DML_REDUCE_FUNCTION ML::GetDMLReduceFunction(ReduceFunction reduceFunction) { static const DML_REDUCE_FUNCTION reduceFunctions[] = { DML_REDUCE_FUNCTION_ARGMAX, DML_REDUCE_FUNCTION_ARGMIN, DML_REDUCE_FUNCTION_AVERAGE, DML_REDUCE_FUNCTION_L1, DML_REDUCE_FUNCTION_L2, DML_REDUCE_FUNCTION_LOG_SUM, DML_REDUCE_FUNCTION_LOG_SUM_EXP, DML_REDUCE_FUNCTION_MAX, DML_REDUCE_FUNCTION_MIN, DML_REDUCE_FUNCTION_MULTIPLY, DML_REDUCE_FUNCTION_SUM, DML_REDUCE_FUNCTION_SUM_SQUARE }; return reduceFunctions[static_cast<uint32_t>(reduceFunction)]; } DML_MATRIX_TRANSFORM ML::GetDMLMatrixTransform(MatrixTransform transform) { static const DML_MATRIX_TRANSFORM matrixTransforms[] = { DML_MATRIX_TRANSFORM_NONE, DML_MATRIX_TRANSFORM_TRANSPOSE }; return matrixTransforms[static_cast<uint32_t>(transform)]; } DML_CONVOLUTION_MODE ML::GetDMLConvolutionMode(ConvolutionType mode) { static const DML_CONVOLUTION_MODE convolutionModes[] = { DML_CONVOLUTION_MODE_CONVOLUTION, DML_CONVOLUTION_MODE_CROSS_CORRELATION }; return convolutionModes[static_cast<uint32_t>(mode)]; } DML_CONVOLUTION_DIRECTION ML::GetDMLConvolutionDirection(ConvolutionDirection direction) { static const DML_CONVOLUTION_DIRECTION convolutionDirections[] = { DML_CONVOLUTION_DIRECTION_FORWARD, DML_CONVOLUTION_DIRECTION_BACKWARD }; return convolutionDirections[static_cast<uint32_t>(direction)]; } DML_PADDING_MODE ML::GetDMLPaddingMode(PaddingType mode) { static const DML_PADDING_MODE paddingModes[] = { DML_PADDING_MODE_CONSTANT, DML_PADDING_MODE_EDGE, DML_PADDING_MODE_REFLECTION, #if DML_TARGET_VERSION >= 0x3000 DML_PADDING_MODE_SYMMETRIC #else DML_PADDING_MODE(DML_PADDING_MODE_REFLECTION + 1) #endif }; return paddingModes[static_cast<uint32_t>(mode)]; } DML_INTERPOLATION_MODE ML::GetDMLInterpolationMode(InterpolationType mode) { static const DML_INTERPOLATION_MODE interpolationModes[] = { DML_INTERPOLATION_MODE_NEAREST_NEIGHBOR, DML_INTERPOLATION_MODE_LINEAR }; return interpolationModes[static_cast<uint32_t>(mode)]; } DML_RECURRENT_NETWORK_DIRECTION ML::GetDMLRecurrentNetworkDirection(RecurrentNetworkDirection direction) { static const DML_RECURRENT_NETWORK_DIRECTION recurrentNetworkDirections[] = { DML_RECURRENT_NETWORK_DIRECTION_FORWARD, DML_RECURRENT_NETWORK_DIRECTION_BACKWARD, DML_RECURRENT_NETWORK_DIRECTION_BIDIRECTIONAL }; return recurrentNetworkDirections[static_cast<uint32_t>(direction)]; } void ML::GetDMLTypedOperator(string& dmlTypedOpDesc, const void* pTypedOp) { struct DMLUnaryOp { const DML_TENSOR_DESC* InputTensor; const DML_TENSOR_DESC* OutputTensor; }; struct DMLElementWiseUnaryOp { const DML_TENSOR_DESC* InputTensor; const DML_TENSOR_DESC* OutputTensor; const DML_SCALE_BIAS* ScaleBias; }; struct DMLElementWiseBinaryOp { const DML_TENSOR_DESC* ATensor; const DML_TENSOR_DESC* BTensor; const DML_TENSOR_DESC* OutputTensor; }; static const auto getDMLUnaryOp = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DMLUnaryOp)); auto& dmlDesc = reinterpret_cast<DMLUnaryOp&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const UnaryOp*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; }; static const auto getDMLElementWiseUnaryOp = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DMLElementWiseUnaryOp)); auto& dmlDesc = reinterpret_cast<DMLElementWiseUnaryOp&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ElementWiseUnaryOp*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.ScaleBias = reinterpret_cast<const DML_SCALE_BIAS*>(typedOp.pScaleBias); }; static const auto getDMLElementWiseBinaryOp = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DMLElementWiseBinaryOp)); auto& dmlDesc = reinterpret_cast<DMLElementWiseBinaryOp&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ElementWiseBinaryOp*>(pTypedOp); dmlDesc.ATensor = typedOp.pA ? static_cast<const DML_TENSOR_DESC*>(typedOp.pA->GetHandle()) : nullptr; dmlDesc.BTensor = typedOp.pB ? static_cast<const DML_TENSOR_DESC*>(typedOp.pB->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; }; static const auto getDMLElementWiseClip = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ELEMENT_WISE_CLIP_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ELEMENT_WISE_CLIP_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ElementWiseClip*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.ScaleBias = reinterpret_cast<const DML_SCALE_BIAS*>(typedOp.pScaleBias); dmlDesc.Min = typedOp.Min; dmlDesc.Max = typedOp.Max; }; static const auto getDMLElementWisePow = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ELEMENT_WISE_POW_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ELEMENT_WISE_POW_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ElementWisePow*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.ExponentTensor = typedOp.pExponent ? static_cast<const DML_TENSOR_DESC*>(typedOp.pExponent->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.ScaleBias = reinterpret_cast<const DML_SCALE_BIAS*>(typedOp.pScaleBias); }; static const auto getDMLElementWiseConstantPow = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ELEMENT_WISE_CONSTANT_POW_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ELEMENT_WISE_CONSTANT_POW_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ElementWiseConstantPow*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.ScaleBias = reinterpret_cast<const DML_SCALE_BIAS*>(typedOp.pScaleBias); dmlDesc.Exponent = typedOp.Exponent; }; static const auto getDMLElementWiseThreshold = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ELEMENT_WISE_THRESHOLD_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ELEMENT_WISE_THRESHOLD_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ElementWiseThreshold*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.ScaleBias = reinterpret_cast<const DML_SCALE_BIAS*>(typedOp.pScaleBias); dmlDesc.Min = typedOp.Min; }; static const auto getDMLElementWiseQuantizeLinear = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ELEMENT_WISE_QUANTIZE_LINEAR_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ELEMENT_WISE_QUANTIZE_LINEAR_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ElementWiseQuantizeLinear*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.ScaleTensor = typedOp.pScale ? static_cast<const DML_TENSOR_DESC*>(typedOp.pScale->GetHandle()) : nullptr; dmlDesc.ZeroPointTensor = typedOp.pZeroPoint ? static_cast<const DML_TENSOR_DESC*>(typedOp.pZeroPoint->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; }; static const auto getDMLActivationELU = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ACTIVATION_ELU_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ACTIVATION_ELU_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ActivationELU*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.Alpha = typedOp.Alpha; }; static const auto getDMLActivationLinear = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ACTIVATION_LINEAR_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ACTIVATION_LINEAR_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ActivationLinear*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.Alpha = typedOp.Alpha; dmlDesc.Beta = typedOp.Beta; }; static const auto getDMLActivationParameterizedRELU = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ACTIVATION_PARAMETERIZED_RELU_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ACTIVATION_PARAMETERIZED_RELU_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ActivationParameterizedRELU*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.SlopeTensor = typedOp.pSlope ? static_cast<const DML_TENSOR_DESC*>(typedOp.pSlope->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; }; static const auto getDMLActivationScaledELU = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ACTIVATION_SCALED_ELU_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ACTIVATION_SCALED_ELU_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ActivationScaledELU*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.Alpha = typedOp.Alpha; dmlDesc.Gamma = typedOp.Gamma; }; static const auto getDMLActivationSoftplus = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ACTIVATION_SOFTPLUS_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ACTIVATION_SOFTPLUS_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ActivationSoftplus*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.Steepness = typedOp.Steepness; }; static const auto getDMLConvolution = [](string& dmlTypedOpDesc, const void* pTypedOp) { const auto& typedOp = *static_cast<const ConvolutionOperator*>(pTypedOp); string dmlFusedActivation; if (typedOp.pFusedActivation) GetDMLTypedOperator(dmlFusedActivation, typedOp.pFusedActivation); dmlTypedOpDesc.resize(sizeof(DML_CONVOLUTION_OPERATOR_DESC) + (typedOp.pFusedActivation ? sizeof(DML_OPERATOR_DESC) + dmlFusedActivation.size() : 0)); auto& dmlDesc = reinterpret_cast<DML_CONVOLUTION_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto pDMLFusedActivation = typedOp.pFusedActivation ? reinterpret_cast<DML_OPERATOR_DESC*>( &dmlTypedOpDesc[sizeof(DML_CONVOLUTION_OPERATOR_DESC)]) : nullptr; dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.FilterTensor = typedOp.pFilter ? static_cast<const DML_TENSOR_DESC*>(typedOp.pFilter->GetHandle()) : nullptr; dmlDesc.BiasTensor = typedOp.pBias ? static_cast<const DML_TENSOR_DESC*>(typedOp.pBias->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.Mode = GetDMLConvolutionMode(typedOp.Mode); dmlDesc.Direction = GetDMLConvolutionDirection(typedOp.Direction); dmlDesc.DimensionCount = typedOp.DimensionCount; dmlDesc.Strides = typedOp.pStrides; dmlDesc.Dilations = typedOp.pDilations; dmlDesc.StartPadding = typedOp.pStartPadding; dmlDesc.EndPadding = typedOp.pEndPadding; dmlDesc.OutputPadding = typedOp.pOutputPadding; dmlDesc.GroupCount = typedOp.GroupCount; dmlDesc.FusedActivation = pDMLFusedActivation; if (pDMLFusedActivation) { assert(typedOp.pFusedActivation); const auto offset = sizeof(DML_CONVOLUTION_OPERATOR_DESC) + sizeof(DML_OPERATOR_DESC); pDMLFusedActivation->Type = GetDMLOpteratorType(*static_cast<const OperatorType*>(typedOp.pFusedActivation)); pDMLFusedActivation->Desc = &dmlTypedOpDesc[offset]; memcpy(&dmlTypedOpDesc[offset], dmlFusedActivation.data(), dmlFusedActivation.size()); } }; static const auto getDMLGEMM = [](string& dmlTypedOpDesc, const void* pTypedOp) { const auto& typedOp = *static_cast<const GEMMOperator*>(pTypedOp); string dmlFusedActivation; if (typedOp.pFusedActivation) GetDMLTypedOperator(dmlFusedActivation, typedOp.pFusedActivation); dmlTypedOpDesc.resize(sizeof(DML_GEMM_OPERATOR_DESC) + (typedOp.pFusedActivation ? sizeof(DML_OPERATOR_DESC) + dmlFusedActivation.size() : 0)); auto& dmlDesc = reinterpret_cast<DML_GEMM_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto pDMLFusedActivation = typedOp.pFusedActivation ? reinterpret_cast<DML_OPERATOR_DESC*>( &dmlTypedOpDesc[sizeof(DML_GEMM_OPERATOR_DESC)]) : nullptr; dmlDesc.ATensor = typedOp.pA ? static_cast<const DML_TENSOR_DESC*>(typedOp.pA->GetHandle()) : nullptr; dmlDesc.BTensor = typedOp.pB ? static_cast<const DML_TENSOR_DESC*>(typedOp.pB->GetHandle()) : nullptr; dmlDesc.CTensor = typedOp.pC ? static_cast<const DML_TENSOR_DESC*>(typedOp.pC->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.TransA = GetDMLMatrixTransform(typedOp.TransA); dmlDesc.TransB = GetDMLMatrixTransform(typedOp.TransB); dmlDesc.Alpha = typedOp.Alpha; dmlDesc.Beta = typedOp.Beta; dmlDesc.FusedActivation = pDMLFusedActivation; if (pDMLFusedActivation) { assert(typedOp.pFusedActivation); const auto offset = sizeof(DML_GEMM_OPERATOR_DESC) + sizeof(DML_OPERATOR_DESC); pDMLFusedActivation->Type = GetDMLOpteratorType(*static_cast<const OperatorType*>(typedOp.pFusedActivation)); pDMLFusedActivation->Desc = &dmlTypedOpDesc[offset]; memcpy(&dmlTypedOpDesc[offset], dmlFusedActivation.data(), dmlFusedActivation.size()); } }; static const auto getDMLReduce = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_REDUCE_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_REDUCE_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ReduceOperator*>(pTypedOp); dmlDesc.Function = GetDMLReduceFunction(typedOp.Function); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.AxisCount = typedOp.AxisCount; dmlDesc.Axes = typedOp.pAxes; }; static const auto getDMLAveragePooling = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_AVERAGE_POOLING_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_AVERAGE_POOLING_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const AveragePooling*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.DimensionCount = typedOp.DimensionCount; dmlDesc.Strides = typedOp.pStrides; dmlDesc.WindowSize = typedOp.pWindowSize; dmlDesc.StartPadding = typedOp.pStartPadding; dmlDesc.EndPadding = typedOp.pEndPadding; dmlDesc.IncludePadding = typedOp.IncludePadding; }; static const auto getDMLLPPooling = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_LP_POOLING_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_LP_POOLING_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const LPPooling*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.DimensionCount = typedOp.DimensionCount; dmlDesc.Strides = typedOp.pStrides; dmlDesc.WindowSize = typedOp.pWindowSize; dmlDesc.StartPadding = typedOp.pStartPadding; dmlDesc.EndPadding = typedOp.pEndPadding; dmlDesc.P = typedOp.P; }; static const auto getDMLMaxPooling = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_MAX_POOLING_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_MAX_POOLING_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const MaxPooling*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.DimensionCount = typedOp.DimensionCount; dmlDesc.Strides = typedOp.pStrides; dmlDesc.WindowSize = typedOp.pWindowSize; dmlDesc.StartPadding = typedOp.pStartPadding; dmlDesc.EndPadding = typedOp.pEndPadding; }; static const auto getDMLROIPooling = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_ROI_POOLING_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_ROI_POOLING_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ROIPooling*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.ROITensor = typedOp.pROI ? static_cast<const DML_TENSOR_DESC*>(typedOp.pROI->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.SpatialScale = typedOp.SpatialScale; dmlDesc.PooledSize.Width = typedOp.PooledWidth; dmlDesc.PooledSize.Height = typedOp.PooledHeight; }; static const auto getDMLSlice = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_SLICE_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_SLICE_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const SliceOperator*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.DimensionCount = typedOp.DimensionCount; dmlDesc.Offsets = typedOp.pOffsets; dmlDesc.Sizes = typedOp.pSizes; dmlDesc.Strides = typedOp.pStrides; }; static const auto getDMLSplit = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_SPLIT_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_SPLIT_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const SplitOperator*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputCount = typedOp.OutputCount; dmlDesc.OutputTensors = typedOp.pOutputs ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutputs->GetHandle()) : nullptr; dmlDesc.Axis = typedOp.Axis; }; static const auto getDMLJoin = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_JOIN_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_JOIN_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const JoinOperator*>(pTypedOp); dmlDesc.InputCount = typedOp.InputCount; dmlDesc.InputTensors = typedOp.pInputs ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInputs->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.Axis = typedOp.Axis; }; static const auto getDMLPadding = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_PADDING_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_PADDING_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const PaddingOperator*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.PaddingMode = GetDMLPaddingMode(typedOp.PaddingMode); dmlDesc.PaddingValue = typedOp.PaddingValue; dmlDesc.DimensionCount = typedOp.DimensionCount; dmlDesc.StartPadding = typedOp.pStartPadding; dmlDesc.EndPadding = typedOp.pEndPadding; }; static const auto getDMLValueScale2D = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_VALUE_SCALE_2D_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_VALUE_SCALE_2D_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const ValueScale2D*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.Scale = typedOp.Scale; dmlDesc.ChannelCount = typedOp.ChannelCount; dmlDesc.Bias = typedOp.pBias; }; static const auto getDMLUpsample2D = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_UPSAMPLE_2D_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_UPSAMPLE_2D_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const Upsample2D*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.ScaleSize.Width = typedOp.ScaleWidth; dmlDesc.ScaleSize.Height = typedOp.ScaleHeight; dmlDesc.InterpolationMode = GetDMLInterpolationMode(typedOp.InterpolationMode); }; static const auto getDMLGather = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_GATHER_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_GATHER_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const GatherOperator*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.IndicesTensor = typedOp.pIndices ? static_cast<const DML_TENSOR_DESC*>(typedOp.pIndices->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.Axis = typedOp.Axis; dmlDesc.IndexDimensions = typedOp.IndexDimensions; }; static const auto getDMLSpaceDepth = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_SPACE_TO_DEPTH_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_SPACE_TO_DEPTH_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const SpaceToDepth*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.BlockSize = typedOp.BlockSize; }; static const auto getDMLTile = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_TILE_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_TILE_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const TileOperator*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.RepeatsCount = typedOp.RepeatsCount; dmlDesc.Repeats = typedOp.pRepeats; }; static const auto getDMLTopK = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_TOP_K_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_TOP_K_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const TopKOperator*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputValueTensor = typedOp.pOutputValue ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutputValue->GetHandle()) : nullptr; dmlDesc.OutputIndexTensor = typedOp.pOutputIndex ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutputIndex->GetHandle()) : nullptr; dmlDesc.Axis = typedOp.Axis; dmlDesc.K = typedOp.K; }; static const auto getDMLBatchNormalization = [](string& dmlTypedOpDesc, const void* pTypedOp) { const auto& typedOp = *static_cast<const BatchNormalization*>(pTypedOp); string dmlFusedActivation; if (typedOp.pFusedActivation) GetDMLTypedOperator(dmlFusedActivation, typedOp.pFusedActivation); dmlTypedOpDesc.resize(sizeof(DML_BATCH_NORMALIZATION_OPERATOR_DESC) + (typedOp.pFusedActivation ? sizeof(DML_OPERATOR_DESC) + dmlFusedActivation.size() : 0)); auto& dmlDesc = reinterpret_cast<DML_BATCH_NORMALIZATION_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto pDMLFusedActivation = typedOp.pFusedActivation ? reinterpret_cast<DML_OPERATOR_DESC*>( &dmlTypedOpDesc[sizeof(DML_BATCH_NORMALIZATION_OPERATOR_DESC)]) : nullptr; dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.MeanTensor = typedOp.pMean ? static_cast<const DML_TENSOR_DESC*>(typedOp.pMean->GetHandle()) : nullptr; dmlDesc.VarianceTensor = typedOp.pVariance ? static_cast<const DML_TENSOR_DESC*>(typedOp.pVariance->GetHandle()) : nullptr; dmlDesc.ScaleTensor = typedOp.pScale ? static_cast<const DML_TENSOR_DESC*>(typedOp.pScale->GetHandle()) : nullptr; dmlDesc.BiasTensor = typedOp.pBias ? static_cast<const DML_TENSOR_DESC*>(typedOp.pBias->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.Spatial = typedOp.Spatial; dmlDesc.Epsilon = typedOp.Epsilon; dmlDesc.FusedActivation = pDMLFusedActivation; if (pDMLFusedActivation) { assert(typedOp.pFusedActivation); const auto offset = sizeof(DML_CONVOLUTION_OPERATOR_DESC) + sizeof(DML_OPERATOR_DESC); pDMLFusedActivation->Type = GetDMLOpteratorType(*static_cast<const OperatorType*>(typedOp.pFusedActivation)); pDMLFusedActivation->Desc = &dmlTypedOpDesc[offset]; memcpy(&dmlTypedOpDesc[offset], dmlFusedActivation.data(), dmlFusedActivation.size()); } }; static const auto getDMLMeanVarianceNormalization = [](string& dmlTypedOpDesc, const void* pTypedOp) { const auto& typedOp = *static_cast<const MeanVarianceNormalization*>(pTypedOp); string dmlFusedActivation; if (typedOp.pFusedActivation) GetDMLTypedOperator(dmlFusedActivation, typedOp.pFusedActivation); dmlTypedOpDesc.resize(sizeof(DML_MEAN_VARIANCE_NORMALIZATION_OPERATOR_DESC) + (typedOp.pFusedActivation ? sizeof(DML_OPERATOR_DESC) + dmlFusedActivation.size() : 0)); auto& dmlDesc = reinterpret_cast<DML_MEAN_VARIANCE_NORMALIZATION_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto pDMLFusedActivation = typedOp.pFusedActivation ? reinterpret_cast<DML_OPERATOR_DESC*>( &dmlTypedOpDesc[sizeof(DML_MEAN_VARIANCE_NORMALIZATION_OPERATOR_DESC)]) : nullptr; dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.ScaleTensor = typedOp.pScale ? static_cast<const DML_TENSOR_DESC*>(typedOp.pScale->GetHandle()) : nullptr; dmlDesc.BiasTensor = typedOp.pBias ? static_cast<const DML_TENSOR_DESC*>(typedOp.pBias->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.CrossChannel = typedOp.CrossChannel; dmlDesc.NormalizeVariance = typedOp.NormalizeVariance; dmlDesc.Epsilon = typedOp.Epsilon; dmlDesc.FusedActivation = pDMLFusedActivation; if (pDMLFusedActivation) { assert(typedOp.pFusedActivation); const auto offset = sizeof(DML_CONVOLUTION_OPERATOR_DESC) + sizeof(DML_OPERATOR_DESC); pDMLFusedActivation->Type = GetDMLOpteratorType(*static_cast<const OperatorType*>(typedOp.pFusedActivation)); pDMLFusedActivation->Desc = &dmlTypedOpDesc[offset]; memcpy(&dmlTypedOpDesc[offset], dmlFusedActivation.data(), dmlFusedActivation.size()); } }; static const auto getDMLLocalResponseNormalization = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_LOCAL_RESPONSE_NORMALIZATION_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_LOCAL_RESPONSE_NORMALIZATION_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const LocalResponseNormalization*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.CrossChannel = typedOp.CrossChannel; dmlDesc.LocalSize = typedOp.LocalSize; dmlDesc.Alpha = typedOp.Alpha; dmlDesc.Beta = typedOp.Beta; dmlDesc.Bias = typedOp.Bias; }; static const auto getDMLLPNormalization = [](string& dmlTypedOpDesc, const void* pTypedOp) { dmlTypedOpDesc.resize(sizeof(DML_LP_NORMALIZATION_OPERATOR_DESC)); auto& dmlDesc = reinterpret_cast<DML_LP_NORMALIZATION_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto& typedOp = *static_cast<const LPNormalization*>(pTypedOp); dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.OutputTensor = typedOp.pOutput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutput->GetHandle()) : nullptr; dmlDesc.Axis = typedOp.Axis; dmlDesc.Epsilon = typedOp.Epsilon; dmlDesc.P = typedOp.P; }; static const auto getDMLRNN = [](string& dmlTypedOpDesc, const void* pTypedOp) { const auto& typedOp = *static_cast<const RNNOperator*>(pTypedOp); vector<string> dmlActivations(typedOp.ActivationCount); auto dmlTypedDescSize = sizeof(DML_RNN_OPERATOR_DESC); if (typedOp.pActivations) { dmlTypedDescSize += sizeof(DML_OPERATOR_DESC) * typedOp.ActivationCount; for (auto i = 0u; i < typedOp.ActivationCount; ++i) { assert(typedOp.pActivations[i]); GetDMLTypedOperator(dmlActivations[i], typedOp.pActivations[i]); dmlTypedDescSize += dmlActivations[i].size(); } } dmlTypedOpDesc.resize(dmlTypedDescSize); auto& dmlDesc = reinterpret_cast<DML_RNN_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto pDMLActivations = typedOp.pActivations ? reinterpret_cast<DML_OPERATOR_DESC*>( &dmlTypedOpDesc[sizeof(DML_RNN_OPERATOR_DESC)]) : nullptr; dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.WeightTensor = typedOp.pWeight ? static_cast<const DML_TENSOR_DESC*>(typedOp.pWeight->GetHandle()) : nullptr; dmlDesc.RecurrenceTensor = typedOp.pRecurrence ? static_cast<const DML_TENSOR_DESC*>(typedOp.pRecurrence->GetHandle()) : nullptr; dmlDesc.BiasTensor = typedOp.pBias ? static_cast<const DML_TENSOR_DESC*>(typedOp.pBias->GetHandle()) : nullptr; dmlDesc.HiddenInitTensor = typedOp.pHiddenInit ? static_cast<const DML_TENSOR_DESC*>(typedOp.pHiddenInit->GetHandle()) : nullptr; dmlDesc.SequenceLengthsTensor = typedOp.pSequenceLengths ? static_cast<const DML_TENSOR_DESC*>(typedOp.pSequenceLengths->GetHandle()) : nullptr; dmlDesc.OutputSequenceTensor = typedOp.pOutputSequence ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutputSequence->GetHandle()) : nullptr; dmlDesc.OutputSingleTensor = typedOp.pOutputSingle ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutputSingle->GetHandle()) : nullptr; dmlDesc.ActivationDescCount = typedOp.ActivationCount; dmlDesc.ActivationDescs = pDMLActivations; dmlDesc.Direction = GetDMLRecurrentNetworkDirection(typedOp.Direction); if (pDMLActivations) { assert(typedOp.pActivations); auto offset = sizeof(DML_CONVOLUTION_OPERATOR_DESC) + sizeof(DML_OPERATOR_DESC) * typedOp.ActivationCount; for (auto i = 0u; i < typedOp.ActivationCount; ++i) { assert(typedOp.pActivations[i]); const auto& dmlActivation = dmlActivations[i]; auto* pDMLActivation = &pDMLActivations[i]; pDMLActivation->Type = GetDMLOpteratorType(*static_cast<const OperatorType*>(typedOp.pActivations[i])); pDMLActivation->Desc = &dmlTypedOpDesc[offset]; memcpy(&dmlTypedOpDesc[offset], dmlActivation.data(), dmlActivation.size()); } } }; static const auto getDMLLSTM = [](string& dmlTypedOpDesc, const void* pTypedOp) { const auto& typedOp = *static_cast<const LSTMOperator*>(pTypedOp); vector<string> dmlActivations(typedOp.ActivationCount); auto dmlTypedDescSize = sizeof(DML_LSTM_OPERATOR_DESC); if (typedOp.pActivations) { dmlTypedDescSize += sizeof(DML_OPERATOR_DESC) * typedOp.ActivationCount; for (auto i = 0u; i < typedOp.ActivationCount; ++i) { assert(typedOp.pActivations[i]); GetDMLTypedOperator(dmlActivations[i], typedOp.pActivations[i]); dmlTypedDescSize += dmlActivations[i].size(); } } dmlTypedOpDesc.resize(dmlTypedDescSize); auto& dmlDesc = reinterpret_cast<DML_LSTM_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto pDMLActivations = typedOp.pActivations ? reinterpret_cast<DML_OPERATOR_DESC*>( &dmlTypedOpDesc[sizeof(DML_LSTM_OPERATOR_DESC)]) : nullptr; dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.WeightTensor = typedOp.pWeight ? static_cast<const DML_TENSOR_DESC*>(typedOp.pWeight->GetHandle()) : nullptr; dmlDesc.RecurrenceTensor = typedOp.pRecurrence ? static_cast<const DML_TENSOR_DESC*>(typedOp.pRecurrence->GetHandle()) : nullptr; dmlDesc.BiasTensor = typedOp.pBias ? static_cast<const DML_TENSOR_DESC*>(typedOp.pBias->GetHandle()) : nullptr; dmlDesc.HiddenInitTensor = typedOp.pHiddenInit ? static_cast<const DML_TENSOR_DESC*>(typedOp.pHiddenInit->GetHandle()) : nullptr; dmlDesc.CellMemInitTensor = typedOp.pCellMemInit ? static_cast<const DML_TENSOR_DESC*>(typedOp.pCellMemInit->GetHandle()) : nullptr; dmlDesc.SequenceLengthsTensor = typedOp.pSequenceLengths ? static_cast<const DML_TENSOR_DESC*>(typedOp.pSequenceLengths->GetHandle()) : nullptr; dmlDesc.PeepholeTensor = typedOp.pPeephole ? static_cast<const DML_TENSOR_DESC*>(typedOp.pPeephole->GetHandle()) : nullptr; dmlDesc.OutputSequenceTensor = typedOp.pOutputSequence ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutputSequence->GetHandle()) : nullptr; dmlDesc.OutputSingleTensor = typedOp.pOutputSingle ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutputSingle->GetHandle()) : nullptr; dmlDesc.OutputCellSingleTensor = typedOp.pOutputCellSingle ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutputCellSingle->GetHandle()) : nullptr; dmlDesc.ActivationDescCount = typedOp.ActivationCount; dmlDesc.ActivationDescs = pDMLActivations; dmlDesc.Direction = GetDMLRecurrentNetworkDirection(typedOp.Direction); dmlDesc.ClipThreshold = typedOp.ClipThreshold; dmlDesc.UseClipThreshold = typedOp.UseClipThreshold; dmlDesc.CoupleInputForget = typedOp.CoupleInputForget; if (pDMLActivations) { assert(typedOp.pActivations); auto offset = sizeof(DML_CONVOLUTION_OPERATOR_DESC) + sizeof(DML_OPERATOR_DESC) * typedOp.ActivationCount; for (auto i = 0u; i < typedOp.ActivationCount; ++i) { assert(typedOp.pActivations[i]); const auto& dmlActivation = dmlActivations[i]; auto* pDMLActivation = &pDMLActivations[i]; pDMLActivation->Type = GetDMLOpteratorType(*static_cast<const OperatorType*>(typedOp.pActivations[i])); pDMLActivation->Desc = &dmlTypedOpDesc[offset]; memcpy(&dmlTypedOpDesc[offset], dmlActivation.data(), dmlActivation.size()); } } }; static const auto getDMLGRU = [](string& dmlTypedOpDesc, const void* pTypedOp) { const auto& typedOp = *static_cast<const GRUOperator*>(pTypedOp); vector<string> dmlActivations(typedOp.ActivationCount); auto dmlTypedDescSize = sizeof(DML_GRU_OPERATOR_DESC); if (typedOp.pActivations) { dmlTypedDescSize += sizeof(DML_OPERATOR_DESC) * typedOp.ActivationCount; for (auto i = 0u; i < typedOp.ActivationCount; ++i) { assert(typedOp.pActivations[i]); GetDMLTypedOperator(dmlActivations[i], typedOp.pActivations[i]); dmlTypedDescSize += dmlActivations[i].size(); } } dmlTypedOpDesc.resize(dmlTypedDescSize); auto& dmlDesc = reinterpret_cast<DML_GRU_OPERATOR_DESC&>(dmlTypedOpDesc[0]); const auto pDMLActivations = typedOp.pActivations ? reinterpret_cast<DML_OPERATOR_DESC*>( &dmlTypedOpDesc[sizeof(DML_GRU_OPERATOR_DESC)]) : nullptr; dmlDesc.InputTensor = typedOp.pInput ? static_cast<const DML_TENSOR_DESC*>(typedOp.pInput->GetHandle()) : nullptr; dmlDesc.WeightTensor = typedOp.pWeight ? static_cast<const DML_TENSOR_DESC*>(typedOp.pWeight->GetHandle()) : nullptr; dmlDesc.RecurrenceTensor = typedOp.pRecurrence ? static_cast<const DML_TENSOR_DESC*>(typedOp.pRecurrence->GetHandle()) : nullptr; dmlDesc.BiasTensor = typedOp.pBias ? static_cast<const DML_TENSOR_DESC*>(typedOp.pBias->GetHandle()) : nullptr; dmlDesc.HiddenInitTensor = typedOp.pHiddenInit ? static_cast<const DML_TENSOR_DESC*>(typedOp.pHiddenInit->GetHandle()) : nullptr; dmlDesc.SequenceLengthsTensor = typedOp.pSequenceLengths ? static_cast<const DML_TENSOR_DESC*>(typedOp.pSequenceLengths->GetHandle()) : nullptr; dmlDesc.OutputSequenceTensor = typedOp.pOutputSequence ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutputSequence->GetHandle()) : nullptr; dmlDesc.OutputSingleTensor = typedOp.pOutputSingle ? static_cast<const DML_TENSOR_DESC*>(typedOp.pOutputSingle->GetHandle()) : nullptr; dmlDesc.ActivationDescCount = typedOp.ActivationCount; dmlDesc.ActivationDescs = pDMLActivations; dmlDesc.Direction = GetDMLRecurrentNetworkDirection(typedOp.Direction); dmlDesc.LinearBeforeReset = typedOp.LinearBeforeReset; if (pDMLActivations) { assert(typedOp.pActivations); auto offset = sizeof(DML_CONVOLUTION_OPERATOR_DESC) + sizeof(DML_OPERATOR_DESC) * typedOp.ActivationCount; for (auto i = 0u; i < typedOp.ActivationCount; ++i) { assert(typedOp.pActivations[i]); const auto& dmlActivation = dmlActivations[i]; auto* pDMLActivation = &pDMLActivations[i]; pDMLActivation->Type = GetDMLOpteratorType(*static_cast<const OperatorType*>(typedOp.pActivations[i])); pDMLActivation->Desc = &dmlTypedOpDesc[offset]; memcpy(&dmlTypedOpDesc[offset], dmlActivation.data(), dmlActivation.size()); } } }; static const function<void(string&, const void*)> pfnGetDMLOps[] = { nullptr, // INVALID getDMLElementWiseUnaryOp, // ELEMENT_WISE_IDENTITY getDMLElementWiseUnaryOp, // ELEMENT_WISE_ABS getDMLElementWiseUnaryOp, // ELEMENT_WISE_ACOS getDMLElementWiseBinaryOp, // ELEMENT_WISE_ADD getDMLElementWiseUnaryOp, // ELEMENT_WISE_ASIN getDMLElementWiseUnaryOp, // ELEMENT_WISE_ATAN getDMLElementWiseUnaryOp, // ELEMENT_WISE_CEIL getDMLElementWiseClip, // ELEMENT_WISE_CLIP getDMLElementWiseUnaryOp, // ELEMENT_WISE_COS getDMLElementWiseBinaryOp, // ELEMENT_WISE_DIVIDE getDMLElementWiseUnaryOp, // ELEMENT_WISE_EXP getDMLElementWiseUnaryOp, // ELEMENT_WISE_FLOOR getDMLElementWiseUnaryOp, // ELEMENT_WISE_LOG getDMLElementWiseBinaryOp, // ELEMENT_WISE_LOGICAL_AND getDMLElementWiseBinaryOp, // ELEMENT_WISE_LOGICAL_EQUALS getDMLElementWiseBinaryOp, // ELEMENT_WISE_LOGICAL_GREATER_THAN getDMLElementWiseBinaryOp, // ELEMENT_WISE_LOGICAL_LESS_THAN getDMLUnaryOp, // ELEMENT_WISE_LOGICAL_NOT getDMLElementWiseBinaryOp, // ELEMENT_WISE_LOGICAL_OR getDMLElementWiseBinaryOp, // ELEMENT_WISE_LOGICAL_XOR getDMLElementWiseBinaryOp, // ELEMENT_WISE_MAX getDMLElementWiseBinaryOp, // ELEMENT_WISE_MEAN getDMLElementWiseBinaryOp, // ELEMENT_WISE_MIN getDMLElementWiseBinaryOp, // ELEMENT_WISE_MULTIPLY getDMLElementWisePow, // ELEMENT_WISE_POW getDMLElementWiseConstantPow, // ELEMENT_WISE_CONSTANT_POW getDMLElementWiseUnaryOp, // ELEMENT_WISE_RECIP getDMLElementWiseUnaryOp, // ELEMENT_WISE_SIN getDMLElementWiseUnaryOp, // ELEMENT_WISE_SQRT getDMLElementWiseBinaryOp, // ELEMENT_WISE_SUBTRACT getDMLElementWiseUnaryOp, // ELEMENT_WISE_TAN getDMLElementWiseThreshold, // ELEMENT_WISE_THRESHOLD getDMLElementWiseQuantizeLinear, // ELEMENT_WISE_QUANTIZE_LINEAR getDMLElementWiseQuantizeLinear, // ELEMENT_WISE_DEQUANTIZE_LINEAR getDMLActivationELU, // ACTIVATION_ELU getDMLUnaryOp, // ACTIVATION_HARDMAX getDMLActivationLinear, // ACTIVATION_HARD_SIGMOID getDMLUnaryOp, // ACTIVATION_IDENTITY getDMLActivationELU, // ACTIVATION_LEAKY_RELU getDMLActivationLinear, // ACTIVATION_LINEAR getDMLUnaryOp, // ACTIVATION_LOG_SOFTMAX getDMLActivationParameterizedRELU, // ACTIVATION_PARAMETERIZED_RELU getDMLActivationLinear, // ACTIVATION_PARAMETRIC_SOFTPLUS getDMLUnaryOp, // ACTIVATION_RELU getDMLActivationScaledELU, // ACTIVATION_SCALED_ELU getDMLActivationLinear, // ACTIVATION_SCALED_TANH getDMLUnaryOp, // ACTIVATION_SIGMOID getDMLUnaryOp, // ACTIVATION_SOFTMAX getDMLActivationSoftplus, // ACTIVATION_SOFTPLUS getDMLUnaryOp, // ACTIVATION_SOFTSIGN getDMLUnaryOp, // ACTIVATION_TANH getDMLActivationELU, // ACTIVATION_THRESHOLDED_RELU getDMLConvolution, // CONVOLUTION getDMLGEMM, // GEMM getDMLReduce, // REDUCE getDMLAveragePooling, // AVERAGE_POOLING getDMLLPPooling, // LP_POOLING getDMLMaxPooling, // MAX_POOLING getDMLROIPooling, // ROI_POOLING getDMLSlice, // SLICE getDMLUnaryOp, // CAST getDMLSplit, // SPLIT getDMLJoin, // JOIN getDMLPadding, // PADDING getDMLValueScale2D, // VALUE_SCALE_2D getDMLUpsample2D, // UPSAMPLE_2D getDMLGather, // GATHER getDMLSpaceDepth, // SPACE_TO_DEPTH getDMLSpaceDepth, // DEPTH_TO_SPACE getDMLTile, // TILE getDMLTopK, // TOP_K getDMLBatchNormalization, // BATCH_NORMALIZATION getDMLMeanVarianceNormalization, // MEAN_VARIANCE_NORMALIZATION getDMLLocalResponseNormalization, // LOCAL_RESPONSE_NORMALIZATION getDMLLPNormalization, // LP_NORMALIZATION getDMLRNN, // RNN getDMLLSTM, // LSTM getDMLGRU // GRU }; pfnGetDMLOps[*static_cast<const uint32_t*>(pTypedOp)](dmlTypedOpDesc, pTypedOp); } //-------------------------------------------------------------------------------------- using namespace XUSG::ML; Device_DML::Device_DML() { } Device_DML::~Device_DML() { } bool Device_DML::GetCommandRecorder(CommandRecorder* pCommandRecorder, const wchar_t* name) { return pCommandRecorder->Create(this, name); } bool Device_DML::Create(const XUSG::Device* pDevice, CreateDeviceFlag flags, const wchar_t* name) { const auto pDxDevice = static_cast<ID3D12Device*>(pDevice->GetHandle()); assert(pDxDevice); V_RETURN(DMLCreateDevice(pDxDevice, static_cast<DML_CREATE_DEVICE_FLAGS>(flags), IID_PPV_ARGS(&m_device)), cerr, false); if (name) m_device->SetName(name); return true; } void Device_DML::Create(void* pHandle, const wchar_t* name) { m_device = static_cast<IDMLDevice*>(pHandle); if (name) m_device->SetName(name); } void* Device_DML::GetHandle() const { return m_device.get(); }
46.707295
149
0.785466
[ "vector", "transform" ]
040a05e04c0d00501e42be0d990eae37f3b6de28
2,917
cpp
C++
src/liblelantus/test/joinsplit_tests.cpp
xinya-123/firo
738c8e1f96fa4c332a157776366b884a451194a2
[ "MIT" ]
1
2021-04-03T09:47:44.000Z
2021-04-03T09:47:44.000Z
src/liblelantus/test/joinsplit_tests.cpp
xinya-123/firo
738c8e1f96fa4c332a157776366b884a451194a2
[ "MIT" ]
null
null
null
src/liblelantus/test/joinsplit_tests.cpp
xinya-123/firo
738c8e1f96fa4c332a157776366b884a451194a2
[ "MIT" ]
1
2021-04-14T16:49:56.000Z
2021-04-14T16:49:56.000Z
#include "lelantus_test_fixture.h" #include "../../sigma/openssl_context.h" #include "../joinsplit.h" #include <boost/test/unit_test.hpp> #include <openssl/rand.h> namespace lelantus { class JoinSplitTests : public LelantusTestingSetup { public: JoinSplitTests() { } public: std::vector<PrivateCoin> GenerateCoins(std::vector<CAmount> const &amounts) { std::vector<PrivateCoin> privs; for (auto a : amounts) { std::vector<unsigned char> ecdsaKey; ecdsaKey.resize(32); // Create a key pair secp256k1_pubkey pubkey; do { if (RAND_bytes(ecdsaKey.data(), ecdsaKey.size()) != 1) { throw std::runtime_error("Unable to generate randomness"); } } while (!secp256k1_ec_pubkey_create( OpenSSLContext::get_context(), &pubkey, ecdsaKey.data())); // Hash the public key in the group to obtain a serial number auto serial = PrivateCoin::serialNumberFromSerializedPublicKey( OpenSSLContext::get_context(), &pubkey); Scalar randomness; randomness.randomize(); privs.emplace_back(params, serial, a, randomness, ecdsaKey, LELANTUS_TX_VERSION_4); } return privs; } std::vector<PublicCoin> BuildPublicCoins(std::vector<GroupElement> const &es) { std::vector<PublicCoin> pubs; pubs.reserve(es.size()); for (auto const &e : es) { pubs.emplace_back(e); } return pubs; } }; BOOST_FIXTURE_TEST_SUITE(lelantus_joinsplit_tests, JoinSplitTests) BOOST_AUTO_TEST_CASE(verify) { auto privs = GenerateCoins({1 * COIN, 10 * COIN, 100 * COIN, 99 * COIN}); std::vector<std::pair<PrivateCoin, uint32_t>> cin = { {privs[0], 1}, {privs[1], 1}, {privs[2], 2} }; std::map<uint32_t, std::vector<PublicCoin>> anons = { {1, BuildPublicCoins(GenerateGroupElements(10))}, {2, BuildPublicCoins(GenerateGroupElements(10))}, }; anons[1][0] = privs[0].getPublicCoin(); anons[1][1] = privs[1].getPublicCoin(); anons[2][0] = privs[2].getPublicCoin(); std::map<uint32_t, uint256> groupBlockHashes = { {1, ArithToUint256(1)}, {2, ArithToUint256(3)}, }; // inputs = 111 // outputs = 0.01(fee) + 99(mint) + 11.99(vout) auto vout = 12 * COIN - CENT; JoinSplit joinSplit( params, cin, anons, vout, // vout {privs[3]}, // cout CENT, // fee groupBlockHashes, ArithToUint256(3)); std::vector<uint32_t> expectedGroupIds = {1, 1, 2}; BOOST_CHECK(expectedGroupIds == joinSplit.getCoinGroupIds()); BOOST_CHECK(joinSplit.Verify(anons, {privs[3].getPublicCoin()}, vout, ArithToUint256(3))); } BOOST_AUTO_TEST_SUITE_END() } // namespace lelantus
27.780952
95
0.597532
[ "vector" ]
040e9e6b560babe9b3835fdca8f52e6353489dc1
4,643
cpp
C++
src/EventManager.cpp
frolv/lynxbot
e9c2e9ba23eca8918d69215850bd094488b9a33a
[ "MIT" ]
3
2016-07-12T21:42:09.000Z
2016-08-31T05:49:40.000Z
src/EventManager.cpp
frolv/osrs-twitch-bot
e9c2e9ba23eca8918d69215850bd094488b9a33a
[ "MIT" ]
null
null
null
src/EventManager.cpp
frolv/osrs-twitch-bot
e9c2e9ba23eca8918d69215850bd094488b9a33a
[ "MIT" ]
1
2016-05-26T14:59:11.000Z
2016-05-26T14:59:11.000Z
#include <ctime> #include <fstream> #include <iostream> #include <utils.h> #include "EventManager.h" #include "lynxbot.h" EventManager::EventManager(ConfigReader *cfgr) : cfg(cfgr), messages_active(false) { read_messages(); messages_active = message_list.size() > 0; } EventManager::~EventManager() {} /* active: return true if recurring messages are active */ bool EventManager::active() { return messages_active; } /* activate: enable recurring messages */ void EventManager::activate() { messages_active = true; } /* deactivate: disable recurring messages */ void EventManager::deactivate() { messages_active = false; } /* addmsg: add a recurring message */ bool EventManager::addmsg(const char *msg, time_t cd, bool write) { if (message_list.size() >= 5 || cd % 300 != 0 || cd > 3600) return false; message_list.push_back({ std::string(msg), cd }); reload_messages(); if (write) write_messages(); return true; } /* delmsg: delete a recurring message */ bool EventManager::delmsg(size_t id) { if (id < 1 || id > message_list.size()) return false; auto it = message_list.begin() + (id - 1); message_list.erase(it); reload_messages(); write_messages(); return true; } /* editmsg: modify recurring message id */ bool EventManager::editmsg(size_t id, const char *msg, time_t cd) { if (id < 1 || id > message_list.size()) return false; auto &pair = message_list[id - 1]; if (msg) pair.first = std::string(msg); if (cd != -1) { pair.second = cd; reload_messages(); } write_messages(); return true; } /* msglist: return a formatted string of all messages and intervals */ std::string EventManager::msglist() const { std::string output = "("; output += messages_active ? "active" : "inactive"; output += ") "; for (size_t i = 0; i < message_list.size(); ++i) { /* only display first 35 characters of each message */ output += std::to_string(i + 1) + ": " + message(i, 35) + (i == message_list.size() - 1 ? "" : ", "); } if (message_list.empty()) output += "No recurring messages exist."; return output; } /* message: return a single message and its interval */ std::string EventManager::message(size_t id, int lim) const { std::string output; const std::string &msg = message_list[id].first; if (lim == -1) output += msg; else output += msg.length() < (size_t)lim ? msg : (msg.substr(0, lim - 3) + "..."); output += " [" + std::to_string(message_list[id].second / 60) + "m]"; return output; } /* messages: return a pointer to messages vector */ std::vector<std::pair<std::string, time_t>> *EventManager::messages() { return &message_list; } /* read_messages: read recurring messages from file */ void EventManager::read_messages() { size_t i, max; bool error, valid; uint32_t cd; std::string err; std::vector<std::unordered_map<std::string, std::string>> &recurring = cfg->olist()["recurring"]; max = recurring.size(); if (max > 5) { max = 5; printf("%s: only reading first five messages\n", cfg->path()); } error = false; for (i = 0; i < max; ++i) { valid = true; auto map = recurring[i]; if (map.find("message") == map.end()) { err = "no message provided"; valid = false; } if (map.find("period") == map.end()) { err = "no period provided"; valid = false; } if (valid) { if (!utils::parse_int(cd, map["period"], err)) { valid = false; } else if (!addmsg(map["message"].c_str(), cd * 60, false)) { err = "cooldown must be multiple of 5 minutes " "and no longer than 60 minutes"; valid = false; } } if (!valid) { error = true; fprintf(stderr, "%s: recurring message %lu: %s\n" "skipping message\n", cfg->path(), i + 1, err.c_str()); continue; } } if (error) WAIT_INPUT(); } /* write_messages: write recurring messages to file */ void EventManager::write_messages() { std::vector<std::unordered_map<std::string, std::string>> &recurring = cfg->olist()["recurring"]; recurring.clear(); for (auto &p : message_list) { std::unordered_map<std::string, std::string> map; map["message"] = p.first; map["period"] = std::to_string(p.second / 60); recurring.emplace_back(map); } cfg->write(); } /* reload_messages: load all messages into timer */ void EventManager::reload_messages() { for (std::vector<std::string>::size_type i = 0; i < message_list.size(); ++i) { /* update offsets for all existing messages and new message */ std::string name = "msg" + std::to_string(i); remove(name); uint16_t offset = static_cast<uint16_t>(i * (300 / message_list.size())); add(name, message_list[i].second, time(nullptr) + offset); } }
23.688776
71
0.646349
[ "vector" ]
041246b40d6764dfc828e8e3496f83a38f477f3b
52,177
cpp
C++
app/src/main/jni/Main.cpp
Hyupai/Classloader-by-S4J
44e4c5101ce9acb1ce444fe68bf2340d78a8ce37
[ "Apache-2.0" ]
5
2022-03-10T18:40:49.000Z
2022-03-13T14:24:54.000Z
app/src/main/jni/Main.cpp
Hyupai/Classloader-by-S4J
44e4c5101ce9acb1ce444fe68bf2340d78a8ce37
[ "Apache-2.0" ]
null
null
null
app/src/main/jni/Main.cpp
Hyupai/Classloader-by-S4J
44e4c5101ce9acb1ce444fe68bf2340d78a8ce37
[ "Apache-2.0" ]
1
2022-03-16T01:44:48.000Z
2022-03-16T01:44:48.000Z
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <sstream> #include <jni.h> #include "obfuscate.h" #include "skdversion.h" #include "Logger.h" #include "sha256.h" using namespace std; /* * Thanks to following projects and sources: * * - LGL MOD MENU -> https://github.com/LGLTeam/Android-Mod-Menu * - CLASSLOADER -> https://github.com/Catherine22/ClassLoader * - SERVER AND CONNECTION -> https://github.com/kp7742/PUBGPatcher * */ extern "C" { /// ----- Important Things -------- /// bool CheckOne = false; bool CheckTwo = false; bool Check3 = false; // you need encrypt urlserver using the apk in app folder to setup :) static const char* Parametro1 = OBFUSCATE("key"); static const char* Valor1 = OBFUSCATE("LPNGuhasd654823nskmfdsdoijdskajsdh7248739486"); static const char* ParametroPrincipal = OBFUSCATE("SamuelForJuliana"); static const char* AESKEY = OBFUSCATE("SAMUELFORJULIANA"); static const char* ClassloaderName = NULL; static const char* ToastInfoTexts[] = { OBFUSCATE("Your device need be android 6+, or you dont have allowed permission"), // 0 OBFUSCATE("Please Fill all the fields requireds"), // 1 OBFUSCATE("Invalid given characters or more than 16 chars"), // 2 OBFUSCATE("You dont have permission to make this request") // 3 }; static const char* InitialDialog[] = { OBFUSCATE("This project was made by Samuel Filipe (old Hyupai), do not share this source with others and guarantee your application.\n\nThe version of this project is in honor of a special person to me.\n\nMyTelegram = @HyupaiJoker"), // text OBFUSCATE("Warning"), // title OBFUSCATE("OK") // Button Text }; jobjectArray GetLoginScreenFields(JNIEnv *env, jobject context) { jobjectArray ret; const char *features[] = { OBFUSCATE("Make Login"), // Title OBFUSCATE("Username"), // Username Field OBFUSCATE("Password"), // Password Field OBFUSCATE("Login"), // Button OBFUSCATE("Your Key: "), // keyField }; int Total_Feature = (sizeof features / sizeof features[0]); ret = (jobjectArray) env->NewObjectArray(Total_Feature, env->FindClass(OBFUSCATE("java/lang/String")), env->NewStringUTF("")); for (int i = 0; i < Total_Feature; i++) env->SetObjectArrayElement(ret, i, env->NewStringUTF(features[i])); if(CheckOne) { return (ret); } else { return NULL; } } jobjectArray GetInitialDialogFields(JNIEnv *env, jobject context) { jobjectArray ret; const char *features[] = { InitialDialog[0], // 0 InitialDialog[1], //1 InitialDialog[2] // 2 }; int Total_Feature = (sizeof features / sizeof features[0]); ret = (jobjectArray) env->NewObjectArray(Total_Feature, env->FindClass(OBFUSCATE("java/lang/String")), env->NewStringUTF("")); for (int i = 0; i < Total_Feature; i++) env->SetObjectArrayElement(ret, i, env->NewStringUTF(features[i])); if(CheckOne) { return (ret); } else { return NULL; } } //// --- here code start ---- /// // we can store still 11 values into char dont modify static const char* Storage[] = { OBFUSCATE(""), // 0 OBFUSCATE(""), // 1 OBFUSCATE(""), // 2 OBFUSCATE(""), // 3 OBFUSCATE(""), // 4 OBFUSCATE(""), // 5 OBFUSCATE(""), // 6 OBFUSCATE(""), // 7 OBFUSCATE(""), // 8 OBFUSCATE(""), // 9 OBFUSCATE(""), // 10 OBFUSCATE("") // 11 }; static bool getCheckOneValue() { return CheckOne; } static bool getCheckTwoValue() { return CheckTwo; } static bool getCheck3Value() { return Check3; } /// --- Request.java Fields ---------- /// JNIEXPORT jstring JNICALL Java_com_classloader_s4j_Request_Valor1 (JNIEnv * env, jobject obj) { return env->NewStringUTF(Valor1); } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_Request_Parametro1 (JNIEnv * env, jobject obj) { return env->NewStringUTF(Parametro1); } JNIEXPORT jbyteArray JNICALL Java_com_classloader_s4j_Request_puk (JNIEnv *env, jobject This) { jbyte a[] = {48, -127, -97, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 3, -127, -115, 0, 48, -127, -119, 2, -127, -127, 0, -41, 36, -11, -27, -61, 32, 124, 58, 39, -94, -13, 7, 48, -104, -109, 106, -75, -8, -128, -92, -89, -125, -49, -83, 75, 12, -26, 90, 56, 35, 52, -116, 30, 40, -69, -70, 86, 14, -80, -20, 55, -89, 104, -46, -17, -80, -119, 83, -14, 116, -66, 11, -108, 5, 76, 12, -43, -89, -49, 11, 38, -124, 71, 45, 65, -103, 10, 99, 33, 79, 21, -16, -38, -60, 24, -108, 101, -89, -18, 48, -37, -78, 59, 10, 89, 42, 51, -43, 9, -33, -68, 61, -45, 94, -49, 83, 52, 56, 105, -123, 18, 89, 3, 54, -48, -63, -61, -103, -9, 79, -36, 18, 119, 11, -35, 82, 73, -66, 12, 123, -38, 97, 121, -30, 31, -50, -106, 127, 2, 3, 1, 0, 1}; jbyteArray ret = env->NewByteArray(162); env->SetByteArrayRegion (ret, 0, 162, a); return ret; } JNIEXPORT jbyteArray JNICALL Java_com_classloader_s4j_Request_crt (JNIEnv *env, jobject This) { jbyte a[] = {45, 45, 45, 45, 45, 66, 69, 71, 73, 78, 32, 67, 69, 82, 84, 73, 70, 73, 67, 65, 84, 69, 45, 45, 45, 45, 45, 13, 10, 77, 73, 73, 70, 54, 122, 67, 67, 66, 78, 79, 103, 65, 119, 73, 66, 65, 103, 73, 82, 65, 73, 68, 53, 88, 53, 112, 118, 85, 72, 71, 112, 43, 81, 49, 84, 54, 88, 103, 117, 67, 78, 81, 119, 68, 81, 89, 74, 75, 111, 90, 73, 104, 118, 99, 78, 65, 81, 69, 76, 66, 81, 65, 119, 13, 10, 99, 106, 69, 76, 77, 65, 107, 71, 65, 49, 85, 69, 66, 104, 77, 67, 86, 86, 77, 120, 67, 122, 65, 74, 66, 103, 78, 86, 66, 65, 103, 84, 65, 108, 82, 89, 77, 82, 65, 119, 68, 103, 89, 68, 86, 81, 81, 72, 69, 119, 100, 73, 98, 51, 86, 122, 100, 71, 57, 117, 77, 82, 85, 119, 13, 10, 69, 119, 89, 68, 86, 81, 81, 75, 69, 119, 120, 106, 85, 71, 70, 117, 90, 87, 119, 115, 73, 69, 108, 117, 89, 121, 52, 120, 76, 84, 65, 114, 66, 103, 78, 86, 66, 65, 77, 84, 74, 71, 78, 81, 89, 87, 53, 108, 98, 67, 119, 103, 83, 87, 53, 106, 76, 105, 66, 68, 90, 88, 74, 48, 13, 10, 97, 87, 90, 112, 89, 50, 70, 48, 97, 87, 57, 117, 73, 69, 70, 49, 100, 71, 104, 118, 99, 109, 108, 48, 101, 84, 65, 101, 70, 119, 48, 120, 79, 84, 65, 51, 77, 68, 77, 119, 77, 68, 65, 119, 77, 68, 66, 97, 70, 119, 48, 120, 79, 84, 69, 119, 77, 68, 69, 121, 77, 122, 85, 53, 13, 10, 78, 84, 108, 97, 77, 66, 77, 120, 69, 84, 65, 80, 66, 103, 78, 86, 66, 65, 77, 84, 67, 71, 116, 116, 98, 50, 82, 122, 76, 109, 49, 115, 77, 73, 73, 66, 73, 106, 65, 78, 66, 103, 107, 113, 104, 107, 105, 71, 57, 119, 48, 66, 65, 81, 69, 70, 65, 65, 79, 67, 65, 81, 56, 65, 13, 10, 77, 73, 73, 66, 67, 103, 75, 67, 65, 81, 69, 65, 113, 68, 77, 48, 52, 103, 116, 121, 106, 80, 76, 114, 117, 97, 113, 103, 70, 84, 56, 71, 99, 49, 112, 103, 68, 48, 77, 49, 71, 78, 49, 86, 43, 49, 78, 56, 89, 102, 76, 50, 89, 65, 98, 48, 105, 100, 118, 48, 100, 87, 108, 116, 13, 10, 66, 106, 43, 116, 49, 100, 117, 82, 111, 80, 52, 55, 89, 43, 98, 81, 65, 69, 104, 79, 67, 43, 47, 110, 108, 97, 88, 113, 115, 115, 85, 65, 101, 116, 72, 68, 67, 69, 89, 100, 79, 54, 117, 110, 109, 88, 71, 113, 48, 82, 75, 119, 53, 114, 79, 80, 77, 103, 65, 113, 99, 81, 79, 48, 13, 10, 50, 86, 81, 85, 80, 86, 56, 120, 53, 119, 85, 111, 121, 85, 52, 76, 115, 121, 54, 98, 79, 57, 86, 48, 68, 83, 72, 120, 89, 77, 114, 71, 43, 97, 107, 83, 65, 56, 121, 73, 82, 87, 104, 77, 81, 84, 115, 51, 105, 109, 118, 78, 111, 73, 78, 83, 90, 111, 111, 70, 72, 110, 75, 100, 13, 10, 115, 83, 76, 68, 79, 89, 81, 78, 51, 118, 80, 112, 121, 53, 75, 121, 69, 116, 76, 110, 70, 84, 116, 88, 83, 89, 49, 74, 120, 79, 67, 71, 52, 52, 88, 114, 106, 119, 83, 82, 97, 122, 79, 66, 117, 84, 121, 102, 86, 98, 56, 100, 116, 88, 79, 83, 118, 78, 85, 101, 69, 88, 104, 52, 13, 10, 118, 107, 72, 54, 103, 109, 90, 98, 67, 83, 53, 98, 71, 99, 117, 88, 118, 89, 49, 71, 77, 114, 97, 68, 114, 117, 116, 50, 89, 83, 121, 72, 48, 71, 80, 102, 65, 73, 119, 75, 83, 112, 120, 90, 47, 52, 82, 74, 75, 97, 85, 67, 75, 49, 114, 56, 48, 103, 79, 57, 67, 121, 76, 50, 13, 10, 57, 78, 100, 117, 100, 101, 77, 100, 103, 71, 85, 72, 88, 122, 80, 80, 87, 70, 122, 56, 100, 73, 117, 72, 49, 119, 104, 109, 108, 56, 68, 48, 88, 119, 73, 68, 65, 81, 65, 66, 111, 52, 73, 67, 50, 84, 67, 67, 65, 116, 85, 119, 72, 119, 89, 68, 86, 82, 48, 106, 66, 66, 103, 119, 13, 10, 70, 111, 65, 85, 102, 103, 78, 97, 90, 85, 70, 114, 112, 51, 52, 75, 52, 98, 105, 100, 67, 79, 111, 100, 106, 104, 49, 113, 120, 50, 85, 119, 72, 81, 89, 68, 86, 82, 48, 79, 66, 66, 89, 69, 70, 77, 113, 103, 116, 109, 77, 102, 100, 97, 84, 87, 76, 108, 97, 107, 72, 107, 99, 116, 13, 10, 83, 112, 72, 77, 70, 122, 69, 48, 77, 65, 52, 71, 65, 49, 85, 100, 68, 119, 69, 66, 47, 119, 81, 69, 65, 119, 73, 70, 111, 68, 65, 77, 66, 103, 78, 86, 72, 82, 77, 66, 65, 102, 56, 69, 65, 106, 65, 65, 77, 66, 48, 71, 65, 49, 85, 100, 74, 81, 81, 87, 77, 66, 81, 71, 13, 10, 67, 67, 115, 71, 65, 81, 85, 70, 66, 119, 77, 66, 66, 103, 103, 114, 66, 103, 69, 70, 66, 81, 99, 68, 65, 106, 66, 80, 66, 103, 78, 86, 72, 83, 65, 69, 83, 68, 66, 71, 77, 68, 111, 71, 67, 121, 115, 71, 65, 81, 81, 66, 115, 106, 69, 66, 65, 103, 73, 48, 77, 67, 115, 119, 13, 10, 75, 81, 89, 73, 75, 119, 89, 66, 66, 81, 85, 72, 65, 103, 69, 87, 72, 87, 104, 48, 100, 72, 66, 122, 79, 105, 56, 118, 99, 50, 86, 106, 100, 88, 74, 108, 76, 109, 78, 118, 98, 87, 57, 107, 98, 121, 53, 106, 98, 50, 48, 118, 81, 49, 66, 84, 77, 65, 103, 71, 66, 109, 101, 66, 13, 10, 68, 65, 69, 67, 65, 84, 66, 77, 66, 103, 78, 86, 72, 82, 56, 69, 82, 84, 66, 68, 77, 69, 71, 103, 80, 54, 65, 57, 104, 106, 116, 111, 100, 72, 82, 119, 79, 105, 56, 118, 89, 51, 74, 115, 76, 109, 78, 118, 98, 87, 57, 107, 98, 50, 78, 104, 76, 109, 78, 118, 98, 83, 57, 106, 13, 10, 85, 71, 70, 117, 90, 87, 120, 74, 98, 109, 78, 68, 90, 88, 74, 48, 97, 87, 90, 112, 89, 50, 70, 48, 97, 87, 57, 117, 81, 88, 86, 48, 97, 71, 57, 121, 97, 88, 82, 53, 76, 109, 78, 121, 98, 68, 66, 57, 66, 103, 103, 114, 66, 103, 69, 70, 66, 81, 99, 66, 65, 81, 82, 120, 13, 10, 77, 71, 56, 119, 82, 119, 89, 73, 75, 119, 89, 66, 66, 81, 85, 72, 77, 65, 75, 71, 79, 50, 104, 48, 100, 72, 65, 54, 76, 121, 57, 106, 99, 110, 81, 117, 89, 50, 57, 116, 98, 50, 82, 118, 89, 50, 69, 117, 89, 50, 57, 116, 76, 50, 78, 81, 89, 87, 53, 108, 98, 69, 108, 117, 13, 10, 89, 48, 78, 108, 99, 110, 82, 112, 90, 109, 108, 106, 89, 88, 82, 112, 98, 50, 53, 66, 100, 88, 82, 111, 98, 51, 74, 112, 100, 72, 107, 117, 89, 51, 74, 48, 77, 67, 81, 71, 67, 67, 115, 71, 65, 81, 85, 70, 66, 122, 65, 66, 104, 104, 104, 111, 100, 72, 82, 119, 79, 105, 56, 118, 13, 10, 98, 50, 78, 122, 99, 67, 53, 106, 98, 50, 49, 118, 90, 71, 57, 106, 89, 83, 53, 106, 98, 50, 48, 119, 77, 65, 89, 68, 86, 82, 48, 82, 66, 67, 107, 119, 74, 52, 73, 73, 97, 50, 49, 118, 90, 72, 77, 117, 98, 87, 121, 67, 68, 87, 49, 104, 97, 87, 119, 117, 97, 50, 49, 118, 13, 10, 90, 72, 77, 117, 98, 87, 121, 67, 68, 72, 100, 51, 100, 121, 53, 114, 98, 87, 57, 107, 99, 121, 53, 116, 98, 68, 67, 67, 65, 81, 81, 71, 67, 105, 115, 71, 65, 81, 81, 66, 49, 110, 107, 67, 66, 65, 73, 69, 103, 102, 85, 69, 103, 102, 73, 65, 56, 65, 66, 50, 65, 76, 118, 90, 13, 10, 51, 55, 119, 102, 105, 110, 71, 49, 107, 53, 81, 106, 108, 54, 113, 83, 101, 48, 99, 52, 86, 53, 85, 75, 113, 49, 76, 111, 71, 112, 67, 87, 90, 68, 97, 79, 72, 116, 71, 70, 65, 65, 65, 66, 97, 55, 108, 90, 120, 106, 81, 65, 65, 65, 81, 68, 65, 69, 99, 119, 82, 81, 73, 104, 13, 10, 65, 79, 87, 50, 80, 65, 114, 105, 114, 77, 84, 54, 57, 116, 75, 52, 112, 107, 121, 50, 108, 108, 74, 84, 51, 112, 117, 79, 77, 122, 76, 114, 106, 73, 87, 82, 52, 119, 71, 54, 119, 72, 104, 49, 65, 105, 65, 116, 117, 107, 121, 114, 78, 111, 71, 86, 90, 65, 87, 115, 43, 50, 74, 101, 13, 10, 65, 107, 57, 107, 87, 76, 104, 57, 76, 72, 121, 104, 98, 66, 80, 43, 49, 66, 83, 68, 121, 50, 74, 71, 100, 119, 66, 50, 65, 72, 82, 43, 50, 111, 77, 120, 114, 84, 77, 81, 107, 83, 71, 99, 122, 105, 86, 80, 81, 110, 68, 67, 118, 47, 49, 101, 81, 105, 65, 73, 120, 106, 99, 49, 13, 10, 101, 101, 89, 81, 101, 56, 120, 87, 65, 65, 65, 66, 97, 55, 108, 90, 120, 108, 77, 65, 65, 65, 81, 68, 65, 69, 99, 119, 82, 81, 73, 103, 81, 102, 103, 118, 90, 66, 85, 80, 100, 102, 122, 119, 100, 67, 83, 67, 101, 118, 77, 80, 75, 52, 79, 57, 105, 80, 111, 101, 101, 75, 98, 74, 13, 10, 67, 120, 56, 85, 89, 69, 109, 74, 105, 109, 111, 67, 73, 81, 68, 121, 120, 107, 43, 113, 98, 104, 85, 70, 54, 49, 89, 53, 114, 79, 68, 117, 47, 52, 122, 72, 118, 116, 116, 105, 53, 66, 56, 85, 114, 120, 65, 73, 109, 82, 109, 86, 52, 115, 65, 85, 117, 68, 65, 78, 66, 103, 107, 113, 13, 10, 104, 107, 105, 71, 57, 119, 48, 66, 65, 81, 115, 70, 65, 65, 79, 67, 65, 81, 69, 65, 70, 72, 116, 51, 47, 102, 87, 115, 80, 111, 110, 47, 55, 74, 81, 72, 84, 50, 66, 76, 82, 111, 50, 112, 55, 103, 111, 73, 73, 51, 52, 112, 115, 121, 103, 67, 50, 55, 72, 106, 87, 120, 110, 109, 13, 10, 57, 50, 121, 102, 107, 74, 68, 106, 113, 87, 99, 90, 56, 110, 79, 48, 113, 73, 114, 116, 100, 79, 85, 84, 103, 114, 115, 108, 82, 83, 89, 67, 111, 71, 97, 108, 111, 49, 119, 90, 81, 54, 107, 73, 71, 89, 117, 71, 115, 97, 89, 121, 110, 71, 78, 68, 67, 56, 109, 47, 86, 76, 52, 75, 13, 10, 116, 72, 65, 110, 120, 108, 49, 79, 106, 49, 105, 68, 77, 117, 43, 48, 89, 115, 113, 114, 69, 80, 72, 107, 78, 111, 81, 109, 118, 99, 108, 47, 75, 86, 88, 74, 47, 121, 74, 122, 68, 56, 118, 114, 69, 74, 47, 107, 110, 103, 55, 106, 51, 85, 51, 101, 115, 122, 98, 114, 69, 71, 117, 90, 13, 10, 79, 54, 77, 122, 105, 90, 47, 54, 121, 105, 56, 56, 108, 65, 109, 65, 81, 71, 79, 103, 105, 84, 108, 76, 117, 113, 69, 68, 97, 110, 57, 112, 107, 116, 76, 72, 78, 55, 84, 115, 82, 53, 85, 50, 119, 84, 103, 68, 112, 50, 111, 83, 114, 116, 50, 52, 110, 49, 111, 90, 116, 47, 115, 117, 13, 10, 49, 53, 66, 47, 82, 119, 55, 97, 116, 74, 78, 43, 49, 66, 110, 83, 43, 47, 102, 81, 108, 51, 98, 118, 57, 80, 97, 108, 56, 48, 65, 80, 66, 88, 107, 121, 100, 97, 90, 109, 50, 90, 120, 86, 68, 103, 49, 65, 83, 105, 47, 118, 119, 120, 55, 68, 49, 106, 104, 101, 71, 81, 111, 100, 13, 10, 56, 66, 115, 88, 48, 53, 110, 80, 73, 83, 51, 68, 111, 97, 79, 83, 121, 85, 76, 83, 106, 66, 76, 120, 109, 111, 51, 111, 86, 81, 106, 69, 55, 116, 48, 106, 99, 115, 66, 47, 87, 65, 61, 61, 13, 10, 45, 45, 45, 45, 45, 69, 78, 68, 32, 67, 69, 82, 84, 73, 70, 73, 67, 65, 84, 69, 45, 45, 45, 45, 45}; jbyteArray ret = env->NewByteArray(2146); env->SetByteArrayRegion (ret, 0, 2146, a); return ret; } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_Request_CheckOne (JNIEnv * env, jobject obj) { CheckOne = true; return env->NewStringUTF("Checked!"); } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_Request_ParametroPrincipal (JNIEnv * env, jobject obj) { CheckOne = true; LOGI("Checked One"); return env->NewStringUTF(ParametroPrincipal); } //// ----- s4J.java fields --------------- /// std::string jstring2string(JNIEnv *env, jstring jStr) { if (!jStr) return ""; const jclass stringClass = env->GetObjectClass(jStr); const jmethodID getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B"); const jbyteArray stringJbytes = (jbyteArray) env->CallObjectMethod(jStr, getBytes, env->NewStringUTF("UTF-8")); size_t length = (size_t) env->GetArrayLength(stringJbytes); jbyte* pBytes = env->GetByteArrayElements(stringJbytes, NULL); std::string ret = std::string((char *)pBytes, length); env->ReleaseByteArrayElements(stringJbytes, pBytes, JNI_ABORT); env->DeleteLocalRef(stringJbytes); env->DeleteLocalRef(stringClass); return ret; } JNIEXPORT jbyteArray JNICALL Java_com_classloader_s4j_S4J_puk (JNIEnv *env, jobject This) { jbyte a[] = {48, -127, -97, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 3, -127, -115, 0, 48, -127, -119, 2, -127, -127, 0, -41, 36, -11, -27, -61, 32, 124, 58, 39, -94, -13, 7, 48, -104, -109, 106, -75, -8, -128, -92, -89, -125, -49, -83, 75, 12, -26, 90, 56, 35, 52, -116, 30, 40, -69, -70, 86, 14, -80, -20, 55, -89, 104, -46, -17, -80, -119, 83, -14, 116, -66, 11, -108, 5, 76, 12, -43, -89, -49, 11, 38, -124, 71, 45, 65, -103, 10, 99, 33, 79, 21, -16, -38, -60, 24, -108, 101, -89, -18, 48, -37, -78, 59, 10, 89, 42, 51, -43, 9, -33, -68, 61, -45, 94, -49, 83, 52, 56, 105, -123, 18, 89, 3, 54, -48, -63, -61, -103, -9, 79, -36, 18, 119, 11, -35, 82, 73, -66, 12, 123, -38, 97, 121, -30, 31, -50, -106, 127, 2, 3, 1, 0, 1}; jbyteArray ret = env->NewByteArray(162); env->SetByteArrayRegion (ret, 0, 162, a); return ret; } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_S4J_CheckTwo (JNIEnv * env, jobject obj) { CheckTwo = true; return env->NewStringUTF("Checked Two!"); } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_S4J_Check3 (JNIEnv * env, jobject obj) { Check3 = true; return env->NewStringUTF("Checked 3!"); } JNIEXPORT void JNICALL Java_com_classloader_s4j_S4J_SetApkName (JNIEnv * env, jobject obj, jstring apkname) { if(Check3) { ClassloaderName = env->GetStringUTFChars(apkname, 0); } return; } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_S4J_GetApkName (JNIEnv * env, jobject obj, jstring apkname) { if(Check3) { return env->NewStringUTF(ClassloaderName); } else { return NULL; } } void AlertDialog( JNIEnv *env, jobject ctx, jobject clicklistener){ jclass Alert = env->FindClass(OBFUSCATE("android/app/AlertDialog$Builder")); jmethodID AlertCons = env->GetMethodID(Alert, OBFUSCATE("<init>"), OBFUSCATE("(Landroid/content/Context;)V")); jobject MainAlert = env->NewObject(Alert, AlertCons, ctx); jmethodID setTitle = env->GetMethodID(Alert, OBFUSCATE("setTitle"), OBFUSCATE("(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;")); env->CallObjectMethod(MainAlert, setTitle, env->NewStringUTF(OBFUSCATE("Welcome - Info"))); jmethodID setMsg = env->GetMethodID(Alert, OBFUSCATE("setMessage"), OBFUSCATE("(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;")); env->CallObjectMethod(MainAlert, setMsg, env->NewStringUTF(Storage[3])); jmethodID setCa = env->GetMethodID(Alert, OBFUSCATE("setCancelable"), OBFUSCATE("(Z)Landroid/app/AlertDialog$Builder;")); env->CallObjectMethod(MainAlert, setCa, false); jmethodID setPB = env->GetMethodID(Alert, OBFUSCATE("setPositiveButton"), OBFUSCATE("(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;")); env->CallObjectMethod(MainAlert, setPB, env->NewStringUTF("Continue"), static_cast<jobject>(clicklistener)); jmethodID create = env->GetMethodID(Alert, OBFUSCATE("create"), OBFUSCATE("()Landroid/app/AlertDialog;")); jobject creaetob = env->CallObjectMethod(MainAlert, create); jclass AlertN = env->FindClass(OBFUSCATE("android/app/AlertDialog")); jmethodID show = env->GetMethodID(AlertN, OBFUSCATE("show"), OBFUSCATE("()V")); env->CallVoidMethod(creaetob, show); } jobject AlertDialogGif( JNIEnv *env, jobject ctx, jint gif, jobject clicklistener1, jobject clicklistener2){ jclass Alert = env->FindClass(OBFUSCATE("com/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder")); jmethodID AlertCons = env->GetMethodID(Alert, OBFUSCATE("<init>"), OBFUSCATE("(Landroid/app/Activity;)V")); jobject MainAlert = env->NewObject(Alert, AlertCons, ctx); jmethodID setTitle = env->GetMethodID(Alert, OBFUSCATE("setTitle"), OBFUSCATE("(Ljava/lang/String;)Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder;")); env->CallObjectMethod(MainAlert, setTitle, env->NewStringUTF(OBFUSCATE("Welcome - Info"))); jmethodID setMsg = env->GetMethodID(Alert, OBFUSCATE("setMessage"), OBFUSCATE("(Ljava/lang/String;)Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder;")); env->CallObjectMethod(MainAlert, setMsg, env->NewStringUTF(Storage[3])); jmethodID setCa = env->GetMethodID(Alert, OBFUSCATE("isCancellable"), OBFUSCATE("(Z)Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder;")); env->CallObjectMethod(MainAlert, setCa, false); jmethodID setBtn1 = env->GetMethodID(Alert, OBFUSCATE("setPositiveBtnText"), OBFUSCATE("(Ljava/lang/String;)Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder;")); env->CallObjectMethod(MainAlert, setBtn1, env->NewStringUTF("Continue")); jmethodID setBtn2 = env->GetMethodID(Alert, OBFUSCATE("setNegativeBtnText"), OBFUSCATE("(Ljava/lang/String;)Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder;")); env->CallObjectMethod(MainAlert, setBtn2, env->NewStringUTF("Cancel")); jmethodID setBtn2Color = env->GetMethodID(Alert, OBFUSCATE("setNegativeBtnBackground"), OBFUSCATE("(Ljava/lang/String;)Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder;")); env->CallObjectMethod(MainAlert, setBtn2Color, env->NewStringUTF("#FF0000")); jmethodID setBtn1Color = env->GetMethodID(Alert, OBFUSCATE("setPositiveBtnBackground"), OBFUSCATE("(Ljava/lang/String;)Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder;")); env->CallObjectMethod(MainAlert, setBtn1Color, env->NewStringUTF("#22b573")); jmethodID setGif = env->GetMethodID(Alert, OBFUSCATE("setGifResource"), OBFUSCATE("(I)Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder;")); env->CallObjectMethod(MainAlert, setGif, gif); jmethodID setPB = env->GetMethodID(Alert, OBFUSCATE("OnPositiveClicked"), OBFUSCATE("(Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialogListener;)Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder;")); env->CallObjectMethod(MainAlert, setPB, static_cast<jobject>(clicklistener1)); jmethodID setPB2 = env->GetMethodID(Alert, OBFUSCATE("OnNegativeClicked"), OBFUSCATE("(Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialogListener;)Lcom/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder;")); env->CallObjectMethod(MainAlert, setPB2, static_cast<jobject>(clicklistener2)); return MainAlert; } JNIEXPORT jobject JNICALL Java_com_classloader_s4j_S4J_InitAlert (JNIEnv * env, jobject obj, jobject ctx, jint gifif, jobject clicklistener1, jobject clicklistener2) { if(Check3) { return AlertDialogGif(env, ctx, gifif, clicklistener1, clicklistener2); } else { return NULL; } } std::string getPublicStaticString(JNIEnv *env, const char *className, const char *fieldName) { jclass clazz = env->FindClass(className); if (clazz != nullptr) { jfieldID fid = env->GetStaticFieldID(clazz, fieldName, "Ljava/lang/String;"); if (fid != nullptr) { jstring GladioReceiver = (jstring) env->GetStaticObjectField(clazz, fid); jboolean blnIsCopy; std::string mystr = env->GetStringUTFChars(GladioReceiver, &blnIsCopy); return mystr; } } return "ERROR"; } std::string CreateDeviceUniqueID(JNIEnv *env) { std::string strReturn; std::string board = getPublicStaticString(env, "android/os/Build", "BOARD"); std::string brand = getPublicStaticString(env, "android/os/Build", "BRAND"); std::string display = getPublicStaticString(env, "android/os/Build", "DISPLAY"); std::string device = getPublicStaticString(env, "android/os/Build", "DEVICE"); std::string manufacturer = getPublicStaticString(env, "android/os/Build", "MANUFACTURER"); std::string model = getPublicStaticString(env, "android/os/Build", "MODEL"); std::string product = getPublicStaticString(env, "android/os/Build", "PRODUCT"); int mod = 10; int a1 = ((int) board.size()) % mod; int a2 = ((int) brand.size()) % mod; int a3 = ((int) display.size()) % mod; int a4 = ((int) device.size()) % mod; int a5 = ((int) manufacturer.size()) % mod; int a6 = ((int) model.size()) % mod; int a7 = ((int) product.size()) % mod; strReturn = "35" + std::to_string(a1) + std::to_string(a2) + std::to_string(a3) + std::to_string(a4) + std::to_string(a5) + std::to_string(a6) + std::to_string(a7); return strReturn; } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_S4J_getDeviceID (JNIEnv *env, jobject This, jobject context) { const int ANDROID_ID_SIZE = 15; const char *settings_name = "android/provider/Settings$Secure"; const char *context_name = "android/content/Context"; jclass class_settings_secure = env->FindClass(settings_name); jclass class_context = env->FindClass(context_name); if(class_settings_secure == nullptr || class_context == nullptr){ return env->NewStringUTF("Not found!"); } //Get the getContentResolver method jmethodID m_get_content_resolver = env->GetMethodID( class_context, "getContentResolver", "()Landroid/content/ContentResolver;"); if(m_get_content_resolver == nullptr){ return env->NewStringUTF("Not found ContentResolver"); } // get Secure.ANDROID_ID jfieldID f_android_id = env->GetStaticFieldID(class_settings_secure, "ANDROID_ID", "Ljava/lang/String;"); if(f_android_id == nullptr){ return env->NewStringUTF("Not found ANDROID_ID field"); } jobject s_android_id = env->GetStaticObjectField(class_settings_secure, f_android_id); //create a ContentResolver instance context.getContentResolver() jobject o_content_resolver = env->CallObjectMethod(context, m_get_content_resolver); if(o_content_resolver == nullptr || s_android_id == nullptr){ return env->NewStringUTF("Not create content resolver instance!"); } //get the method getString jmethodID m_get_string = env->GetStaticMethodID( class_settings_secure, "getString", "(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;"); if(m_get_string == nullptr){ return env->NewStringUTF("Not create content resolver instance string!"); } //get the Android ID auto android_id = (jstring) env->CallStaticObjectMethod(class_settings_secure, m_get_string, o_content_resolver, s_android_id); // generate SHA-256 from ANDROID_ID jboolean isCopy; const char *convertedValue = env->GetStringUTFChars(android_id, &isCopy); string src_comp = "(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;"; string src_str = string(convertedValue, ANDROID_ID_SIZE) + CreateDeviceUniqueID(env); //vector<unsigned char> hash(picosha2::k_digest_size); //picosha2::hash256(src_str.begin(), src_str.end(), hash.begin(), hash.end()); //string hex_str = picosha2::bytes_to_hex_string(hash.begin(), hash.end()); return env->NewStringUTF(src_str.c_str()); } JNIEXPORT jbyteArray JNICALL Java_com_classloader_s4j_S4J_crt (JNIEnv *env, jobject This) { jbyte a[] = {45, 45, 45, 45, 45, 66, 69, 71, 73, 78, 32, 67, 69, 82, 84, 73, 70, 73, 67, 65, 84, 69, 45, 45, 45, 45, 45, 13, 10, 77, 73, 73, 70, 54, 122, 67, 67, 66, 78, 79, 103, 65, 119, 73, 66, 65, 103, 73, 82, 65, 73, 68, 53, 88, 53, 112, 118, 85, 72, 71, 112, 43, 81, 49, 84, 54, 88, 103, 117, 67, 78, 81, 119, 68, 81, 89, 74, 75, 111, 90, 73, 104, 118, 99, 78, 65, 81, 69, 76, 66, 81, 65, 119, 13, 10, 99, 106, 69, 76, 77, 65, 107, 71, 65, 49, 85, 69, 66, 104, 77, 67, 86, 86, 77, 120, 67, 122, 65, 74, 66, 103, 78, 86, 66, 65, 103, 84, 65, 108, 82, 89, 77, 82, 65, 119, 68, 103, 89, 68, 86, 81, 81, 72, 69, 119, 100, 73, 98, 51, 86, 122, 100, 71, 57, 117, 77, 82, 85, 119, 13, 10, 69, 119, 89, 68, 86, 81, 81, 75, 69, 119, 120, 106, 85, 71, 70, 117, 90, 87, 119, 115, 73, 69, 108, 117, 89, 121, 52, 120, 76, 84, 65, 114, 66, 103, 78, 86, 66, 65, 77, 84, 74, 71, 78, 81, 89, 87, 53, 108, 98, 67, 119, 103, 83, 87, 53, 106, 76, 105, 66, 68, 90, 88, 74, 48, 13, 10, 97, 87, 90, 112, 89, 50, 70, 48, 97, 87, 57, 117, 73, 69, 70, 49, 100, 71, 104, 118, 99, 109, 108, 48, 101, 84, 65, 101, 70, 119, 48, 120, 79, 84, 65, 51, 77, 68, 77, 119, 77, 68, 65, 119, 77, 68, 66, 97, 70, 119, 48, 120, 79, 84, 69, 119, 77, 68, 69, 121, 77, 122, 85, 53, 13, 10, 78, 84, 108, 97, 77, 66, 77, 120, 69, 84, 65, 80, 66, 103, 78, 86, 66, 65, 77, 84, 67, 71, 116, 116, 98, 50, 82, 122, 76, 109, 49, 115, 77, 73, 73, 66, 73, 106, 65, 78, 66, 103, 107, 113, 104, 107, 105, 71, 57, 119, 48, 66, 65, 81, 69, 70, 65, 65, 79, 67, 65, 81, 56, 65, 13, 10, 77, 73, 73, 66, 67, 103, 75, 67, 65, 81, 69, 65, 113, 68, 77, 48, 52, 103, 116, 121, 106, 80, 76, 114, 117, 97, 113, 103, 70, 84, 56, 71, 99, 49, 112, 103, 68, 48, 77, 49, 71, 78, 49, 86, 43, 49, 78, 56, 89, 102, 76, 50, 89, 65, 98, 48, 105, 100, 118, 48, 100, 87, 108, 116, 13, 10, 66, 106, 43, 116, 49, 100, 117, 82, 111, 80, 52, 55, 89, 43, 98, 81, 65, 69, 104, 79, 67, 43, 47, 110, 108, 97, 88, 113, 115, 115, 85, 65, 101, 116, 72, 68, 67, 69, 89, 100, 79, 54, 117, 110, 109, 88, 71, 113, 48, 82, 75, 119, 53, 114, 79, 80, 77, 103, 65, 113, 99, 81, 79, 48, 13, 10, 50, 86, 81, 85, 80, 86, 56, 120, 53, 119, 85, 111, 121, 85, 52, 76, 115, 121, 54, 98, 79, 57, 86, 48, 68, 83, 72, 120, 89, 77, 114, 71, 43, 97, 107, 83, 65, 56, 121, 73, 82, 87, 104, 77, 81, 84, 115, 51, 105, 109, 118, 78, 111, 73, 78, 83, 90, 111, 111, 70, 72, 110, 75, 100, 13, 10, 115, 83, 76, 68, 79, 89, 81, 78, 51, 118, 80, 112, 121, 53, 75, 121, 69, 116, 76, 110, 70, 84, 116, 88, 83, 89, 49, 74, 120, 79, 67, 71, 52, 52, 88, 114, 106, 119, 83, 82, 97, 122, 79, 66, 117, 84, 121, 102, 86, 98, 56, 100, 116, 88, 79, 83, 118, 78, 85, 101, 69, 88, 104, 52, 13, 10, 118, 107, 72, 54, 103, 109, 90, 98, 67, 83, 53, 98, 71, 99, 117, 88, 118, 89, 49, 71, 77, 114, 97, 68, 114, 117, 116, 50, 89, 83, 121, 72, 48, 71, 80, 102, 65, 73, 119, 75, 83, 112, 120, 90, 47, 52, 82, 74, 75, 97, 85, 67, 75, 49, 114, 56, 48, 103, 79, 57, 67, 121, 76, 50, 13, 10, 57, 78, 100, 117, 100, 101, 77, 100, 103, 71, 85, 72, 88, 122, 80, 80, 87, 70, 122, 56, 100, 73, 117, 72, 49, 119, 104, 109, 108, 56, 68, 48, 88, 119, 73, 68, 65, 81, 65, 66, 111, 52, 73, 67, 50, 84, 67, 67, 65, 116, 85, 119, 72, 119, 89, 68, 86, 82, 48, 106, 66, 66, 103, 119, 13, 10, 70, 111, 65, 85, 102, 103, 78, 97, 90, 85, 70, 114, 112, 51, 52, 75, 52, 98, 105, 100, 67, 79, 111, 100, 106, 104, 49, 113, 120, 50, 85, 119, 72, 81, 89, 68, 86, 82, 48, 79, 66, 66, 89, 69, 70, 77, 113, 103, 116, 109, 77, 102, 100, 97, 84, 87, 76, 108, 97, 107, 72, 107, 99, 116, 13, 10, 83, 112, 72, 77, 70, 122, 69, 48, 77, 65, 52, 71, 65, 49, 85, 100, 68, 119, 69, 66, 47, 119, 81, 69, 65, 119, 73, 70, 111, 68, 65, 77, 66, 103, 78, 86, 72, 82, 77, 66, 65, 102, 56, 69, 65, 106, 65, 65, 77, 66, 48, 71, 65, 49, 85, 100, 74, 81, 81, 87, 77, 66, 81, 71, 13, 10, 67, 67, 115, 71, 65, 81, 85, 70, 66, 119, 77, 66, 66, 103, 103, 114, 66, 103, 69, 70, 66, 81, 99, 68, 65, 106, 66, 80, 66, 103, 78, 86, 72, 83, 65, 69, 83, 68, 66, 71, 77, 68, 111, 71, 67, 121, 115, 71, 65, 81, 81, 66, 115, 106, 69, 66, 65, 103, 73, 48, 77, 67, 115, 119, 13, 10, 75, 81, 89, 73, 75, 119, 89, 66, 66, 81, 85, 72, 65, 103, 69, 87, 72, 87, 104, 48, 100, 72, 66, 122, 79, 105, 56, 118, 99, 50, 86, 106, 100, 88, 74, 108, 76, 109, 78, 118, 98, 87, 57, 107, 98, 121, 53, 106, 98, 50, 48, 118, 81, 49, 66, 84, 77, 65, 103, 71, 66, 109, 101, 66, 13, 10, 68, 65, 69, 67, 65, 84, 66, 77, 66, 103, 78, 86, 72, 82, 56, 69, 82, 84, 66, 68, 77, 69, 71, 103, 80, 54, 65, 57, 104, 106, 116, 111, 100, 72, 82, 119, 79, 105, 56, 118, 89, 51, 74, 115, 76, 109, 78, 118, 98, 87, 57, 107, 98, 50, 78, 104, 76, 109, 78, 118, 98, 83, 57, 106, 13, 10, 85, 71, 70, 117, 90, 87, 120, 74, 98, 109, 78, 68, 90, 88, 74, 48, 97, 87, 90, 112, 89, 50, 70, 48, 97, 87, 57, 117, 81, 88, 86, 48, 97, 71, 57, 121, 97, 88, 82, 53, 76, 109, 78, 121, 98, 68, 66, 57, 66, 103, 103, 114, 66, 103, 69, 70, 66, 81, 99, 66, 65, 81, 82, 120, 13, 10, 77, 71, 56, 119, 82, 119, 89, 73, 75, 119, 89, 66, 66, 81, 85, 72, 77, 65, 75, 71, 79, 50, 104, 48, 100, 72, 65, 54, 76, 121, 57, 106, 99, 110, 81, 117, 89, 50, 57, 116, 98, 50, 82, 118, 89, 50, 69, 117, 89, 50, 57, 116, 76, 50, 78, 81, 89, 87, 53, 108, 98, 69, 108, 117, 13, 10, 89, 48, 78, 108, 99, 110, 82, 112, 90, 109, 108, 106, 89, 88, 82, 112, 98, 50, 53, 66, 100, 88, 82, 111, 98, 51, 74, 112, 100, 72, 107, 117, 89, 51, 74, 48, 77, 67, 81, 71, 67, 67, 115, 71, 65, 81, 85, 70, 66, 122, 65, 66, 104, 104, 104, 111, 100, 72, 82, 119, 79, 105, 56, 118, 13, 10, 98, 50, 78, 122, 99, 67, 53, 106, 98, 50, 49, 118, 90, 71, 57, 106, 89, 83, 53, 106, 98, 50, 48, 119, 77, 65, 89, 68, 86, 82, 48, 82, 66, 67, 107, 119, 74, 52, 73, 73, 97, 50, 49, 118, 90, 72, 77, 117, 98, 87, 121, 67, 68, 87, 49, 104, 97, 87, 119, 117, 97, 50, 49, 118, 13, 10, 90, 72, 77, 117, 98, 87, 121, 67, 68, 72, 100, 51, 100, 121, 53, 114, 98, 87, 57, 107, 99, 121, 53, 116, 98, 68, 67, 67, 65, 81, 81, 71, 67, 105, 115, 71, 65, 81, 81, 66, 49, 110, 107, 67, 66, 65, 73, 69, 103, 102, 85, 69, 103, 102, 73, 65, 56, 65, 66, 50, 65, 76, 118, 90, 13, 10, 51, 55, 119, 102, 105, 110, 71, 49, 107, 53, 81, 106, 108, 54, 113, 83, 101, 48, 99, 52, 86, 53, 85, 75, 113, 49, 76, 111, 71, 112, 67, 87, 90, 68, 97, 79, 72, 116, 71, 70, 65, 65, 65, 66, 97, 55, 108, 90, 120, 106, 81, 65, 65, 65, 81, 68, 65, 69, 99, 119, 82, 81, 73, 104, 13, 10, 65, 79, 87, 50, 80, 65, 114, 105, 114, 77, 84, 54, 57, 116, 75, 52, 112, 107, 121, 50, 108, 108, 74, 84, 51, 112, 117, 79, 77, 122, 76, 114, 106, 73, 87, 82, 52, 119, 71, 54, 119, 72, 104, 49, 65, 105, 65, 116, 117, 107, 121, 114, 78, 111, 71, 86, 90, 65, 87, 115, 43, 50, 74, 101, 13, 10, 65, 107, 57, 107, 87, 76, 104, 57, 76, 72, 121, 104, 98, 66, 80, 43, 49, 66, 83, 68, 121, 50, 74, 71, 100, 119, 66, 50, 65, 72, 82, 43, 50, 111, 77, 120, 114, 84, 77, 81, 107, 83, 71, 99, 122, 105, 86, 80, 81, 110, 68, 67, 118, 47, 49, 101, 81, 105, 65, 73, 120, 106, 99, 49, 13, 10, 101, 101, 89, 81, 101, 56, 120, 87, 65, 65, 65, 66, 97, 55, 108, 90, 120, 108, 77, 65, 65, 65, 81, 68, 65, 69, 99, 119, 82, 81, 73, 103, 81, 102, 103, 118, 90, 66, 85, 80, 100, 102, 122, 119, 100, 67, 83, 67, 101, 118, 77, 80, 75, 52, 79, 57, 105, 80, 111, 101, 101, 75, 98, 74, 13, 10, 67, 120, 56, 85, 89, 69, 109, 74, 105, 109, 111, 67, 73, 81, 68, 121, 120, 107, 43, 113, 98, 104, 85, 70, 54, 49, 89, 53, 114, 79, 68, 117, 47, 52, 122, 72, 118, 116, 116, 105, 53, 66, 56, 85, 114, 120, 65, 73, 109, 82, 109, 86, 52, 115, 65, 85, 117, 68, 65, 78, 66, 103, 107, 113, 13, 10, 104, 107, 105, 71, 57, 119, 48, 66, 65, 81, 115, 70, 65, 65, 79, 67, 65, 81, 69, 65, 70, 72, 116, 51, 47, 102, 87, 115, 80, 111, 110, 47, 55, 74, 81, 72, 84, 50, 66, 76, 82, 111, 50, 112, 55, 103, 111, 73, 73, 51, 52, 112, 115, 121, 103, 67, 50, 55, 72, 106, 87, 120, 110, 109, 13, 10, 57, 50, 121, 102, 107, 74, 68, 106, 113, 87, 99, 90, 56, 110, 79, 48, 113, 73, 114, 116, 100, 79, 85, 84, 103, 114, 115, 108, 82, 83, 89, 67, 111, 71, 97, 108, 111, 49, 119, 90, 81, 54, 107, 73, 71, 89, 117, 71, 115, 97, 89, 121, 110, 71, 78, 68, 67, 56, 109, 47, 86, 76, 52, 75, 13, 10, 116, 72, 65, 110, 120, 108, 49, 79, 106, 49, 105, 68, 77, 117, 43, 48, 89, 115, 113, 114, 69, 80, 72, 107, 78, 111, 81, 109, 118, 99, 108, 47, 75, 86, 88, 74, 47, 121, 74, 122, 68, 56, 118, 114, 69, 74, 47, 107, 110, 103, 55, 106, 51, 85, 51, 101, 115, 122, 98, 114, 69, 71, 117, 90, 13, 10, 79, 54, 77, 122, 105, 90, 47, 54, 121, 105, 56, 56, 108, 65, 109, 65, 81, 71, 79, 103, 105, 84, 108, 76, 117, 113, 69, 68, 97, 110, 57, 112, 107, 116, 76, 72, 78, 55, 84, 115, 82, 53, 85, 50, 119, 84, 103, 68, 112, 50, 111, 83, 114, 116, 50, 52, 110, 49, 111, 90, 116, 47, 115, 117, 13, 10, 49, 53, 66, 47, 82, 119, 55, 97, 116, 74, 78, 43, 49, 66, 110, 83, 43, 47, 102, 81, 108, 51, 98, 118, 57, 80, 97, 108, 56, 48, 65, 80, 66, 88, 107, 121, 100, 97, 90, 109, 50, 90, 120, 86, 68, 103, 49, 65, 83, 105, 47, 118, 119, 120, 55, 68, 49, 106, 104, 101, 71, 81, 111, 100, 13, 10, 56, 66, 115, 88, 48, 53, 110, 80, 73, 83, 51, 68, 111, 97, 79, 83, 121, 85, 76, 83, 106, 66, 76, 120, 109, 111, 51, 111, 86, 81, 106, 69, 55, 116, 48, 106, 99, 115, 66, 47, 87, 65, 61, 61, 13, 10, 45, 45, 45, 45, 45, 69, 78, 68, 32, 67, 69, 82, 84, 73, 70, 73, 67, 65, 84, 69, 45, 45, 45, 45, 45}; jbyteArray ret = env->NewByteArray(2146); env->SetByteArrayRegion (ret, 0, 2146, a); return ret; } //// --- Service SetupDex ---- /// JNIEXPORT void JNICALL Java_com_classloader_s4j_SetupDex_CreateFile (JNIEnv *env, jobject thiz) { if(Check3) { jclass base64Class = env->FindClass("android/util/Base64"); jmethodID decode_method = env->GetStaticMethodID(base64Class, "decode", "(Ljava/lang/String;I)[B"); jfieldID fid_no_padding = env->GetStaticFieldID(base64Class, "NO_PADDING", "I"); int i_no_padding = env->GetStaticIntField(base64Class, fid_no_padding); jbyteArray resultArray = (jbyteArray) env-> CallStaticObjectMethod(base64Class, decode_method, env -> NewStringUTF(Storage[6]), i_no_padding ); jclass fileOutputStreamClass = env->FindClass("java/io/FileOutputStream"); jmethodID initFileOutputStreamClassMethod = env->GetMethodID(fileOutputStreamClass, "<init>", "(Ljava/lang/String;)V"); jobject out = env->NewObject(fileOutputStreamClass, initFileOutputStreamClassMethod, env->NewStringUTF(Storage[7])); jmethodID write_method = env->GetMethodID(fileOutputStreamClass, "write", "([B)V"); jmethodID flush_method = env->GetMethodID(fileOutputStreamClass, "flush", "()V"); jmethodID out_close_method = env->GetMethodID(fileOutputStreamClass, "close", "()V"); env-> CallVoidMethod (out, write_method, resultArray ); env-> CallVoidMethod (out, flush_method ); env-> CallVoidMethod (out, out_close_method ); } return; } /// --- MainActivity.java Fields ---- /// std::string EncryptByS4J(std::string strDec) { std::replace( strDec.begin(), strDec.end(), 'a', '+'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'd', '['); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'e', ']'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'h', ';'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'i', '>'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'j', '<'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'm', '?'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'o', '|'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'g', ','); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'p', '!'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'r', '@'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'u', '#'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'b', '$'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'x', '%'); // string velha, string nov std::replace( strDec.begin(), strDec.end(), 'L', '&'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'W', '*'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'R', '('); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'S', ')'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 'H', '-'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '.', '_'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '/', '='); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 't', '{'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), 's', '}'); // string velha, string novo return strDec; } std::string DecryptByS4J(std::string strDec) { std::replace( strDec.begin(), strDec.end(), '+', 'a'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '[', 'd'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), ']', 'e'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), ';', 'h'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '>', 'i'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '<', 'j'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '?', 'm'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '|', 'o'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), ',', 'g'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '!', 'p'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '@', 'r'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '#', 'u'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '$', 'b'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '%', 'x'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '&', 'L'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '*', 'W'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '(', 'R'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), ')', 'S'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '-', 'H'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '_', '.'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '=', '/'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '{', 't'); // string velha, string novo std::replace( strDec.begin(), strDec.end(), '}', 's'); // string velha, string novo return strDec; } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_MainActivity_MYKEY (JNIEnv * env, jobject obj) { /// its so beatiful have exactly 16 Bytes <3 return env->NewStringUTF(AESKEY); } JNIEXPORT jboolean JNICALL Java_com_classloader_s4j_MainActivity_CheckFields (JNIEnv * env, jobject obj, jstring jstr, jstring jstr2) { std::string s1 = jstring2string(env, jstr); std::string s2 = jstring2string(env, jstr2); std::string s01 = "\""; std::string s02 = "\'"; std::string s03 = "="; if(s1.length() > 16 || s2.length() > 16) { return true; } else { return false; } if (s1.find(s01) != std::string::npos || s2.find(s01) != std::string::npos || s1.find(s02) != std::string::npos || s2.find(s02) != std::string::npos || s1.find(s03) != std::string::npos || s2.find(s03) != std::string::npos) { return true; } else { return false; } } JNIEXPORT void JNICALL Java_com_classloader_s4j_MainActivity_Stack (JNIEnv * env, jobject obj, jint inte, jstring str) { Storage[inte] = env->GetStringUTFChars(str, 0); LOGI("Stacked"); return; } JNIEXPORT jboolean JNICALL Java_com_classloader_s4j_MainActivity_getCheckOne (JNIEnv * env, jobject obj) { return getCheckOneValue(); } JNIEXPORT jboolean JNICALL Java_com_classloader_s4j_MainActivity_getCheckTwo (JNIEnv * env, jobject obj) { return getCheckTwoValue(); } JNIEXPORT jboolean JNICALL Java_com_classloader_s4j_MainActivity_getCheck3 (JNIEnv * env, jobject obj) { return getCheck3Value(); } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_MainActivity_getStack (JNIEnv * env, jobject obj, jint inte, jboolean isencript) { if(isencript) { jstring str = env->NewStringUTF(Storage[inte]); std::string strDec = jstring2string(env, str); return env->NewStringUTF(DecryptByS4J(strDec).c_str()); } else { return env->NewStringUTF(Storage[inte]); } } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_MainActivity_Encrypt (JNIEnv * env, jobject obj, jstring str) { std::string strDec = jstring2string(env, str); return env->NewStringUTF(EncryptByS4J(strDec).c_str()); } JNIEXPORT jstring JNICALL Java_com_classloader_s4j_MainActivity_Decrypt (JNIEnv * env, jobject obj, jstring str) { std::string strDec = jstring2string(env, str); return env->NewStringUTF(DecryptByS4J(strDec).c_str()); } /// ----- inicial loading method ----- /// JNIEXPORT jobject JNICALL Java_com_classloader_s4j_MainActivity_InitialLoading (JNIEnv * env, jobject obj, jobject ctx) { jclass Alert = env->FindClass(OBFUSCATE("cn/pedant/SweetAlert/SweetAlertDialog")); jmethodID AlertCons = env->GetMethodID(Alert, OBFUSCATE("<init>"), OBFUSCATE("(Landroid/content/Context;I)V")); jobject MainAlert = env->NewObject(Alert, AlertCons, ctx, 5); return MainAlert ; } JNIEXPORT jobject JNICALL Java_com_classloader_s4j_MainActivity_InitialDialog (JNIEnv * env, jobject obj, jobject ctx) { jclass Alert = env->FindClass(OBFUSCATE("com/bestsoft32/tt_fancy_gif_dialog_lib/TTFancyGifDialog$Builder")); jmethodID AlertCons = env->GetMethodID(Alert, OBFUSCATE("<init>"), OBFUSCATE("(Landroid/app/Activity;)V")); jobject MainAlert = env->NewObject(Alert, AlertCons, ctx); if(CheckOne) { return MainAlert; } else { return NULL; } } } //// --- overlay permission and toast----- /// void Toast(JNIEnv *env, jobject thiz, const char *text, int length) { jstring jstr = env->NewStringUTF(text); jclass toast = env->FindClass(OBFUSCATE("android/widget/Toast")); jmethodID methodMakeText =env->GetStaticMethodID(toast,OBFUSCATE("makeText"),OBFUSCATE("(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;")); jobject toastobj = env->CallStaticObjectMethod(toast, methodMakeText,thiz, jstr, length); jmethodID methodShow = env->GetMethodID(toast, OBFUSCATE("show"), OBFUSCATE("()V")); env->CallVoidMethod(toastobj, methodShow); } void ToastInfo(JNIEnv *env, jobject thiz, const char *text, int length) { jstring jstr = env->NewStringUTF(text); jclass toast = env->FindClass(OBFUSCATE("ir/hatamiarash/toast/RTLToast")); jmethodID methodMakeText =env->GetStaticMethodID(toast,OBFUSCATE("info"),OBFUSCATE("(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;")); jobject toastobj = env->CallStaticObjectMethod(toast, methodMakeText,thiz, jstr, length); jclass AlertN = env->FindClass(OBFUSCATE("android/widget/Toast")); jmethodID show = env->GetMethodID(AlertN, OBFUSCATE("show"), OBFUSCATE("()V")); env->CallVoidMethod(toastobj, show); LOGI("ToastCalled"); } void startActivityPermisson(JNIEnv *env, jobject ctx){ jclass native_context = env->GetObjectClass(ctx); jmethodID startActivity = env->GetMethodID(native_context, OBFUSCATE("startActivity"),OBFUSCATE("(Landroid/content/Intent;)V")); jmethodID pack = env->GetMethodID(native_context, OBFUSCATE("getPackageName"),OBFUSCATE("()Ljava/lang/String;")); jstring packageName = static_cast<jstring>(env->CallObjectMethod(ctx, pack)); const char *pkg = env->GetStringUTFChars(packageName, 0); std::stringstream pkgg; pkgg << OBFUSCATE("package:"); pkgg << pkg; std::string pakg = pkgg.str(); jclass Uri = env->FindClass(OBFUSCATE("android/net/Uri")); jmethodID Parce = env->GetStaticMethodID(Uri, OBFUSCATE("parse"), OBFUSCATE("(Ljava/lang/String;)Landroid/net/Uri;")); jobject UriMethod = env->CallStaticObjectMethod(Uri, Parce, env->NewStringUTF(pakg.c_str())); jclass intentclass = env->FindClass(OBFUSCATE("android/content/Intent")); jmethodID newIntent = env->GetMethodID(intentclass, OBFUSCATE("<init>"), OBFUSCATE("(Ljava/lang/String;Landroid/net/Uri;)V")); jobject intent = env->NewObject(intentclass,newIntent,env->NewStringUTF(OBFUSCATE("android.settings.action.MANAGE_OVERLAY_PERMISSION")), UriMethod); env->CallVoidMethod(ctx, startActivity, intent); } void startService(JNIEnv *env, jobject ctx){ jclass native_context = env->GetObjectClass(ctx); jclass intentClass = env->FindClass(OBFUSCATE("android/content/Intent")); jclass actionString = env->FindClass(OBFUSCATE("com/android/support/Launcher")); jmethodID newIntent = env->GetMethodID(intentClass, OBFUSCATE("<init>"), OBFUSCATE("(Landroid/content/Context;Ljava/lang/Class;)V")); jobject intent = env->NewObject(intentClass,newIntent,ctx,actionString); jmethodID startActivityMethodId = env->GetMethodID(native_context, OBFUSCATE("startService"), OBFUSCATE("(Landroid/content/Intent;)Landroid/content/ComponentName;")); env->CallObjectMethod(ctx, startActivityMethodId, intent); } void *exit_thread(void *) { sleep(5); exit(0); } void CheckOverlayPermission(JNIEnv *env, jclass thiz, jobject ctx){ // LOGI(OBFUSCATE("Check overlay permission")); int sdkVer = api_level(); if (sdkVer >= 23){ //Android 6.0 jclass Settings = env->FindClass(OBFUSCATE("android/provider/Settings")); jmethodID canDraw =env->GetStaticMethodID(Settings, OBFUSCATE("canDrawOverlays"), OBFUSCATE("(Landroid/content/Context;)Z")); if (!env->CallStaticBooleanMethod(Settings, canDraw, ctx)){ startActivityPermisson(env, ctx); ToastInfo(env,ctx,OBFUSCATE("Enable This Permission so Classloader Overlay can be used"),0); pthread_t ptid; pthread_create(&ptid, NULL, exit_thread, NULL); return; } } } bool CanUserOverlayPermission(){ int sdkVer = api_level(); if (sdkVer >= 23){ //Android 6.0 return true; } else { return false; } } int VerifyOverlayPermission(JNIEnv *env, jclass thiz, jobject ctx){ int sdkVer = api_level(); if (sdkVer >= 23){ //Android 6.0 jclass Settings = env->FindClass(OBFUSCATE("android/provider/Settings")); jmethodID canDraw =env->GetStaticMethodID(Settings, OBFUSCATE("canDrawOverlays"), OBFUSCATE("(Landroid/content/Context;)Z")); if (!env->CallStaticBooleanMethod(Settings, canDraw, ctx)){ return 2; } else { return 1; } } else { return 3; } } void ToastInfo2(JNIEnv *env, jclass thiz, jobject ctx, int textid, int duration) { ToastInfo(env,ctx,ToastInfoTexts[textid],duration); } int RegisterMethods1(JNIEnv *env) { JNINativeMethod methods[] = { {OBFUSCATE("CheckOverlayPermission"), OBFUSCATE("(Landroid/content/Context;)V"), reinterpret_cast<void *>(CheckOverlayPermission)}, {OBFUSCATE("CanUserOverlayPermission"), OBFUSCATE("()Z"), reinterpret_cast<void *>(CanUserOverlayPermission)}, {OBFUSCATE("VerifyOverlayPermission"), OBFUSCATE("(Landroid/content/Context;)I"), reinterpret_cast<void *>(VerifyOverlayPermission)}, {OBFUSCATE("ToastInfo"), OBFUSCATE("(Landroid/content/Context;II)V"), reinterpret_cast<void *>(ToastInfo2)}, {OBFUSCATE("GetLoginScreenFields"), OBFUSCATE("()[Ljava/lang/String;"), reinterpret_cast<void *>(GetLoginScreenFields)}, {OBFUSCATE("GetInitialDialogFields"), OBFUSCATE("()[Ljava/lang/String;"), reinterpret_cast<void *>(GetInitialDialogFields)}, }; jclass clazz = env->FindClass(OBFUSCATE("com/classloader/s4j/MainActivity")); if (!clazz) return JNI_ERR; if (env->RegisterNatives(clazz, methods, sizeof(methods) / sizeof(methods[0])) != 0) return JNI_ERR; return JNI_OK; } extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env; vm->GetEnv((void **) &env, JNI_VERSION_1_6); if (RegisterMethods1(env) != 0) { return JNI_ERR; } else { return JNI_VERSION_1_6; } }
62.189511
9,227
0.619832
[ "vector", "model" ]
041b912422d801e06f53cb48fd2a077529a5a93a
1,979
hpp
C++
inference-engine/samples/validation_app/image_decoder.hpp
mypopydev/dldt
8cd639116b261adbbc8db860c09807c3be2cc2ca
[ "Apache-2.0" ]
3
2019-07-08T09:03:03.000Z
2020-09-09T10:34:17.000Z
inference-engine/samples/validation_app/image_decoder.hpp
openvino-pushbot/dldt
e607ee70212797cf9ca51dac5b7ac79f66a1c73f
[ "Apache-2.0" ]
3
2020-11-13T18:59:18.000Z
2022-02-10T02:14:53.000Z
inference-engine/samples/validation_app/image_decoder.hpp
openvino-pushbot/dldt
e607ee70212797cf9ca51dac5b7ac79f66a1c73f
[ "Apache-2.0" ]
1
2018-12-14T07:56:02.000Z
2018-12-14T07:56:02.000Z
// Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <map> #include <opencv2/core/core.hpp> #include <opencv2/core/mat.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <string> #include <vector> #include "ie_blob.h" #include "PreprocessingOptions.hpp" using namespace cv; using namespace InferenceEngine; class ImageDecoder { public: /** * @brief Load single image to blob * @param name - image file name * @param blob - blob object to load image data to * @return original image sizes */ Size loadToBlob(std::string name, Blob& blob, PreprocessingOptions preprocessingOptions); /** * @brief Load a list of images to blob * @param names - list of images filenames * @param blob - blob object to load images data to * @return original image size */ std::map<std::string, cv::Size> loadToBlob(std::vector<std::string> names, Blob& blob, PreprocessingOptions preprocessingOptions); /** * @brief Insert image data to blob at specified batch position. * Does no checks if blob has sufficient space * @param name - image file name * @param batch_pos - batch position image should be loaded to * @param blob - blob object to load image data to * @return original image size */ Size insertIntoBlob(std::string name, int batch_pos, Blob& blob, PreprocessingOptions preprocessingOptions); };
32.983333
134
0.704901
[ "object", "vector" ]
041c706bbf1b0efeb6b38b18ec79ead9f7ee38ed
788
cpp
C++
LeetCode/cpp/904.cpp
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
279
2019-02-19T16:00:32.000Z
2022-03-23T12:16:30.000Z
LeetCode/cpp/904.cpp
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
2
2019-03-31T08:03:06.000Z
2021-03-07T04:54:32.000Z
LeetCode/cpp/904.cpp
ZintrulCre/LeetCode_Crawler
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
12
2019-01-29T11:45:32.000Z
2019-02-04T16:31:46.000Z
class Solution { public: int totalFruit(vector<int> &tree) { time_t begin = clock(); int size = tree.size(); int total = 0; for (int i = 0; i < size; ++i) { if (i > 0 && tree[i] == tree[i - 1]) continue; int a = tree[i], b = -1; int current = 1, j = i + 1; for (; j < size; ++j) { if (b != -1 && (tree[j] != a && tree[j] != b)) break; if (b == -1 && tree[j] != a) b = tree[j]; ++current; } total = max(total, current); if (j == size) break; } time_t end = clock(); cout << end - begin << endl; return total; } };
29.185185
62
0.346447
[ "vector" ]
042031a74eeb383f840a163d11b9c3b32368ab0d
5,763
hpp
C++
lsdtt_xtensor/src/LSDRasterInfo.hpp
LSDtopotools/lsdtopytools
9809cbd368fe46b5e483085fa55f3206e4d85183
[ "MIT" ]
2
2020-05-04T14:32:34.000Z
2021-06-29T10:59:03.000Z
lsdtt_xtensor/src/LSDRasterInfo.hpp
LSDtopotools/lsdtopytools
9809cbd368fe46b5e483085fa55f3206e4d85183
[ "MIT" ]
1
2020-01-30T14:03:00.000Z
2020-02-06T16:32:56.000Z
lsdtt_xtensor/src/LSDRasterInfo.hpp
LSDtopotools/lsdtopytools
9809cbd368fe46b5e483085fa55f3206e4d85183
[ "MIT" ]
1
2021-04-21T17:40:42.000Z
2021-04-21T17:40:42.000Z
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // LSDRaster // Land Surface Dynamics Raster Info // // An object within the University // of Edinburgh Land Surface Dynamics group topographic toolbox // for examining the georeferencing and existence of rasters // // Developed by: // Simon M. Mudd // Martin D. Hurst // David T. Milodowski // Stuart W.D. Grieve // Declan A. Valters // Fiona Clubb // // Copyright (C) 2013 Simon M. Mudd 2013 // // Developer can be contacted by simon.m.mudd _at_ ed.ac.uk // // Simon Mudd // University of Edinburgh // School of GeoSciences // Drummond Street // Edinburgh, EH8 9XP // Scotland // United Kingdom // // 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 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; // without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the // GNU General Public License along with this program; // if not, write to: // Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 // USA // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #ifndef LSDRasterInfo_H #define LSDRasterInfo_H #include <map> #include <string> using namespace std; // declare classes. Implementation is included in cpp file class LSDRaster; class LSDTindexRaster; ///@brief Object that stores georeferencing information. This information is /// also stored with the raster, it is seperated here mainly to compare /// different datasets class LSDRasterInfo { public: /// an empty create function LSDRasterInfo() { create(); } /// This function reads the file LSDRasterInfo(string filename, string extension) { create(filename, extension); } /// This gets the information from an existing raster LSDRasterInfo(LSDRaster& Raster) { create(Raster); } /// This gets the information from an existing index raster LSDRasterInfo(LSDIndexRaster& IRaster) { create(IRaster); } /// The equality operator bool operator==(LSDRasterInfo& LSDRI); /// The inequality operator bool operator!=(LSDRasterInfo& LSDRI); /// @brief this function gets the UTM_zone and a boolean that is true if /// the map is in the northern hemisphere /// @param UTM_zone the UTM zone. Replaced in function. /// @param is_North a boolean that is true if the DEM is in the northern hemisphere. /// replaced in function /// @author SMM /// @date 22/12/2014 void get_UTM_information(int& UTM_zone, bool& is_North); /// @brief this check to see if a point is within the raster /// @param X_coordinate the x location of the point /// @param Y_coordinate the y location of the point /// @return is_in_raster a boolean telling if the point is in the raster /// @author SMM /// @date 13/11/2014 bool check_if_point_is_in_raster(float X_coordinate,float Y_coordinate); /// @brief Prints the raster information to screen /// @author SMM /// @date 19/11/2019 void print_raster_information(); // Get functions /// @return Number of rows as an integer. int get_NRows() const { return NRows; } /// @return Number of columns as an integer. int get_NCols() const { return NCols; } /// @return Minimum X coordinate as an integer. float get_XMinimum() const { return XMinimum; } /// @return Minimum Y coordinate as an integer. float get_YMinimum() const { return YMinimum; } /// @return Data resolution as an integer. float get_DataResolution() const { return DataResolution; } /// @return No Data Value as an integer. int get_NoDataValue() const { return NoDataValue; } /// @return map containing the georeferencing strings map<string,string> get_GeoReferencingStrings() const { return GeoReferencingStrings; } protected: /// @brief Read a header /// The supported formats are .asc, .flt and .bil which are /// both exported and imported by arcmap. /// The filename is the string of characters before the '.' in the extension /// and the extension is the characters after the '.'. /// If the full filename is my_dem.01.asc then: /// filename = "my_dem.01" and extension = "asc". /// For float files both a data file and a header are read /// the header file must have the same filename, before extention, of /// the raster data, and the extension must be .hdr. /// @param filename the prefix of the file /// @param extension this is either "asc", "flt", or "bil" /// @author SMM /// @date 01/01/12 void read_header(string filename, string extension); ///Number of rows. int NRows; ///Number of columns. int NCols; ///Minimum X coordinate. float XMinimum; ///Minimum Y coordinate. float YMinimum; ///Data resolution. float DataResolution; ///No data value. int NoDataValue; ///A map of strings for holding georeferencing information map<string,string> GeoReferencingStrings; private: void create(); void create(LSDRaster& Raster); void create(LSDIndexRaster& IRaster); void create(string filename, string extension); }; #endif
32.931429
90
0.649141
[ "object" ]
0420b25caf3814ee9bb52e5517e5d7e28f6452e4
3,866
cpp
C++
gse/src/v20191112/model/ResourceCreationLimitPolicy.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
gse/src/v20191112/model/ResourceCreationLimitPolicy.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
gse/src/v20191112/model/ResourceCreationLimitPolicy.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/gse/v20191112/model/ResourceCreationLimitPolicy.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Gse::V20191112::Model; using namespace std; ResourceCreationLimitPolicy::ResourceCreationLimitPolicy() : m_newGameServerSessionsPerCreatorHasBeenSet(false), m_policyPeriodInMinutesHasBeenSet(false) { } CoreInternalOutcome ResourceCreationLimitPolicy::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("NewGameServerSessionsPerCreator") && !value["NewGameServerSessionsPerCreator"].IsNull()) { if (!value["NewGameServerSessionsPerCreator"].IsUint64()) { return CoreInternalOutcome(Error("response `ResourceCreationLimitPolicy.NewGameServerSessionsPerCreator` IsUint64=false incorrectly").SetRequestId(requestId)); } m_newGameServerSessionsPerCreator = value["NewGameServerSessionsPerCreator"].GetUint64(); m_newGameServerSessionsPerCreatorHasBeenSet = true; } if (value.HasMember("PolicyPeriodInMinutes") && !value["PolicyPeriodInMinutes"].IsNull()) { if (!value["PolicyPeriodInMinutes"].IsUint64()) { return CoreInternalOutcome(Error("response `ResourceCreationLimitPolicy.PolicyPeriodInMinutes` IsUint64=false incorrectly").SetRequestId(requestId)); } m_policyPeriodInMinutes = value["PolicyPeriodInMinutes"].GetUint64(); m_policyPeriodInMinutesHasBeenSet = true; } return CoreInternalOutcome(true); } void ResourceCreationLimitPolicy::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_newGameServerSessionsPerCreatorHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "NewGameServerSessionsPerCreator"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_newGameServerSessionsPerCreator, allocator); } if (m_policyPeriodInMinutesHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PolicyPeriodInMinutes"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_policyPeriodInMinutes, allocator); } } uint64_t ResourceCreationLimitPolicy::GetNewGameServerSessionsPerCreator() const { return m_newGameServerSessionsPerCreator; } void ResourceCreationLimitPolicy::SetNewGameServerSessionsPerCreator(const uint64_t& _newGameServerSessionsPerCreator) { m_newGameServerSessionsPerCreator = _newGameServerSessionsPerCreator; m_newGameServerSessionsPerCreatorHasBeenSet = true; } bool ResourceCreationLimitPolicy::NewGameServerSessionsPerCreatorHasBeenSet() const { return m_newGameServerSessionsPerCreatorHasBeenSet; } uint64_t ResourceCreationLimitPolicy::GetPolicyPeriodInMinutes() const { return m_policyPeriodInMinutes; } void ResourceCreationLimitPolicy::SetPolicyPeriodInMinutes(const uint64_t& _policyPeriodInMinutes) { m_policyPeriodInMinutes = _policyPeriodInMinutes; m_policyPeriodInMinutesHasBeenSet = true; } bool ResourceCreationLimitPolicy::PolicyPeriodInMinutesHasBeenSet() const { return m_policyPeriodInMinutesHasBeenSet; }
34.517857
171
0.768236
[ "model" ]
54b5fca2cb61aeaa602d4d7bb760a6560b461882
34,927
cpp
C++
dev/Code/Sandbox/Editor/ObjectSelectorModel.cpp
BadDevCode/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
2
2020-06-27T12:13:44.000Z
2020-06-27T12:13:46.000Z
dev/Code/Sandbox/Editor/ObjectSelectorModel.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
null
null
null
dev/Code/Sandbox/Editor/ObjectSelectorModel.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "StdAfx.h" #include "ObjectSelectorModel.h" #include "Objects/EntityObject.h" #include "Objects/BaseObject.h" #include "Objects/ObjectLayer.h" #include "Objects/Group.h" #include "Objects/GeomEntity.h" #include "Objects/BrushObject.h" #include "Material/Material.h" #include "TrackView/TrackViewAnimNode.h" #include "TrackView/TrackViewSequence.h" #include "TrackView/TrackViewSequenceManager.h" #include <QtUtil.h> #include <QtUtilWin.h> #include <StringUtils.h> #include <QSize> #include <QDebug> #include <QStringList> #include <QIcon> #include <map> #define CLOSED_GRP_STR " (Closed)]" static int g_sortColumn = ObjectSelectorModel::NameColumn; static Qt::SortOrder g_sortOrder = Qt::DescendingOrder; ObjectSelectorModel::TGeometryCountMap ObjectSelectorModel::m_mGeomCountMap; ObjectSelectorModel::ObjToStrMap ObjectSelectorModel::s_trackViewMap; static bool lessThanEmptyLast(const QString& s1, const QString& s2, Qt::SortOrder order) { if (s1.isEmpty() ^ s2.isEmpty()) { return s2.isEmpty(); } return order == Qt::AscendingOrder ? s1 < s2 : s1 > s2; } static bool objectLessThan(CBaseObject* obj1, CBaseObject* obj2) { QString text1 = ObjectSelectorModel::data(obj1, Qt::DisplayRole, g_sortColumn).toString().toLower(); QString text2 = ObjectSelectorModel::data(obj2, Qt::DisplayRole, g_sortColumn).toString().toLower(); switch (g_sortColumn) { case ObjectSelectorModel::SelectedColumn: if (obj1->IsSelected() ^ obj1->IsSelected()) { return obj1->IsSelected(); } break; case ObjectSelectorModel::DefaultMaterialColumn: case ObjectSelectorModel::CustomMaterialColumn: case ObjectSelectorModel::GeometryColumn: text1.replace(WIN_SLASH, ""); text2.replace(WIN_SLASH, ""); text1.replace(UNIX_SLASH, ""); text2.replace(UNIX_SLASH, ""); if (text1 != text2) { return lessThanEmptyLast(text1, text2, g_sortOrder); } break; case ObjectSelectorModel::InstancesInLevel: case ObjectSelectorModel::LODsColumn: { bool ok; const int lod1 = text1.isEmpty() ? MAXINT : text1.toInt(&ok); const int lod2 = text2.isEmpty() ? MAXINT : text2.toInt(&ok); return g_sortOrder == Qt::AscendingOrder ? lod1 < lod2 : lod1 >= lod2; } case ObjectSelectorModel::AIGroupColumn: { int gropid1 = ObjectSelectorModel::GetAIGroupID(obj1); int gropid2 = ObjectSelectorModel::GetAIGroupID(obj2); if (gropid1 == -1) { gropid1 = MAXINT; } if (gropid2 == -1) { gropid2 = MAXINT; } if (gropid1 != gropid2) { return g_sortOrder == Qt::AscendingOrder ? gropid1 < gropid2 : gropid1 >= gropid2; } break; } } return lessThanEmptyLast(text1, text2, g_sortOrder); } QString ObjectSelectorModel::GetObjectName(CBaseObject* pObject) { QString resultBuffer; if (!pObject) { return QString(); } CGroup* pObjGroup = pObject->GetGroup(); if (pObjGroup) { resultBuffer = "["; resultBuffer += pObjGroup->GetName(); if (pObjGroup->IsOpen()) { resultBuffer += "]"; } else { resultBuffer += CLOSED_GRP_STR; } resultBuffer += pObject->GetName(); return resultBuffer; } else if ((pObject->GetType() == OBJTYPE_GROUP) || (pObject->GetType() == OBJTYPE_PREFAB)) { resultBuffer = "["; resultBuffer += pObject->GetName(); CGroup* pGroupObj = (CGroup*)pObject; if (pGroupObj) { if (pGroupObj->IsOpen()) { resultBuffer += "]"; } else { resultBuffer += CLOSED_GRP_STR; } } return resultBuffer; } else { return pObject->GetName(); } } static QString GetTrackViewName(CBaseObject* pObject) { auto it = ObjectSelectorModel::s_trackViewMap.find(pObject); if (it == ObjectSelectorModel::s_trackViewMap.end()) { return QString(); } else { return it->second; } } static void GetExtraLightInfo(CBaseObject* pObject, QString& csText) { if (qobject_cast<CEntityObject*>(pObject)) { CEntityObject* pEntity = (CEntityObject*)pObject; if (pEntity) { IObjectManager* objMan = GetIEditor()->GetObjectManager(); if (objMan) { if (objMan->IsLightClass(pEntity)) { if (!pEntity->GetEntityPropertyString("file_deferred_clip_geom").isEmpty()) { csText += ".clip"; } if (pEntity->GetEntityPropertyBool("bAmbient")) { csText += ".ambient"; } if (pEntity->GetEntityPropertyBool("bAreaLight")) { csText += ".arealight"; } if (!pEntity->GetEntityPropertyString("texture_Texture").isEmpty()) { csText += ".projector"; } int nLightType = pEntity->GetEntityPropertyInteger("nCastShadows"); if (nLightType > 0) { csText += ".shadow"; switch (nLightType) { case 1: csText += ".lowSpec"; break; case 2: csText += ".mediumSpec"; break; case 3: csText += ".highSpec"; break; case 4: csText += ".veryHighSpec"; break; case 7: csText += ".detailSpec"; break; } } } } } } } static QString ComputeTrackViewName(CBaseObject* pObject) { QString result; if (qobject_cast<CEntityObject*>(pObject)) { CEntityObject* pEntity = static_cast<CEntityObject*>(pObject); CTrackViewAnimNodeBundle bundle = GetIEditor()->GetSequenceManager()->GetAllRelatedAnimNodes(pEntity); const int count = bundle.GetCount(); for (unsigned int i = 0; i < count; ++i) { if (!result.isEmpty()) { result += ","; } CTrackViewSequence* pSequence = bundle.GetNode(i)->GetSequence(); if (pSequence) { result += pSequence->GetName(); } } return result; } return QString(); } static QString GetMaterialName(CBaseObject* pObject, bool bGetCustomMaterial = false) { static QString sEffect; static QString custMaterialStr; static QString defMaterialStr; sEffect.clear(); custMaterialStr.clear(); defMaterialStr.clear(); // Get default material stored in CGF file if (qobject_cast<CBrushObject*>(pObject)) { CBrushObject* pBrush = (CBrushObject*)pObject; if (!pBrush) { return QString(); } if (!pBrush->GetIStatObj()) { return QString(); } if (!pBrush->GetIStatObj()->GetMaterial()) { return QString(); } defMaterialStr = pBrush->GetIStatObj()->GetMaterial()->GetName(); defMaterialStr = defMaterialStr.toLower(); defMaterialStr.replace(UNIX_SLASH, WIN_SLASH); } // Get material assigned by the user CMaterial* pMtl = pObject->GetMaterial(); if (pMtl) { custMaterialStr = pMtl->GetName(); custMaterialStr = custMaterialStr.toLower(); custMaterialStr.replace(UNIX_SLASH, WIN_SLASH); } if (!defMaterialStr.isEmpty() || !custMaterialStr.isEmpty()) { if (bGetCustomMaterial) { if (!custMaterialStr.isEmpty() && custMaterialStr != defMaterialStr) { return custMaterialStr; } else { return QString(); } } else { return defMaterialStr; } } // Entity if (qobject_cast<CEntityObject*>(pObject)) { CEntityObject* pEntity = (CEntityObject*)pObject; if (pEntity->GetProperties()) { IVariable* pVar = pEntity->GetProperties()->FindVariable("ParticleEffect"); if (pVar) { pVar->Get(sEffect); return sEffect; } } } return QString(); } static void GetMaterialBreakability(std::set<QString>* breakTypes, CMaterial* pMaterial) { if (pMaterial) { const QString surfaceTypeName = pMaterial->GetSurfaceTypeName(); ISurfaceTypeManager* pSurfaceManager = GetIEditor()->Get3DEngine()->GetMaterialManager()->GetSurfaceTypeManager(); if (!pSurfaceManager) { return; } ISurfaceType* pSurfaceType = pSurfaceManager->GetSurfaceTypeByName(surfaceTypeName.toUtf8().data()); if (pSurfaceType && pSurfaceType->GetBreakability() != 0) { breakTypes->insert(pSurfaceType->GetType()); } int subMaterialCount = pMaterial->GetSubMaterialCount(); for (int i = 0; i < subMaterialCount; ++i) { CMaterial* pChild = pMaterial->GetSubMaterial(i); if (!pChild) { continue; } GetMaterialBreakability(breakTypes, pChild); } } } static QString GetObjectBreakability(CBaseObject* pObject) { CMaterial* pMaterial = pObject->GetMaterial(); if (!pMaterial) { return QString(); } std::set<QString> breakabilityTypes; GetMaterialBreakability(&breakabilityTypes, pMaterial); QString result; { for (auto it = breakabilityTypes.begin(); it != breakabilityTypes.end(); ++it) { if (!result.isEmpty()) { result += ", "; } result += *it; } } return result; } static QString GetGeometryFile(CBaseObject* pObject) { QString resultBuffer; if (qobject_cast<CBrushObject*>(pObject)) { CBrushObject* pObj = (CBrushObject*)pObject; resultBuffer = pObj->GetGeometryFile().toLower(); resultBuffer.replace(UNIX_SLASH, WIN_SLASH); return resultBuffer; } else if (qobject_cast<CGeomEntity*>(pObject)) { CGeomEntity* pObj = (CGeomEntity*)pObject; resultBuffer = pObj->GetGeometryFile().toLower(); resultBuffer.replace(UNIX_SLASH, WIN_SLASH); return resultBuffer; } else if (qobject_cast<CEntityObject*>(pObject)) { CEntityObject* pEntity = static_cast<CEntityObject*>(pObject); IRenderNode* pEngineNode = pEntity->GetEngineNode(); if (pEngineNode) { IStatObj* pEntityStatObj = pEngineNode->GetEntityStatObj(); ICharacterInstance* iEntityCharacter = pEngineNode->GetEntityCharacter(0); if (pEntityStatObj) { resultBuffer = pEntityStatObj->GetFilePath(); } if (resultBuffer.isEmpty() && iEntityCharacter) { resultBuffer = iEntityCharacter->GetFilePath(); } if (resultBuffer.isEmpty() && pEntity->GetProperties()) { IVariable* pVar = pEntity->GetProperties()->FindVariable("Model"); if (pVar) { pVar->Get(resultBuffer); } } if (!resultBuffer.isEmpty()) { resultBuffer = resultBuffer.toLower(); resultBuffer.replace(UNIX_SLASH, WIN_SLASH); } } } return resultBuffer; } bool GetGeomCount(CBaseObject* pObject, int& val) { val = -1; if (pObject) { QString sGeomFileStr = GetGeometryFile(pObject); if (!sGeomFileStr.isEmpty()) { val = stl::find_in_map(ObjectSelectorModel::m_mGeomCountMap, sGeomFileStr, 0); return true; } } return false; } int ObjectSelectorModel::GetAIGroupID(CBaseObject* obj) { if (qobject_cast<CEntityObject*>(obj)) { CEntityObject* pEnt = (CEntityObject*)obj; CVarBlock* properties = pEnt->GetProperties2(); if (properties) { IVariable* varEn = properties->FindVariable("groupid"); if (varEn) { int groupid; varEn->Get(groupid); return groupid; } } } return -1; } static QString GetSmartObject(CBaseObject* pObject) { if (qobject_cast<CEntityObject*>(pObject)) { CEntityObject* pEntity = (CEntityObject*)pObject; return pEntity->GetSmartObjectClass(); } return QString(); } bool GETLODNumber(CBaseObject* pObject, int& nLodNumber) { IStatObj::SStatistics stats; nLodNumber = -1; if (qobject_cast<CBrushObject*>(pObject)) { CBrushObject* pBrush = (CBrushObject*)pObject; if (!pBrush) { return false; } IStatObj* pStatObj = pBrush->GetIStatObj(); if (pStatObj) { pStatObj->GetStatistics(stats); nLodNumber = stats.nLods; return true; } } else if (qobject_cast<CGeomEntity*>(pObject)) { CGeomEntity* pGeomEntity = (CGeomEntity*)pObject; IRenderNode* pEngineNode = pGeomEntity->GetEngineNode(); if (pEngineNode) { IStatObj* pEntityStatObj = pEngineNode->GetEntityStatObj(); if (pEntityStatObj) { pEntityStatObj->GetStatistics(stats); nLodNumber = stats.nLods; return true; } } } else if (qobject_cast<CEntityObject*>(pObject)) { CEntityObject* pEntity = static_cast<CEntityObject*>(pObject); IRenderNode* pEngineNode = pEntity->GetEngineNode(); if (pEngineNode) { IStatObj* pEntityStatObj = pEngineNode->GetEntityStatObj(); if (pEntityStatObj) { pEntityStatObj->GetStatistics(stats); nLodNumber = stats.nLods; return true; } ICharacterInstance* iEntityCharacter = pEngineNode->GetEntityCharacter(0); if (iEntityCharacter) { const IDefaultSkeleton& rIDefaultSkeleton = iEntityCharacter->GetIDefaultSkeleton(); { uint32 numInstances = gEnv->pCharacterManager->GetNumInstancesPerModel(rIDefaultSkeleton); if (numInstances > 0) { ICharacterInstance* pCharInstance = gEnv->pCharacterManager->GetICharInstanceFromModel(rIDefaultSkeleton, 0); if (pCharInstance) { if (ISkeletonPose* pSkeletonPose = pCharInstance->GetISkeletonPose()) { IDefaultSkeleton& rIDefaultSkeleton = pCharInstance->GetIDefaultSkeleton(); uint32 numJoints = rIDefaultSkeleton.GetJointCount(); // check StatObj attachments for (uint32 i = 0; i < numJoints; ++i) { IStatObj* pStatObj = (IStatObj*)pSkeletonPose->GetStatObjOnJoint(i); if (pStatObj) { pStatObj->GetStatistics(stats); nLodNumber = stats.nLods; return true; } } } } } } } } } return false; } ObjectSelectorModel::ObjectSelectorModel(QObject* parent) : QAbstractTableModel(parent) , m_objectTypeMask(0) , m_displayMode(ObjectSelectorModel::DisplayModeVisible) , m_matchPropertyName(true) { connect(this, &QAbstractItemModel::rowsInserted, this, &ObjectSelectorModel::countChanged); connect(this, &QAbstractItemModel::rowsRemoved, this, &ObjectSelectorModel::countChanged); connect(this, &QAbstractItemModel::modelReset, this, &ObjectSelectorModel::countChanged); connect(this, &QAbstractItemModel::layoutChanged, this, &ObjectSelectorModel::countChanged); } ObjectSelectorModel::~ObjectSelectorModel() { Clear(); } void ObjectSelectorModel::Clear() { beginResetModel(); m_mGeomCountMap.clear(); s_trackViewMap.clear(); m_objects.clear(); m_indentState.clear(); endResetModel(); } QStringList ObjectSelectorModel::ColumnNames() { static const QStringList names = { "Name", "Selected", "Type", "Layer", "Default Material", "Custom Material", "Breakability", "Smart Object", "Track View", "Geometry", "Instances In Level", "Number of LODs", "Spec", "AI GroupID" }; Q_ASSERT(names.size() == ObjectSelectorModel::NumberOfColumns); return names; } void ObjectSelectorModel::Reload(bool rebuildMaps) { beginResetModel(); m_objects.clear(); m_indentState.clear(); const int numObjects = GetIEditor()->GetObjectManager()->GetObjectCount(); m_objects.reserve(numObjects); m_indentState.reserve(numObjects); std::vector<CBaseObject*> objects; GetIEditor()->GetObjectManager()->GetObjects(objects); std::sort(objects.begin(), objects.end(), objectLessThan); // Filter the object list properly. for (CBaseObject* obj : objects) { if (m_treeModeEnabled && obj->GetParent() && !m_bSearchInsideObjects) { continue; } if (m_treeModeEnabled || m_bSearchInsideObjects) { AddObjectRecursively(obj, 0); } else { AddObject(obj, 0); } } UpdateGeomCount(); if (rebuildMaps) { BuildMaps(); } endResetModel(); } void ObjectSelectorModel::AddObjectToMaps(CBaseObject* pObject) { QString tv = ComputeTrackViewName(pObject); if (!tv.isEmpty()) { s_trackViewMap[pObject] = tv; } } int ObjectSelectorModel::rowCount(const QModelIndex& parent) const { return m_objects.size(); } int ObjectSelectorModel::columnCount(const QModelIndex& parent) const { return NumberOfColumns; } QVariant ObjectSelectorModel::data(CBaseObject* object, int role, int col) { if (object == nullptr) { return QVariant(); } if (role == Qt::DisplayRole || role == Qt::EditRole) { switch ((Column)col) { case NameColumn: return GetObjectName(object); case SelectedColumn: return object->IsSelected() ? QStringLiteral("x") : QString(); case TypeColumn: { QString result = object->GetTypeDescription(); GetExtraLightInfo(object, result); return result; } case LayerColumn: { auto layer = object->GetLayer(); return layer ? layer->GetName() : QString(); } case DefaultMaterialColumn: return GetMaterialName(object); case CustomMaterialColumn: return GetMaterialName(object, true); case BreakabilityColumn: return GetObjectBreakability(object); case SmartObjectColumn: return GetSmartObject(object); case TrackViewColumn: return GetTrackViewName(object); case GeometryColumn: return GetGeometryFile(object); case InstancesInLevel: { int nVal = -1; GetGeomCount(object, nVal); if (nVal != -1) { return nVal; } else { return ""; } } case LODsColumn: { int nLODNo1 = -1; if (GETLODNumber(object, nLODNo1)) { return nLODNo1; } return QString(); } case SpecColumn: { static const QStringList specs = { "All", "Low", "Medium/Console", "PC High", "PC Very High", "Detail" }; return specs.value(object->GetMinSpec()); } case AIGroupColumn: { const int groupId = GetAIGroupID(object); if (groupId != -1) { return groupId; } else { return QString(); } } default: return QVariant(); } } else if (role == ObjectSelectorModel::ObjectRole) { return QVariant::fromValue<CBaseObject*>(object); } return QVariant(); } QVariant ObjectSelectorModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) { return QVariant(); } const int row = index.row(); const int col = index.column(); if (row < 0 || row >= rowCount() || col < 0 || col >= columnCount()) { return QVariant(); } auto object = m_objects.at(row); if (role == IdentationRole) { return m_indentState.at(row); } else if (role == Qt::DecorationRole && col == NameColumn) { if (m_treeModeEnabled) { FirstColumnImage image = LIST_BITMAP_ANY; switch (object->GetType()) { case OBJTYPE_GROUP: image = LIST_BITMAP_GROUP; break; case OBJTYPE_TAGPOINT: image = LIST_BITMAP_TAGPOINT; break; case OBJTYPE_ENTITY: image = LIST_BITMAP_ENTITY; break; case OBJTYPE_SHAPE: image = LIST_BITMAP_PATH; break; case OBJTYPE_VOLUME: image = LIST_BITMAP_VOLUME; break; case OBJTYPE_BRUSH: image = LIST_BITMAP_BRUSH; break; } QIcon icon(QString(":/ObjectSelector/icons/tile_%1.png").arg(image)); return QVariant(icon); } else { return QVariant(); } } return data(object, role, col); } QVariant ObjectSelectorModel::headerData(int section, Qt::Orientation orientation, int role) const { if (section < 0 || section >= NumberOfColumns) { return QVariant(); } if (orientation == Qt::Vertical) { return QVariant(); } if (role == Qt::DisplayRole) { return ColumnNames().at(section); } else if (role == Qt::TextAlignmentRole) { return QVariant(Qt::AlignLeft); } return QVariant(); } Qt::ItemFlags ObjectSelectorModel::flags(const QModelIndex& index) const { if (!index.isValid()) { return 0; } return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } void ObjectSelectorModel::EnableTreeMode(bool enable) { if (m_treeModeEnabled != enable) { m_treeModeEnabled = enable; Reload(); } } void ObjectSelectorModel::UpdateGeomCount() { ObjectSelectorModel::m_mGeomCountMap.clear(); std::vector<CBaseObject*> objects; GetIEditor()->GetObjectManager()->GetObjects(objects); const int size = objects.size(); for (size_t i = 0; i < size; ++i) { CBaseObject* pObj = objects[i]; if (pObj) { QString sGeomFileStr = GetGeometryFile(pObj); if (!sGeomFileStr.isEmpty()) { int nGeomCount = stl::find_in_map(ObjectSelectorModel::m_mGeomCountMap, sGeomFileStr, 0); ObjectSelectorModel::m_mGeomCountMap[sGeomFileStr] = nGeomCount + 1; } } } } void ObjectSelectorModel::EmitDataChanged(CBaseObject* obj) { const int row = std::find(m_objects.cbegin(), m_objects.cend(), obj) - m_objects.cbegin(); if (row >= 0 && row < m_objects.size()) { emit dataChanged(index(row, 0), index(row, columnCount() - 1)); } } void ObjectSelectorModel::EmitDataChanged() { if (!m_objects.empty()) { emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1)); } } void ObjectSelectorModel::EmitDataChanged(const QModelIndex& ndx) { if (ndx.isValid() && ndx.row() >= 0 && ndx.row() < m_objects.size()) emit dataChanged(index(ndx.row(), 0), index(ndx.row(), columnCount() - 1)); } void ObjectSelectorModel::RemoveObject(CBaseObject* obj) { const int row = std::find(m_objects.cbegin(), m_objects.cend(), obj) - m_objects.cbegin(); if (row >= 0 && row < m_objects.size()) { beginRemoveRows(QModelIndex(), row, row); m_objects.erase(m_objects.cbegin() + row); m_indentState.erase(m_indentState.cbegin() + row); endRemoveRows(); } } bool ObjectSelectorModel::AddObject(CBaseObject* obj, int level) { if (!AcceptsObject(obj)) { return false; } const int count = m_objects.size(); beginInsertRows(QModelIndex(), count, count); m_objects.push_back(obj); m_indentState.push_back(level); endInsertRows(); return true; } void ObjectSelectorModel::AddObjectRecursively(CBaseObject* obj, int level) { bool parentObjectAdded = AddObject(obj, level); std::vector<CBaseObject*> children; const int numChildren = obj->GetChildCount(); children.reserve(obj->GetChildCount()); for (int i = 0; i < numChildren; i++) { children.push_back(obj->GetChild(i)); } std::sort(children.begin(), children.end(), objectLessThan); for (CBaseObject* childObj : children) { AddObjectRecursively(childObj, parentObjectAdded ? level + 1 : level); } } bool ObjectSelectorModel::IsTreeMode() const { return m_treeModeEnabled; } void ObjectSelectorModel::SetObjectTypeMask(int mask) { if (mask != m_objectTypeMask) { m_objectTypeMask = mask; Reload(false); } } void ObjectSelectorModel::SetFilterText(const QString& text) { if (text != m_filterText) { m_filterText = text; Reload(false); } } bool ObjectSelectorModel::IsPropertyMatchVariable(IVariable* pVar) const { QString propertyFilter = m_propertyFilter; if (m_matchPropertyName) { if (pVar->GetHumanName().contains(propertyFilter, Qt::CaseInsensitive)) { return true; } } else { QString value; pVar->Get(value); if (value.contains(propertyFilter, Qt::CaseInsensitive)) { return true; } } if (pVar->GetNumVariables() > 0) { for (int i = 0; i < pVar->GetNumVariables(); i++) { IVariable* pChildVar = pVar->GetVariable(i); if (IsPropertyMatchVariable(pChildVar)) { return true; } } } return false; } bool ObjectSelectorModel::IsPropertyMatch(CBaseObject* pObject) const { CVarBlock* pVars = pObject->GetVarBlock(); if (pVars) { for (int i = 0; i < pVars->GetNumVariables(); i++) { IVariable* pVar = pVars->GetVariable(i); if (IsPropertyMatchVariable(pVar)) { return true; } } } if (qobject_cast<CEntityObject*>(pObject)) { CEntityObject* pEntity = (CEntityObject*)pObject; { CVarBlock* pVars = pEntity->GetProperties(); if (pVars) { for (int i = 0; i < pVars->GetNumVariables(); i++) { IVariable* pVar = pVars->GetVariable(i); if (IsPropertyMatchVariable(pVar)) { return true; } } } } { CVarBlock* pVars = pEntity->GetProperties2(); if (pVars) { for (int i = 0; i < pVars->GetNumVariables(); i++) { IVariable* pVar = pVars->GetVariable(i); if (IsPropertyMatchVariable(pVar)) { return true; } } } } if (pEntity) { QString propertyFilter = m_propertyFilter; QString sPropFilter = propertyFilter.toLower(); sPropFilter.replace(UNIX_SLASH, WIN_SLASH); IRenderNode* pEngineNode = pEntity->GetEngineNode(); if (pEngineNode) { QString sVarPath(""); IStatObj* pEntityStatObj = pEngineNode->GetEntityStatObj(); ICharacterInstance* iEntityCharacter = pEngineNode->GetEntityCharacter(0); if (pEntityStatObj) { sVarPath = pEntityStatObj->GetFilePath(); } if (sVarPath.isEmpty() && iEntityCharacter) { sVarPath = iEntityCharacter->GetFilePath(); } sVarPath = sVarPath.toLower(); sVarPath.replace(UNIX_SLASH, WIN_SLASH); if (sVarPath.contains(sPropFilter)) { return true; } CVarBlock* pVars = pEntity->GetProperties(); if (sVarPath.isEmpty() && pVars) { IVariable* pVar = pVars->FindVariable(sPropFilter.toUtf8().data()); if (pVar) { return true; } } } } } return false; } void ObjectSelectorModel::SetProperties(const QString& propertyText) { if (m_propertyFilter != propertyText) { m_propertyFilter = propertyText; Reload(false); } } void ObjectSelectorModel::SetDisplayMode(ObjectSelectorModel::DisplayMode mode) { if (mode != m_displayMode) { m_displayMode = mode; Reload(false); } } void ObjectSelectorModel::SetMatchPropertyName(bool match) { if (match != m_matchPropertyName) { m_matchPropertyName = match; Reload(false); } } std::vector<CBaseObject*> ObjectSelectorModel::GetObjects() const { return m_objects; } ObjectSelectorModel::DisplayMode ObjectSelectorModel::GetDisplayMode() const { return m_displayMode; } void ObjectSelectorModel::SetIsLinkTool(bool is) { m_bIsLinkTool = is; } void ObjectSelectorModel::SetSearchInsideObjects(bool search) { if (m_bSearchInsideObjects != search) { m_bSearchInsideObjects = search; Reload(false); } } bool ObjectSelectorModel::GetSearchInsideObjects() const { return m_bSearchInsideObjects; } bool ObjectSelectorModel::AcceptsObject(CBaseObject* obj) const { if (m_bIsLinkTool && obj->IsSelected()) { return false; } if (obj->GetGroup()) { if (!obj->GetGroup()->IsOpen() && !m_bSearchInsideObjects) { return false; } } if (!(m_objectTypeMask & obj->GetType())) { return false; } if (m_displayMode == ObjectSelectorModel::DisplayModeVisible) { if (obj->IsHidden() || obj->IsFrozen()) { return false; } } else if (m_displayMode == ObjectSelectorModel::DisplayModeHidden) { if (!obj->IsHidden()) { return false; } } else if (m_displayMode == ObjectSelectorModel::DisplayModeFrozen) { if (!obj->IsFrozen()) { return false; } } CObjectLayer* layer = obj->GetLayer(); if (layer->IsFrozen()) { return false; } if (!layer->IsVisible()) { return false; } if (!m_filterText.isEmpty()) { QString objName = ObjectSelectorModel::GetObjectName(obj); QString objTypeDescription = obj->GetTypeDescription(); QString objLayerName = obj->GetLayer()->GetName(); if (!objName.contains(m_filterText, Qt::CaseInsensitive) && !objTypeDescription.contains(m_filterText, Qt::CaseInsensitive) && !objLayerName.contains(m_filterText, Qt::CaseInsensitive)) { return false; } } if (!m_propertyFilter.isEmpty()) { if (!IsPropertyMatch(obj)) { return false; } } return true; } void ObjectSelectorModel::BuildMaps() { s_trackViewMap.clear(); for (size_t i = 0; i < m_objects.size(); ++i) { AddObjectToMaps(m_objects[i]); } // Now it has the latest data again. m_bTrackViewModified = false; } void ObjectSelectorModel::SetTrackViewModified(bool modified) { m_bTrackViewModified = modified; } bool ObjectSelectorModel::IsTrackViewModified() const { return m_bTrackViewModified; } int ObjectSelectorModel::IndexOfObject(CBaseObject* obj) const { auto it = find(m_objects.cbegin(), m_objects.cend(), obj); return it == m_objects.cend() ? -1 : it - m_objects.cbegin(); } void ObjectSelectorModel::sort(int column, Qt::SortOrder order) { g_sortColumn = column; g_sortOrder = order; if (!m_objects.empty()) { beginResetModel(); std::sort(m_objects.begin(), m_objects.end(), objectLessThan); endResetModel(); } } #include <ObjectSelectorModel.moc>
26.36
133
0.551722
[ "geometry", "object", "vector", "model" ]
54ba5c1f00aad9935680fa2ea6519fb7df36e355
14,753
cpp
C++
libs/scenic/src/scenic/render_context/ffp/object.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/scenic/src/scenic/render_context/ffp/object.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/scenic/src/scenic/render_context/ffp/object.cpp
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) #include <sge/image/color/predef.hpp> #include <sge/image/color/any/object.hpp> #include <sge/renderer/primitive_type.hpp> #include <sge/renderer/caps/device.hpp> #include <sge/renderer/context/core.hpp> #include <sge/renderer/context/ffp.hpp> #include <sge/renderer/context/ffp_ref.hpp> #include <sge/renderer/device/ffp.hpp> #include <sge/renderer/state/core/blend/object.hpp> #include <sge/renderer/state/core/blend/parameters.hpp> #include <sge/renderer/state/core/blend/write_mask_all.hpp> #include <sge/renderer/state/core/depth_stencil/object.hpp> #include <sge/renderer/state/core/depth_stencil/parameters.hpp> #include <sge/renderer/state/core/rasterizer/object.hpp> #include <sge/renderer/state/core/rasterizer/parameters.hpp> #include <sge/renderer/state/core/sampler/object.hpp> #include <sge/renderer/state/core/sampler/parameters.hpp> #include <sge/renderer/state/core/sampler/address/mode_all.hpp> #include <sge/renderer/state/core/sampler/address/parameters.hpp> #include <sge/renderer/state/core/sampler/filter/trilinear.hpp> #include <sge/renderer/state/ffp/lighting/diffuse_from_vertex.hpp> #include <sge/renderer/state/ffp/lighting/enabled.hpp> #include <sge/renderer/state/ffp/lighting/object.hpp> #include <sge/renderer/state/ffp/lighting/parameters.hpp> #include <sge/renderer/state/ffp/lighting/light/const_object_ref_vector.hpp> #include <sge/renderer/state/ffp/lighting/light/object.hpp> #include <sge/renderer/state/ffp/lighting/light/object_unique_ptr.hpp> #include <sge/renderer/state/ffp/lighting/light/parameters.hpp> #include <sge/renderer/state/ffp/lighting/material/object.hpp> #include <sge/renderer/state/ffp/lighting/material/object_unique_ptr.hpp> #include <sge/renderer/state/ffp/lighting/material/parameters.hpp> #include <sge/renderer/state/ffp/transform/mode.hpp> #include <sge/renderer/state/ffp/transform/object.hpp> #include <sge/renderer/state/ffp/transform/object_unique_ptr.hpp> #include <sge/renderer/state/ffp/transform/parameters.hpp> #include <sge/renderer/texture/base.hpp> #include <sge/renderer/texture/planar.hpp> #include <sge/renderer/vertex/buffer.hpp> #include <sge/renderer/vertex/count.hpp> #include <sge/renderer/vertex/first.hpp> #include <sge/renderer/vertex/scoped_buffer.hpp> #include <sge/scenic/exception.hpp> #include <sge/scenic/index_buffer_range.hpp> #include <sge/scenic/render_context/transform_matrix_type.hpp> #include <sge/scenic/render_context/ffp/manager.hpp> #include <sge/scenic/render_context/ffp/object.hpp> #include <sge/scenic/render_context/material/object.hpp> #include <fcppt/make_cref.hpp> #include <fcppt/make_ref.hpp> #include <fcppt/make_unique_ptr.hpp> #include <fcppt/reference_impl.hpp> #include <fcppt/reference_to_base.hpp> #include <fcppt/text.hpp> #include <fcppt/algorithm/map.hpp> #include <fcppt/optional/assign.hpp> #include <fcppt/optional/map.hpp> #include <fcppt/variant/apply.hpp> namespace { struct light_visitor { using result_type = sge::renderer::state::ffp::lighting::light::variant; result_type operator()(sge::scenic::render_context::light::point const &p) const { return sge::renderer::state::ffp::lighting::light::variant{ sge::renderer::state::ffp::lighting::light::point( sge::renderer::state::ffp::lighting::light::position(p.position().get()), sge::renderer::state::ffp::lighting::light::attenuation( sge::renderer::state::ffp::lighting::light::constant_attenuation( p.attenuation().constant_attenuation().get()), sge::renderer::state::ffp::lighting::light::linear_attenuation( p.attenuation().linear_attenuation().get()), sge::renderer::state::ffp::lighting::light::quadratic_attenuation( p.attenuation().quadratic_attenuation().get())))}; } result_type operator()(sge::scenic::render_context::light::directional const &p) const { return sge::renderer::state::ffp::lighting::light::variant{ sge::renderer::state::ffp::lighting::light::directional( sge::renderer::state::ffp::lighting::light::direction(p.direction().get()))}; } }; sge::renderer::state::ffp::lighting::light::parameters transform_light(sge::scenic::render_context::light::object const &_light) { return sge::renderer::state::ffp::lighting::light::parameters( sge::renderer::state::ffp::lighting::diffuse_color(_light.diffuse_color().get()), sge::renderer::state::ffp::lighting::specular_color(_light.specular_color().get()), sge::renderer::state::ffp::lighting::ambient_color(_light.ambient_color().get()), fcppt::variant::apply(light_visitor(), _light.variant())); } } sge::scenic::render_context::ffp::object::object( fcppt::reference<sge::scenic::render_context::ffp::manager> const _manager, sge::renderer::context::ffp_ref const _context) : manager_(_manager), context_(_context), scoped_vertex_declaration_( fcppt::reference_to_base<sge::renderer::context::core>(context_), manager_.get().vertex_declaration_), projection_transform_(), world_transform_(), current_vertex_buffer_size_(0U), current_vertex_buffer_(), current_material_(), diffuse_texture_sampler_(manager_.get().renderer_.get().create_sampler_state( sge::renderer::state::core::sampler::parameters( sge::renderer::state::core::sampler::address::parameters( sge::renderer::state::core::sampler::address::mode_all( sge::renderer::state::core::sampler::address::mode::repeat)), sge::renderer::state::core::sampler::filter::trilinear()))), scoped_sampler_{ fcppt::reference_to_base<sge::renderer::context::core>(_context), sge::renderer::state::core::sampler::const_object_ref_map{ sge::renderer::state::core::sampler::const_object_ref_map::value_type{ sge::renderer::texture::stage{0U}, fcppt::make_cref(*diffuse_texture_sampler_)}}}, current_lighting_(manager_.get().renderer_.get().create_lighting_state( sge::renderer::state::ffp::lighting::parameters( sge::renderer::state::ffp::lighting::variant( sge::renderer::state::ffp::lighting::enabled( sge::renderer::state::ffp::lighting::ambient_color( sge::image::color::any::object{sge::image::color::predef::black()}), sge::renderer::state::ffp::lighting::diffuse_from_vertex(false)))))), depth_stencil_state_(manager_.get().renderer_.get().create_depth_stencil_state( sge::renderer::state::core::depth_stencil::parameters( sge::renderer::state::core::depth_stencil::depth::variant( sge::renderer::state::core::depth_stencil::depth::enabled( sge::renderer::state::core::depth_stencil::depth::func::less, sge::renderer::state::core::depth_stencil::depth::write_enable(true))), sge::renderer::state::core::depth_stencil::stencil::variant( sge::renderer::state::core::depth_stencil::stencil::off())))), blend_state_(manager_.get().renderer_.get().create_blend_state( sge::renderer::state::core::blend::parameters( sge::renderer::state::core::blend::alpha_variant( sge::renderer::state::core::blend::alpha_off()), sge::renderer::state::core::blend::write_mask_all()))), rasterizer_state_(manager_.get().renderer_.get().create_rasterizer_state( sge::renderer::state::core::rasterizer::parameters( sge::renderer::state::core::rasterizer::cull_mode::counter_clockwise, sge::renderer::state::core::rasterizer::fill_mode::solid, sge::renderer::state::core::rasterizer::enable_scissor_test(false)))), scoped_depth_stencil_state_( fcppt::reference_to_base<sge::renderer::context::core>(_context), fcppt::make_cref(*depth_stencil_state_)), scoped_blend_state_( fcppt::reference_to_base<sge::renderer::context::core>(_context), fcppt::make_cref(*blend_state_)), scoped_rasterizer_state_( fcppt::reference_to_base<sge::renderer::context::core>(_context), fcppt::make_cref(*rasterizer_state_)) { context_.get().lighting_state(sge::renderer::state::ffp::lighting::const_optional_object_ref( fcppt::make_cref(*current_lighting_))); } void sge::scenic::render_context::ffp::object::transform( sge::scenic::render_context::transform_matrix_type const _type, sge::renderer::matrix4 const &_matrix) { switch (_type) { case sge::scenic::render_context::transform_matrix_type::projection: { sge::renderer::state::ffp::transform::object_unique_ptr const &cur_transform( fcppt::optional::assign( projection_transform_, manager_.get().renderer_.get().create_transform_state( sge::renderer::state::ffp::transform::parameters(_matrix)))); context_.get().transform( sge::renderer::state::ffp::transform::mode::projection, sge::renderer::state::ffp::transform::const_optional_object_ref( fcppt::make_cref(*cur_transform))); break; } case sge::scenic::render_context::transform_matrix_type::world: { sge::renderer::state::ffp::transform::object_unique_ptr const &cur_transform( fcppt::optional::assign( world_transform_, manager_.get().renderer_.get().create_transform_state( sge::renderer::state::ffp::transform::parameters(_matrix)))); context_.get().transform( sge::renderer::state::ffp::transform::mode::world, sge::renderer::state::ffp::transform::const_optional_object_ref( fcppt::make_cref(*cur_transform))); break; } } } void sge::scenic::render_context::ffp::object::material( sge::scenic::render_context::material::object const &_material) { sge::renderer::state::ffp::lighting::material::object_unique_ptr const &current_material( fcppt::optional::assign( current_material_, manager_.get().renderer_.get().create_material_state( sge::renderer::state::ffp::lighting::material::parameters( sge::renderer::state::ffp::lighting::diffuse_color( _material.diffuse_color().get()), sge::renderer::state::ffp::lighting::ambient_color( _material.ambient_color().get()), sge::renderer::state::ffp::lighting::specular_color( _material.specular_color().get()), sge::renderer::state::ffp::lighting::material::emissive_color( _material.emissive_color().get()), sge::renderer::state::ffp::lighting::material::shininess( _material.shininess().get()))))); context_.get().material_state( sge::renderer::state::ffp::lighting::material::const_optional_object_ref( fcppt::make_cref(*current_material))); context_.get().texture( fcppt::optional::map( _material.diffuse_texture(), [](fcppt::reference<sge::renderer::texture::planar> const _texture) { return fcppt::reference_to_base<sge::renderer::texture::base const>(_texture); }), sge::renderer::texture::stage(0U)); } void sge::scenic::render_context::ffp::object::lights( sge::scenic::render_context::light::sequence const &_lights) { if (_lights.size() >= manager_.get().renderer_.get().caps().light_indices().get()) { throw sge::scenic::exception{FCPPT_TEXT("ffp::object: Too many lights!")}; } context_.get().lights_state( sge::renderer::state::ffp::lighting::light::const_object_ref_vector()); lights_ = fcppt::algorithm::map<light_ptr_vector>( _lights, [this](sge::scenic::render_context::light::object const &_light) { return manager_.get().renderer_.get().create_light_state(transform_light(_light)); }); context_.get().lights_state( fcppt::algorithm::map<sge::renderer::state::ffp::lighting::light::const_object_ref_vector>( lights_, [](sge::renderer::state::ffp::lighting::light::object_unique_ptr const &_light) { return fcppt::make_cref(*_light); })); } void sge::scenic::render_context::ffp::object::vertex_buffer( sge::renderer::vertex::buffer const &_vertex_buffer) { current_vertex_buffer_ = optional_scoped_vertex_buffer_unique_ptr(); current_vertex_buffer_ = optional_scoped_vertex_buffer_unique_ptr( fcppt::make_unique_ptr<sge::renderer::vertex::scoped_buffer>( fcppt::reference_to_base<sge::renderer::context::core>(context_), fcppt::make_cref(_vertex_buffer))); current_vertex_buffer_size_ = sge::renderer::vertex::count{_vertex_buffer.linear_size()}; } void sge::scenic::render_context::ffp::object::fog( sge::scenic::render_context::fog::optional_properties const &) { } void sge::scenic::render_context::ffp::object::render( sge::renderer::index::buffer const &_index_buffer, sge::scenic::index_buffer_range const &_index_buffer_range) { context_.get().render_indexed( _index_buffer, sge::renderer::vertex::first(0U), current_vertex_buffer_size_, sge::renderer::primitive_type::triangle_list, _index_buffer_range.first_index(), _index_buffer_range.index_count()); } sge::renderer::target::base &sge::scenic::render_context::ffp::object::target() { return context_.get().target(); } sge::scenic::render_context::ffp::object::~object() { context_.get().material_state( sge::renderer::state::ffp::lighting::material::const_optional_object_ref()); context_.get().transform( sge::renderer::state::ffp::transform::mode::world, sge::renderer::state::ffp::transform::const_optional_object_ref()); context_.get().transform( sge::renderer::state::ffp::transform::mode::projection, sge::renderer::state::ffp::transform::const_optional_object_ref()); context_.get().texture( sge::renderer::texture::const_optional_base_ref(), sge::renderer::texture::stage(0U)); context_.get().sampler_state( sge::renderer::state::core::sampler::const_optional_object_ref_map()); context_.get().lights_state( sge::renderer::state::ffp::lighting::light::const_object_ref_vector()); context_.get().lighting_state(sge::renderer::state::ffp::lighting::const_optional_object_ref()); }
46.247649
100
0.690571
[ "render", "object", "transform", "solid" ]
54c520669d2b35ad82fcefd38ca4e205db818777
6,403
cpp
C++
player/src/ui/overlays/video_details.cpp
Globidev/twitch-player
062306685e182c422980d57fe7ba9fbdee141c37
[ "MIT" ]
36
2018-03-09T08:05:32.000Z
2021-09-09T19:06:39.000Z
player/src/ui/overlays/video_details.cpp
Globidev/twitch-player
062306685e182c422980d57fe7ba9fbdee141c37
[ "MIT" ]
35
2018-03-15T06:43:49.000Z
2021-04-14T00:07:00.000Z
player/src/ui/overlays/video_details.cpp
Globidev/twitch-player
062306685e182c422980d57fe7ba9fbdee141c37
[ "MIT" ]
3
2018-05-18T21:17:05.000Z
2021-09-09T19:06:42.000Z
#include "ui/overlays/video_details.hpp" #include "ui_stream_details.h" #include "prelude/timer.hpp" #include <QTimer> #include <QMouseEvent> #include <QPainter> #include <QPushButton> #include "ui/native/capabilities.hpp" VideoDetails::VideoDetails(QWidget *parent): QWidget(parent), _state_timer(new QTimer(this)), _spinner(":/images/kappa.png"), _spinner_timer(new QTimer(this)), _stream_details_widget(std::make_unique<QWidget>()), _stream_details_ui(std::make_unique<Ui::StreamDetails>()), _stream_details_timer(new QTimer(this)), _http_client(new QNetworkAccessManager(this)) { setWindowFlags(Qt::Window | Qt::FramelessWindowHint); setAttribute(Qt::WA_NoSystemBackground); setAttribute(Qt::WA_TranslucentBackground); setAttribute(Qt::WA_TransparentForMouseEvents); _state_text_font.setBold(true); _state_text_font.setPointSize(40); _state_text_font.setWeight(40); _state_timer->setInterval(2500); QObject::connect(_state_timer, &QTimer::timeout, [this] { _show_state_text = false; repaint(); }); _spinner_timer->setInterval(20); QObject::connect(_spinner_timer, &QTimer::timeout, [this] { _spinner_angle = (_spinner_angle + 6) % 360; repaint(); }); _stream_details_timer->setInterval(2500); QObject::connect(_stream_details_timer, &QTimer::timeout, [this] { hide_stream_details(); }); _stream_details_ui->setupUi(_stream_details_widget.get()); interval(this, 60 * 1000, [=] { fetch_channel_details(); }); _http_client->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy); set_transparent(to_native_handle(winId())); } VideoDetails::~VideoDetails() = default; void VideoDetails::mouseReleaseEvent(QMouseEvent *event) { event->ignore(); parentWidget()->activateWindow(); }; void VideoDetails::paintEvent(QPaintEvent *event) { if(_show_stream_details && _has_valid_stream_details) draw_stream_details(); if (_show_state_text) draw_state_text(); if (_show_spinner) draw_spinner(); QWidget::paintEvent(event); } void VideoDetails::draw_state_text() { QPainter painter { this }; painter.setFont(_state_text_font); painter.setPen(Qt::white); QRect br; painter.drawText(rect(), Qt::AlignTop | Qt::AlignRight, _state_text, &br); QLinearGradient gradient(br.topLeft(), br.bottomLeft()); gradient.setColorAt(0, QColor(0, 0, 0, 0xB0)); gradient.setColorAt(1, QColor(0, 0, 0, 0x00)); painter.fillRect(br, QBrush(gradient)); painter.drawText(rect(), Qt::AlignTop | Qt::AlignRight, _state_text); } void VideoDetails::draw_spinner() { QPainter painter { this }; auto centered_rect = _spinner.rect(); auto aspect_ratio = (float)centered_rect.height() / centered_rect.width(); if (rect().width() < centered_rect.width()) { auto new_width = rect().width(); centered_rect.setWidth(new_width); centered_rect.setHeight(new_width * aspect_ratio); } if (rect().height() < centered_rect.height()) { auto new_height = rect().height(); centered_rect.setHeight(new_height); centered_rect.setWidth(new_height / aspect_ratio); } centered_rect.moveCenter(rect().center()); painter.translate(rect().center()); painter.rotate(_spinner_angle); painter.drawImage( centered_rect.translated(-rect().center()), _spinner ); } void VideoDetails::draw_stream_details() { // QPainter painter { this }; _stream_details_widget->resize(width(), _stream_details_widget->height()); _stream_details_widget->render(this); } void VideoDetails::show_state(const QString &state) { _state_text = state; _state_timer->start(); _show_state_text = true; repaint(); } void VideoDetails::set_buffering(bool enabled) { if (enabled == _show_spinner) return ; _show_spinner = enabled; _spinner_angle = 0; if (enabled) _spinner_timer->start(); else _spinner_timer->stop(); repaint(); } void VideoDetails::show_stream_details() { _stream_details_timer->start(); _show_stream_details = true; repaint(); } void VideoDetails::set_channel(const QString &channel) { _channel = channel; _stream_details_ui->channelLogo->setPixmap(QPixmap{}); _has_valid_stream_details = false; fetch_channel_details(); } void VideoDetails::hide_stream_details() { _show_stream_details = false; repaint(); } void VideoDetails::fetch_channel_details() { auto fill_stream_info = [=](StreamData data) { if (_stream_details_ui->channelLogo->pixmap()->isNull()) fetch_channel_logo(data.channel.logo_url); auto uptime_secs = data.created_at.secsTo(QDateTime::currentDateTime()); auto uptime_hours = uptime_secs / 3600; auto uptime_minutes = (uptime_secs - uptime_hours * 3600) / 60; _stream_details_ui->labelChannel->setText(_channel.toUpper()); _stream_details_ui->labelTitle->setText(data.channel.title); _stream_details_ui->labelPlaying->setText(data.current_game); _stream_details_ui->labelViewcount->setText(QString::number(data.viewcount)); _stream_details_ui->labelUptime->setText(QString("%1:%2").arg(uptime_hours).arg(uptime_minutes, 2, 10, QChar('0'))); _has_valid_stream_details = true; repaint(); }; auto fetch_stream = [=](QList<ChannelData> channels) { auto channel_it = std::find_if( channels.begin(), channels.end(), [=](ChannelData channel) { return channel.name == _channel; } ); if (channel_it != channels.end()) return _api.stream(channel_it->id); else return TwitchAPI::stream_response_t::reject("Channel not found"); }; _api.channel_search(_channel) .then(fetch_stream) .then(fill_stream_info); } void VideoDetails::fetch_channel_logo(const QString &url) { auto request = QNetworkRequest(QUrl(url)); auto preview_reply = _http_client->get(request); QObject::connect(preview_reply, &QNetworkReply::finished, [=] { auto data = preview_reply->readAll(); auto pixmap = QPixmap::fromImage(QImage::fromData(data)); _stream_details_ui->channelLogo->setPixmap(pixmap); preview_reply->deleteLater(); }); }
30.636364
124
0.682493
[ "render" ]
54c8822e6fc2edccf7658ebc0cb45b24556421a6
1,091
cc
C++
Projects/SSAO/SSAO.cc
mnrn/ReGL
922b36716ff29fa5ed8f18c078d2369ef9fba6a9
[ "MIT" ]
null
null
null
Projects/SSAO/SSAO.cc
mnrn/ReGL
922b36716ff29fa5ed8f18c078d2369ef9fba6a9
[ "MIT" ]
null
null
null
Projects/SSAO/SSAO.cc
mnrn/ReGL
922b36716ff29fa5ed8f18c078d2369ef9fba6a9
[ "MIT" ]
null
null
null
/** * @brief スクリーンスペースアンビエントオクルージョン */ #include "SSAO.h" #include <glm/gtc/constants.hpp> // ******************************************************************************** // Sampling for SSAO // ******************************************************************************** std::vector<float> SSAO::BuildKernel(std::size_t kernelSize) { std::vector<float> kern(3 * kernelSize); for (size_t i = 0; i < kernelSize; i++) { glm::vec3 randDir = dist_.OnHemisphere(engine_); const float kScale = static_cast<float>(i * i) / static_cast<float>(kernelSize * kernelSize); randDir *= glm::mix(0.1f, 1.0f, kScale); kern[3 * i + 0] = randDir.x; kern[3 * i + 1] = randDir.y; kern[3 * i + 2] = randDir.z; } return kern; } std::vector<float> SSAO::BuildRandRot(std::size_t rotTexSize) { std::vector<float> randDir(3 * rotTexSize * rotTexSize); for (size_t i = 0; i < rotTexSize * rotTexSize; i++) { glm::vec2 v = dist_.OnCircle(engine_); randDir[3 * i + 0] = v.x; randDir[3 * i + 1] = v.y; randDir[3 * i + 2] = 0.0f; } return randDir; }
29.486486
97
0.52154
[ "vector" ]
54c9f08cbd73906512d49d761c7d344ad7b6ca57
4,375
cpp
C++
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/elements/SoListenerOrientationElement.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/elements/SoListenerOrientationElement.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/elements/SoListenerOrientationElement.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ /*! \class SoListenerOrientationElement Inventor/elements/SoListenerOrientationElement.h \brief The SoListenerOrientationElement holds the orientation of the current listener. \ingroup elements This orientation is set by SoListener nodes and SoCamera Nodes during audio rendering. When a SoListener is visited by the SoAudioRenderAction, it will add a new SoListenerOrientationElement to the state, holding it's orientation and with the setbylistener flag set. When a SoCamera is visited by SoAudioRenderAction, it will add a new SoListenerOrientationElement only if there are no previous elements with the setbylistener flag set. The SoListenerOrientationElement is used when the SoVRMLSound nodes render themselves. \COIN_CLASS_EXTENSION \since Coin 2.0 */ #include <Inventor/elements/SoListenerOrientationElement.h> #include "coindefs.h" #include "SbBasicP.h" #include <Inventor/nodes/SoNode.h> /*! \fn SoListenerOrientationElement::orientation The orientation of the listener. Can be set by the SoListener class or the SoCamera class. */ SO_ELEMENT_SOURCE(SoListenerOrientationElement); /*! This static method initializes static data for the SoListenerOrientationElement class. */ void SoListenerOrientationElement::initClass(void) { SO_ELEMENT_INIT_CLASS(SoListenerOrientationElement, inherited); } /*! The destructor. */ SoListenerOrientationElement::~SoListenerOrientationElement(void) { } /*! Initializes the element to it's default value. The default value for the orientation is (0.0f, 0.0f, 1.0f, 0.0f) and the default value for the setByListener flag is FALSE. */ void SoListenerOrientationElement::init(SoState * state) { inherited::init(state); this->orientation = SbRotation(0.0f, 0.0f, 1.0f, 0.0f); this->setbylistener = FALSE; } /*! Sets the current listener orientation, and indicates if it was set by a SoListener node or a SoCamera node. */ void SoListenerOrientationElement::set(SoState * const state, SoNode * const COIN_UNUSED_ARG(node), const SbRotation & orientation, SbBool setbylistener) { SoListenerOrientationElement *elem = coin_safe_cast<SoListenerOrientationElement *> ( SoElement::getElement(state,classStackIndex) ); if (elem) { elem->orientation = orientation; elem->setbylistener = setbylistener; } } //! Returns the current listener orientation const SbRotation & SoListenerOrientationElement::get(SoState * const state) { const SoListenerOrientationElement * elem = coin_assert_cast<const SoListenerOrientationElement *> ( SoElement::getConstElement(state, classStackIndex) ); return elem->orientation; } /*! Returns TRUE if the orientation was set by a SoListener node, and FALSE if it was set by a SoCamera node */ SbBool SoListenerOrientationElement::isSetByListener(SoState * const state) { const SoListenerOrientationElement * elem = coin_assert_cast<const SoListenerOrientationElement *> ( SoElement::getConstElement(state, classStackIndex) ); return elem->setbylistener; } //! Prints the contents of the element (unimplemented) void SoListenerOrientationElement::print(FILE * /* file */) const { }
28.97351
88
0.7136
[ "render", "3d" ]
54ca39d8e7393a9f6d294623129115f6290ebc00
6,875
cc
C++
3rdparty/pytorch/caffe2/core/net.cc
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
3rdparty/pytorch/caffe2/core/net.cc
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
3rdparty/pytorch/caffe2/core/net.cc
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
#include "caffe2/core/net.h" #include "caffe2/core/net_simple.h" #include <set> #include <unordered_map> #include <unordered_set> #include "caffe2/core/init.h" #include "caffe2/core/operator.h" #include "caffe2/core/timer.h" #include "caffe2/proto/caffe2_pb.h" #include "caffe2/utils/proto_utils.h" #include "caffe2/utils/string_utils.h" C10_DEFINE_string( caffe2_override_executor, "", "Comma-separated list of executor overrides"); namespace caffe2 { C10_DEFINE_REGISTRY( NetRegistry, NetBase, const std::shared_ptr<const NetDef>&, Workspace*); NetBase::NetBase( const std::shared_ptr<const NetDef>& def, Workspace* /* unused */) : external_input_( def->external_input().begin(), def->external_input().end()), external_output_( def->external_output().begin(), def->external_output().end()), name_(def->name()), net_def_(def) { static GlobalInitIsCalledGuard guard; // Check that node_name is empty for all ops for (const OperatorDef& op : def->op()) { if (op.has_device_option()) { CAFFE_ENFORCE( !op.device_option().has_node_name(), "node_name must be empty for all operators at execution time."); } } // Go through the operators and make sure that blobs are correctly made. std::set<string> known_blobs( external_input_.begin(), external_input_.end()); std::set<string> remaining_output( external_output_.begin(), external_output_.end()); for (const auto& blob : known_blobs) { remaining_output.erase(blob); } for (const OperatorDef& op : def->op()) { for (const string& in : op.input()) { if (!known_blobs.count(in)) { if (external_input_.size()) { CAFFE_THROW( "op ", op.type(), ": Source for input ", in, " is unknown for net ", def->name(), ", operator ", ProtoDebugString(op)); } else { // If we are not declaring input and output, we will simply VLOG it // for debugging purposes. VLOG(1) << "op " << op.type() << ": input " << in << " is unknown."; } } } for (const string& out : op.output()) { known_blobs.insert(out); remaining_output.erase(out); } } // Finally, check if all declared outputs are being created. CAFFE_ENFORCE( remaining_output.size() == 0, "Some of the blobs are declared as output but never produced by the " "net ", def->name(), ", the first one is ", *remaining_output.begin()); } bool NetBase::RunAsync() { for (auto& op : GetOperators()) { op->ResetEvent(); } return DoRunAsync(); } namespace { const std::string kSimpleNet = "simple"; std::vector<NetObserverCreator>* GetNetObserverCreators() { static std::vector<NetObserverCreator> creators; return &creators; } const std::unordered_map<std::string, std::string>& defaultOverrides() { // redirecting legacy net types to async_scheduling (except for 'simple'); // async_scheduling checks net type for backward compatibility static const std::unordered_map<std::string, std::string> overrides = { {"dag", "async_scheduling"}, {"prof_dag", "async_scheduling"}, {"async_dag", "async_scheduling"}, {"async_polling", "async_scheduling"}, {"async_simple", "simple"}, // "async_simple" impl has been removed. {"rnn", "simple"}, // "rnn" impl has been removed. }; return overrides; } void ApplyPotentialExecutorOverride(std::string* net_type) { auto executors = caffe2::split(',', FLAGS_caffe2_override_executor); CAFFE_ENFORCE( executors.size() % 2 == 0, "Invalid override executors flag value"); std::unordered_map<std::string, std::string> overrides; for (const auto& kv : defaultOverrides()) { overrides[kv.first] = kv.second; } for (size_t idx = 0; idx < executors.size(); idx += 2) { overrides[executors[idx]] = executors[idx + 1]; } if (overrides.count(*net_type)) { VLOG(1) << "Overrode net type '" << *net_type << "' with '" << overrides[*net_type] << "'"; *net_type = overrides[*net_type]; } } } // namespace void AddGlobalNetObserverCreator(NetObserverCreator creator) { GetNetObserverCreators()->push_back(creator); VLOG(1) << "Have set a custom GlobalNetObserverCreator"; } void ClearGlobalNetObservers() { GetNetObserverCreators()->clear(); VLOG(1) << "All net observers cleared"; } unique_ptr<NetBase> CreateNet(const NetDef& net_def, Workspace* ws) { std::shared_ptr<NetDef> tmp_net_def(new NetDef(net_def)); return CreateNet(tmp_net_def, ws); } unique_ptr<NetBase> CreateNet( const std::shared_ptr<const NetDef>& net_def, Workspace* ws) { std::string net_type; if (net_def->has_type()) { net_type = net_def->type(); } else { // By default, we will return a simple network that just runs all operators // sequentially. net_type = kSimpleNet; } ApplyPotentialExecutorOverride(&net_type); unique_ptr<NetBase> net = NetRegistry()->Create(net_type, net_def, ws); VLOG(1) << "Adding a global observer to a net"; if (net) { auto* observer_creators = GetNetObserverCreators(); for (auto& creator : *observer_creators) { net->AttachObserver(creator(net.get())); } } return net; } TaskThreadPoolBase* ExecutorHelper::GetPool( const DeviceOption& /* unused */) const { CAFFE_THROW("Not implemented"); } std::vector<OperatorBase*> ExecutorHelper::GetOperators() const { CAFFE_THROW("Not implemented"); } int ExecutorHelper::GetNumWorkers() const { CAFFE_THROW("Not implemented"); } std::vector<float> NetBase::TEST_Benchmark( const int warmup_runs, const int main_runs, const bool run_individual) { LOG(INFO) << "Starting benchmark, running warmup runs"; CAFFE_ENFORCE( warmup_runs >= 0, "Number of warm up runs should be non negative, provided ", warmup_runs); for (int run_idx = 0; run_idx < warmup_runs; ++run_idx) { CAFFE_ENFORCE(Run(), "Warmup run ", run_idx, " has failed"); } LOG(INFO) << "Running main runs"; CAFFE_ENFORCE( main_runs >= 0, "Number of main runs should be non negative, provided ", main_runs); Timer timer; for (int run_idx = 0; run_idx < main_runs; ++run_idx) { CAFFE_ENFORCE(Run(), "Main run ", run_idx, " has failed"); } auto millis = timer.MilliSeconds(); LOG(INFO) << "Main runs finished. Milliseconds per iter: " << millis / main_runs << ". Iters per second: " << 1000.0 * main_runs / millis; if (run_individual) { LOG(INFO) << "Net does not support per-op benchmark; " "to run it, switch to a simple net type"; } return std::vector<float>{millis / main_runs}; } } // namespace caffe2
30.021834
79
0.6432
[ "vector" ]
54d8e92f6490359708b681660081ee083b9ba00e
3,034
cc
C++
libraries/mosek/9.3/tools/examples/fusion/cxx/gp1.cc
TimDSF/SBSOS_ShapeSegmentation
e30495dcf71dc63d1d54f3b73132fcfa75d7647e
[ "MIT" ]
null
null
null
libraries/mosek/9.3/tools/examples/fusion/cxx/gp1.cc
TimDSF/SBSOS_ShapeSegmentation
e30495dcf71dc63d1d54f3b73132fcfa75d7647e
[ "MIT" ]
null
null
null
libraries/mosek/9.3/tools/examples/fusion/cxx/gp1.cc
TimDSF/SBSOS_ShapeSegmentation
e30495dcf71dc63d1d54f3b73132fcfa75d7647e
[ "MIT" ]
1
2022-02-24T02:51:35.000Z
2022-02-24T02:51:35.000Z
// // Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved. // // File: gp1.cc // // Purpose: Demonstrates how to solve a simple Geometric Program (GP) // cast into conic form with exponential cones and log-sum-exp. // // Example from // https://gpkit.readthedocs.io/en/latest/examples.html//maximizing-the-volume-of-a-box // #include <string> #include <iostream> #include <iomanip> #include <cmath> #include "fusion.h" using namespace mosek::fusion; using namespace monty; // Models log(sum(exp(Ax+b))) <= 0. // Each row of [A b] describes one of the exp-terms void logsumexp(Model::t M, std::shared_ptr<ndarray<double, 2>> A, Variable::t x, std::shared_ptr<ndarray<double, 1>> b) { int k = A->size(0); auto u = M->variable(k); M->constraint(Expr::sum(u), Domain::equalsTo(1.0)); M->constraint(Expr::hstack(u, Expr::constTerm(k, 1.0), Expr::add(Expr::mul(A, x), b)), Domain::inPExpCone()); } // maximize h*w*d // subjecto to 2*(h*w + h*d) <= Awall // w*d <= Afloor // alpha <= h/w <= beta // gamma <= d/w <= delta // // Variable substitutions: h = exp(x), w = exp(y), d = exp(z). // // maximize x+y+z // subject log( exp(x+y+log(2/Awall)) + exp(x+z+log(2/Awall)) ) <= 0 // y+z <= log(Afloor) // log( alpha ) <= x-y <= log( beta ) // log( gamma ) <= z-y <= log( delta ) std::shared_ptr<ndarray<double, 1>> max_volume_box(double Aw, double Af, double alpha, double beta, double gamma, double delta) { Model::t M = new Model("max_vol_box"); auto _M = finally([&]() { M->dispose(); }); auto xyz = M->variable(3); M->objective("Objective", ObjectiveSense::Maximize, Expr::sum(xyz)); logsumexp(M, new_array_ptr<double,2>({{1,1,0}, {1,0,1}}), xyz, new_array_ptr<double,1>({log(2.0/Aw), log(2.0/Aw)})); M->constraint(Expr::dot(new_array_ptr<double,1>({0,1,1}), xyz), Domain::lessThan(log(Af))); M->constraint(Expr::dot(new_array_ptr<double,1>({1,-1,0}), xyz), Domain::inRange(log(alpha),log(beta))); M->constraint(Expr::dot(new_array_ptr<double,1>({0,-1,1}), xyz), Domain::inRange(log(gamma),log(delta))); M->setLogHandler([](const std::string & msg) { std::cout << msg << std::flush; } ); M->solve(); return std::make_shared<ndarray<double, 1>>(shape(3), [xyz](ptrdiff_t i) { return exp((*(xyz->level()))[i]); }); } int main() { double Aw = 200.0; double Af = 50.0; double alpha = 2.0; double beta = 10.0; double gamma = 2.0; double delta = 10.0; auto hwd = max_volume_box(Aw, Af, alpha, beta, gamma, delta); std::cout << std::setprecision(4); std::cout << "h=" << (*hwd)[0] << " w=" << (*hwd)[1] << " d=" << (*hwd)[2] << std::endl; }
35.694118
114
0.534278
[ "shape", "model" ]
54d9af85b8af40a514bfabc95788334394279ffd
519
cpp
C++
test/plane_tests.cpp
dillonhuff/scg
21d004ce37c0e0e3650e373726d7e8bac51fffa4
[ "MIT" ]
14
2018-05-10T16:40:38.000Z
2020-01-09T06:36:09.000Z
test/plane_tests.cpp
dillonhuff/scg
21d004ce37c0e0e3650e373726d7e8bac51fffa4
[ "MIT" ]
1
2019-10-26T13:08:56.000Z
2019-10-26T13:08:56.000Z
test/plane_tests.cpp
dillonhuff/scg
21d004ce37c0e0e3650e373726d7e8bac51fffa4
[ "MIT" ]
2
2020-11-28T17:36:45.000Z
2021-05-30T14:32:05.000Z
#include "catch.hpp" #include "geometry/plane.h" namespace gca { TEST_CASE("Plane line intersection") { plane p(point(0, 0, 1), point(0, 0, 0)); SECTION("Line that does not intersect") { line l(point(10, 0, 6), point(11, 0, 7)); REQUIRE(!intersection(p, l)); } SECTION("Line that does intersect") { line l(point(0, 0, 10), point(0, 0, -10)); boost::optional<point> r = intersection(p, l); REQUIRE(r); REQUIRE(within_eps(*r, point(0, 0, 0), 0.001)); } } }
23.590909
53
0.572254
[ "geometry" ]
54e0e26e2ee2befafab01dcc8c8399a154db3cbd
5,265
hpp
C++
cpp/src/shared/forcing_helpers/rank_one_forcing.hpp
fnrizzi/ElasticShearWaves
b09cde0711562412c6bc24de0d18ad3a972b7289
[ "BSD-3-Clause" ]
null
null
null
cpp/src/shared/forcing_helpers/rank_one_forcing.hpp
fnrizzi/ElasticShearWaves
b09cde0711562412c6bc24de0d18ad3a972b7289
[ "BSD-3-Clause" ]
null
null
null
cpp/src/shared/forcing_helpers/rank_one_forcing.hpp
fnrizzi/ElasticShearWaves
b09cde0711562412c6bc24de0d18ad3a972b7289
[ "BSD-3-Clause" ]
null
null
null
#ifndef RANK_ONE_FORCING_HPP_ #define RANK_ONE_FORCING_HPP_ #include "map_point_source_to_velocity_grid_point.hpp" #include "KokkosBlas1_fill.hpp" #include "KokkosBlas1_scal.hpp" template <typename sc_t, typename state_d_t, typename int_t> class RankOneForcing { static_assert(is_vector_kokkos< state_d_t >::value, "Rank-1 forcing must use a rank-1 kokkos view"); using state_h_t = typename state_d_t::host_mirror_type; // f_h_ contains the full time series of the signal state_h_t f_h_; // f_d_ contains the forcing vector over the mesh state_d_t f_d_; // // indicator_d_ is all zeros except for the entry where forcing acts // // this is set upon construction, and used to evaluate the forcing // // each time the evaluation is requested, see evaluate method below // state_d_t indicator_d_; // The signal is always associated with a velocity point, not a stress point. // myVpGid_ identifies which velocity point the signal is located at int_t myVpGid_ = -1; sc_t maxFreq_ = {}; const sc_t dt_ = {}; const int_t NSteps_ = {}; public: template <typename signal_t, typename parser_t, typename mesh_info_t, typename app_t> RankOneForcing(const signal_t & signalObj, const parser_t & parser, const mesh_info_t & meshInfo, const app_t & appObj, const sc_t depthKm, const sc_t angleDeg) : f_h_("Fh", parser.getNumSteps()), f_d_("Fd", meshInfo.getNumResidualVpPts()), dt_(parser.getTimeStepSize()), NSteps_(parser.getNumSteps()), /*indicator_d_("Indic_d", meshInfo.getNumResidualVpPts()),*/ maxFreq_(signalObj.getFrequency()) { const auto gidsVp = appObj.viewGidListHost(dofId::vp); const auto coords = appObj.viewCoordsHost(dofId::vp); // find the vpGid identifying the grid point where the source is mapped to const sc_t myRadiusKm = constants<sc_t>::earthSurfaceRadiusKm() - depthKm; mapPointSourceToGridPoint(angleDeg, myRadiusKm, depthKm, meshInfo.viewDomainBounds(), meshInfo.getNumResidualVpPts(), gidsVp, coords, meshInfo.getAngularSpacing(), myVpGid_); KokkosBlas::fill(f_h_, constants<sc_t>::zero()); KokkosBlas::fill(f_d_, constants<sc_t>::zero()); // // set the target entry in the indicator host vector equal to 1 // state_h_t indicator_h = Kokkos::create_mirror_view(indicator_d_); // KokkosBlas::fill(indicator_h, constants<sc_t>::zero()); // indicator_h(myVpGid_) = constants<sc_t>::one(); // Kokkos::deep_copy(indicator_d_, indicator_h); // store the full time series of the signal into the host array storeSignalTimeSeries(signalObj); } template <typename parser_t, typename mesh_info_t, typename app_t> RankOneForcing(const parser_t & parser, const mesh_info_t & meshInfo, const app_t & appObj) : RankOneForcing(Signal<sc_t>(parser.getSourceSignalKind(), parser.getSourceProperty("delay"), parser.getSourceProperty("period")), parser, meshInfo, appObj, parser.getSourceProperty("depth"), parser.getSourceProperty("angle")) {} template <typename signal_t> void replaceSignal(const signal_t & newSignal) { maxFreq_ = newSignal.getFrequency(); KokkosBlas::fill(f_h_, constants<sc_t>::zero()); storeSignalTimeSeries(newSignal); } private: template <typename signal_t> void storeSignalTimeSeries(const signal_t signal){ // store the full time series of the signal into the host array sc_t time = constants<sc_t>::zero(); for (int_t iStep = 1; iStep<=NSteps_; ++iStep){ signal(time, f_h_(iStep-1)); time = iStep * dt_; } } public: // for single source, max frquency is the frequency of the source signal sc_t getMaxFreq() const{ return maxFreq_; } int_t getVpGid() const{ return myVpGid_; } sc_t getForcingValueAtStep(std::size_t step) const{ return f_h_(step-1); } state_d_t viewForcingDevice() const{ return f_d_; } void evaluate(sc_t time, std::size_t step){ KokkosBlas::fill(f_d_, constants<sc_t>::zero()); const auto src = Kokkos::subview(f_h_, step-1); const auto des = Kokkos::subview(f_d_, myVpGid_); Kokkos::deep_copy(des, src); } void complexityOfEvaluateMethod(double & memCostMB, double flopsCost) const{ // no operation is done during evaluate, just copying, see above const double memMBCostFill = 1.*( f_d_.extent(0)*sizeof(sc_t) )/1024./1024.; // for copy we have one read + one write const double memMBCostCopy = 1.*( 2*sizeof(sc_t) )/1024./1024.; memCostMB = memMBCostFill + memMBCostCopy; flopsCost = 0.; } // // // *** for non-host **** // // template <typename _state_d_t = state_d_t> // // typename std::enable_if< !is_accessible_on_host<_state_d_t>::value >::type // // evaluate(sc_t time, std::size_t step){ // // KokkosBlas::scal(f_d_, f_h_(step-1), indicator_d_); // // } // template <typename _state_d_t = state_d_t> // typename std::enable_if< !is_accessible_on_host<_state_d_t>::value >::type // complexity(double & memCostMB, double flopsCost) const{ // using ord_t = typename state_d_t::traits::size_type; // using comp_t = Complexity<sc_t, ord_t>; // comp_t::scal(f_d_.extent(0), memCostMB, flopsCost); // } }; #endif
35.1
87
0.701235
[ "mesh", "vector" ]
54e3b12130278ed85821aafe8c5a789416e5f8b0
7,990
cpp
C++
phoenix/gtk/widget/list-view.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
4
2015-08-02T06:48:46.000Z
2017-10-15T14:46:35.000Z
phoenix/gtk/widget/list-view.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
null
null
null
phoenix/gtk/widget/list-view.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
null
null
null
namespace phoenix { static void ListView_activate(GtkTreeView* treeView, GtkTreePath* path, GtkTreeViewColumn* column, ListView* self) { char* pathname = gtk_tree_path_to_string(path); unsigned selection = decimal(pathname); g_free(pathname); self->state.selection = selection; if(self->onActivate) self->onActivate(); } static void ListView_change(GtkTreeView* treeView, ListView* self) { GtkTreeIter iter; if(!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(treeView), 0, &iter)) return; //should not be possible char* path = gtk_tree_model_get_string_from_iter(gtk_tree_view_get_model(treeView), &iter); unsigned selection = decimal(path); g_free(path); if(!self->state.selected || self->state.selection != selection) { self->state.selected = true; self->state.selection = selection; if(self->onChange) self->onChange(); } } static void ListView_toggle(GtkCellRendererToggle* cell, gchar* path, ListView* self) { unsigned selection = decimal(path); self->setChecked(selection, !self->checked(selection)); if(self->onToggle) self->onToggle(selection); } void pListView::append(const lstring& text) { GtkTreeIter iter; gtk_list_store_append(store, &iter); for(unsigned n = 0; n < text.size(); n++) { gtk_list_store_set(store, &iter, 1 + n * 2 + 1, (const char*)text[n], -1); } } void pListView::autoSizeColumns() { gtk_tree_view_columns_autosize(GTK_TREE_VIEW(subWidget)); } bool pListView::focused() { return GTK_WIDGET_HAS_FOCUS(subWidget); } void pListView::remove(unsigned selection) { GtkTreeModel* model = gtk_tree_view_get_model(GTK_TREE_VIEW(subWidget)); GtkTreeIter iter; gtk_tree_model_get_iter_from_string(model, &iter, string(selection)); gtk_list_store_remove(store, &iter); } void pListView::reset() { listView.state.selected = false; listView.state.selection = 0; gtk_list_store_clear(GTK_LIST_STORE(store)); gtk_tree_view_set_model(GTK_TREE_VIEW(subWidget), GTK_TREE_MODEL(store)); //reset gtk_scrolled_window scrollbar position to 0,0 (top-left), as ListView is now empty gtk_scrolled_window_set_hadjustment(GTK_SCROLLED_WINDOW(gtkWidget), 0); gtk_scrolled_window_set_vadjustment(GTK_SCROLLED_WINDOW(gtkWidget), 0); } void pListView::setCheckable(bool checkable) { gtk_cell_renderer_set_visible(column(0).checkbutton, checkable); } void pListView::setChecked(unsigned selection, bool checked) { GtkTreeModel* model = gtk_tree_view_get_model(GTK_TREE_VIEW(subWidget)); GtkTreeIter iter; gtk_tree_model_get_iter_from_string(model, &iter, string(selection)); gtk_list_store_set(GTK_LIST_STORE(model), &iter, 0, checked, -1); } void pListView::setHeaderText(const lstring& text) { destructor(); constructor(); } void pListView::setHeaderVisible(bool visible) { gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(subWidget), visible); } void pListView::setImage(unsigned selection, unsigned position, const image& image) { GtkTreeModel* model = gtk_tree_view_get_model(GTK_TREE_VIEW(subWidget)); GtkTreeIter iter; gtk_tree_model_get_iter_from_string(model, &iter, string(selection)); if(image.empty() == false) { GdkPixbuf* pixbuf = CreatePixbuf(image, true); gtk_list_store_set(store, &iter, 1 + position * 2, pixbuf, -1); } else { gtk_list_store_set(store, &iter, 1 + position * 2, nullptr, -1); } } void pListView::setSelected(bool selected) { if(selected == false) { GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(subWidget)); gtk_tree_selection_unselect_all(selection); } else { setSelection(listView.state.selection); } } void pListView::setSelection(unsigned selection) { GtkTreeSelection* treeSelection = gtk_tree_view_get_selection(GTK_TREE_VIEW(subWidget)); GtkTreeModel* model = gtk_tree_view_get_model(GTK_TREE_VIEW(subWidget)); gtk_tree_selection_unselect_all(treeSelection); GtkTreeIter iter; if(gtk_tree_model_get_iter_from_string(model, &iter, string(selection)) == false) return; gtk_tree_selection_select_iter(treeSelection, &iter); //scroll window to selected item char* path = gtk_tree_model_get_string_from_iter(model, &iter); GtkTreePath* treePath = gtk_tree_path_new_from_string(path); gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(subWidget), treePath, nullptr, true, 0.5, 0.0); gtk_tree_path_free(treePath); g_free(path); } void pListView::setText(unsigned selection, unsigned position, string text) { GtkTreeModel* model = gtk_tree_view_get_model(GTK_TREE_VIEW(subWidget)); GtkTreeIter iter; gtk_tree_model_get_iter_from_string(model, &iter, string(selection)); gtk_list_store_set(store, &iter, 1 + position * 2 + 1, (const char*)text, -1); } void pListView::constructor() { gtkWidget = gtk_scrolled_window_new(0, 0); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(gtkWidget), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(gtkWidget), GTK_SHADOW_ETCHED_IN); lstring headerText = listView.state.headerText; if(headerText.size() == 0) headerText.append(""); //ListView must have at least one column column.reset(); vector<GType> gtype; for(auto& text : headerText) { GtkColumn cell; cell.label = gtk_label_new(text); cell.column = gtk_tree_view_column_new(); gtk_tree_view_column_set_resizable(cell.column, true); gtk_tree_view_column_set_title(cell.column, ""); if(column.size() == 0) { //first column checkbutton cell.checkbutton = gtk_cell_renderer_toggle_new(); gtk_tree_view_column_pack_start(cell.column, cell.checkbutton, false); gtk_tree_view_column_set_attributes(cell.column, cell.checkbutton, "active", gtype.size(), nullptr); gtype.append(G_TYPE_BOOLEAN); g_signal_connect(cell.checkbutton, "toggled", G_CALLBACK(ListView_toggle), (gpointer)&listView); } cell.icon = gtk_cell_renderer_pixbuf_new(); gtk_tree_view_column_pack_start(cell.column, cell.icon, false); gtk_tree_view_column_set_attributes(cell.column, cell.icon, "pixbuf", gtype.size(), nullptr); gtype.append(GDK_TYPE_PIXBUF); cell.text = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(cell.column, cell.text, false); gtk_tree_view_column_set_attributes(cell.column, cell.text, "text", gtype.size(), nullptr); gtype.append(G_TYPE_STRING); column.append(cell); } store = gtk_list_store_newv(gtype.size(), gtype.data()); subWidget = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); gtk_container_add(GTK_CONTAINER(gtkWidget), subWidget); g_object_unref(G_OBJECT(store)); for(auto& cell : column) { gtk_tree_view_column_set_widget(GTK_TREE_VIEW_COLUMN(cell.column), cell.label); gtk_tree_view_append_column(GTK_TREE_VIEW(subWidget), cell.column); gtk_widget_show(cell.label); } gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(subWidget), headerText.size() >= 2); //two or more columns + checkbutton column gtk_tree_view_set_search_column(GTK_TREE_VIEW(subWidget), 2); g_signal_connect(G_OBJECT(subWidget), "cursor-changed", G_CALLBACK(ListView_change), (gpointer)&listView); g_signal_connect(G_OBJECT(subWidget), "row-activated", G_CALLBACK(ListView_activate), (gpointer)&listView); gtk_widget_show(subWidget); setHeaderVisible(listView.state.headerVisible); setCheckable(listView.state.checkable); for(auto& text : listView.state.text) append(text); for(unsigned n = 0; n < listView.state.checked.size(); n++) setChecked(n, listView.state.checked[n]); if(listView.state.selected) setSelection(listView.state.selection); autoSizeColumns(); } void pListView::destructor() { gtk_widget_destroy(subWidget); gtk_widget_destroy(gtkWidget); } void pListView::orphan() { destructor(); constructor(); } void pListView::setFocused() { gtk_widget_grab_focus(subWidget); } void pListView::setFont(string font) { pFont::setFont(gtkWidget, font); for(auto& cell : column) pFont::setFont(cell.label, font); } }
37.511737
125
0.760951
[ "vector", "model" ]
54e5c1f3edbf21e73eed7296214618feca3b8a4a
1,942
cpp
C++
src/pbrProgram/main.cpp
moddyz/Pbrt
fa92b09a98d07503e1dc381fcb0e9d9b6ae88915
[ "MIT" ]
null
null
null
src/pbrProgram/main.cpp
moddyz/Pbrt
fa92b09a98d07503e1dc381fcb0e9d9b6ae88915
[ "MIT" ]
null
null
null
src/pbrProgram/main.cpp
moddyz/Pbrt
fa92b09a98d07503e1dc381fcb0e9d9b6ae88915
[ "MIT" ]
null
null
null
// Physically based ray tracing program. #include <cxxopts.hpp> #include <pbr/utils/log.h> /// \struct Program options /// /// Describes the inputs to the renderer program. struct ProgramOptions { std::vector< std::string > m_inputFiles; //< The input scene files to the renderer. std::string m_outputFile; //< The output image file to write. }; /// Parse command line arguments into renderer program options. ProgramOptions ParseCommandLineArguments( int i_argc, char** i_argv ) { // Parse command line arguments. cxxopts::Options parser( "pbrProgram", "Physically based ray tracing program." ); parser.add_options() // Command line parser. ( "h,help", "Print usage" ) // ( "o,output", "Output file", cxxopts::value< std::string >()->default_value( "out.ppm" ) ) // ( "inputs", "Input file(s)", cxxopts::value< std::vector< std::string > >() ); parser.parse_positional( {"inputs"} ); auto args = parser.parse( i_argc, i_argv ); if ( args.count( "help" ) > 0 ) { PBR_LOG_INFO( "%s\n", parser.help().c_str() ); exit( 0 ); } if ( args.count( "inputs" ) == 0 ) { PBR_LOG_INFO( "%s\n", parser.help().c_str() ); exit( -1 ); } ProgramOptions programOptions; programOptions.m_inputFiles = args[ "inputs" ].as< std::vector< std::string > >(); programOptions.m_outputFile = args[ "output" ].as< std::string >(); return programOptions; } int main( int i_argc, char** i_argv ) { ProgramOptions options = ParseCommandLineArguments( i_argc, i_argv ); PBR_LOG_INFO( "[pbrProgram] Physically based rendering program\n" ); PBR_LOG_INFO( "Input scene file(s): " ); for ( const std::string& inputFile : options.m_inputFiles ) { PBR_LOG_INFO( "%s ", inputFile.c_str() ); } PBR_LOG_INFO( "\nOutput image file: %s\n", options.m_outputFile.c_str() ); return 0; }
31.836066
101
0.623584
[ "vector" ]
54ea8689004e4bd9c6ea7d40ab7ecc52465161f8
10,978
cpp
C++
tools/builder/src/gwf_translator.cpp
RuslanKorshunov/sc-machine
8cb79a818d4e4144843b26722ac67bd71515ddaf
[ "MIT" ]
2
2015-02-20T16:48:59.000Z
2015-03-14T11:37:40.000Z
tools/builder/src/gwf_translator.cpp
RuslanKorshunov/sc-machine
8cb79a818d4e4144843b26722ac67bd71515ddaf
[ "MIT" ]
19
2015-02-01T19:42:52.000Z
2016-10-27T15:59:55.000Z
tools/builder/src/gwf_translator.cpp
RuslanKorshunov/sc-machine
8cb79a818d4e4144843b26722ac67bd71515ddaf
[ "MIT" ]
23
2015-04-18T15:11:56.000Z
2021-12-21T14:43:22.000Z
/* * This source file is part of an OSTIS project. For the latest info, see http://ostis.net * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #include "gwf_translator.h" #include "tinyxml/tinyxml2.h" #include "base64/base64.h" #include "utils.h" #include <fstream> #include <iostream> #include <assert.h> GwfTranslator::GwfTranslator(sc_memory_context *ctx) : iTranslator(ctx) { } GwfTranslator::~GwfTranslator() { } bool GwfTranslator::translateImpl() { // open file and read data bool result = true; std::ifstream ifs(mParams.fileName.c_str()); if (ifs.is_open()) { String data((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); result = processString(data); } else return false; ifs.close(); return result; } const String& GwfTranslator::getFileExt() const { return GwfTranslatorFactory::EXTENSION; } bool GwfTranslator::processString(const String &data) { tinyxml2::XMLDocument doc; tinyxml2::XMLError error = doc.Parse(data.c_str()); if (error != tinyxml2::XML_SUCCESS) { THROW_EXCEPT(Exception::ERR_PARSE, doc.GetErrorStr2(), mParams.fileName, -1); } tinyxml2::XMLElement *root = doc.FirstChildElement("GWF"); if (!root) { THROW_EXCEPT(Exception::ERR_PARSE, "Can't find root element", mParams.fileName, -1); } root = root->FirstChildElement("staticSector"); if (!root) { THROW_EXCEPT(Exception::ERR_PARSE, "Cna't find static sector", mParams.fileName, -1); } // collect elements std::vector<tinyxml2::XMLElement*> nodes; std::vector<tinyxml2::XMLElement*> edges; std::vector<tinyxml2::XMLElement*> buses; std::vector<tinyxml2::XMLElement*> all; static std::string s_arc = "arc"; static std::string s_pair = "pair"; static std::string s_bus = "bus"; tinyxml2::XMLElement *el = root->FirstChildElement(); while (el) { all.push_back(el); if (el->Name() == s_arc || el->Name() == s_pair) edges.push_back(el); else if (el->Name() == s_bus) buses.push_back(el); else nodes.push_back(el); el = el->NextSiblingElement(); } static std::string s_node = "node"; static std::string s_contour = "contour"; tStringAddrMap id_map; tStringAddrMap::iterator itId; // create all nodes std::vector<tinyxml2::XMLElement*>::iterator it, itEnd = nodes.end(); for (it = nodes.begin(); it != itEnd; ++it) { el = *it; String idtf = el->Attribute("idtf"); String id = el->Attribute("id"); sc_addr addr; itId = id_map.find(id); if (itId != id_map.end()) continue; if (idtf.size() > 0) { if (getScAddr(idtf, addr)) { id_map[id] = addr; continue; // skip elements that already exists } } if (el->Name() == s_contour) { addr = sc_memory_node_new(mContext, sc_type_const | sc_type_node_struct); appendScAddr(addr, idtf); } else { tinyxml2::XMLElement *content = el->FirstChildElement("content"); if (!content) { THROW_EXCEPT(Exception::ERR_PARSE, "There are no child content for node with id=" + id, mParams.fileName, -1); } if (content->IntAttribute("type") == 0) { addr = sc_memory_node_new(mContext, convertType(el->Attribute("type"))); appendScAddr(addr, idtf); } else { // need to create link addr = sc_memory_link_new(mContext); // setup content String data = content->GetText(); if (content->IntAttribute("type") == 4) data = base64_decode(data); sc_stream *stream = sc_stream_memory_new(data.c_str(), (sc_uint)data.size(), SC_STREAM_FLAG_READ, SC_FALSE); sc_memory_set_link_content(mContext, addr, stream); sc_stream_free(stream); if (mParams.autoFormatInfo) { String ext = StringUtil::getFileExtension(content->Attribute("file_name")); if (!ext.empty()) generateFormatInfo(addr, ext); } } } if (!idtf.empty()) sc_helper_set_system_identifier(mContext, addr, idtf.c_str(), (sc_uint32)idtf.size()); id_map[id] = addr; } // process buses itEnd = buses.end(); for (it = buses.begin(); it != itEnd; ++it) { el = *it; tStringAddrMap::iterator itOwner = id_map.find(el->Attribute("owner")); if (itOwner == id_map.end()) continue; id_map[el->Attribute("id")] = itOwner->second; } // now create edges bool created = true; while (created) { created = false; itEnd = edges.end(); for (it = edges.begin(); it != itEnd; ++it) { el = *it; sc_addr addr; String id = el->Attribute("id"); String idtf = el->Attribute("idtf"); if (id_map.find(id) != id_map.end()) continue; if (getScAddr(idtf, addr)) continue; // get begin and end elements tStringAddrMap::iterator itB = id_map.find(el->Attribute("id_b")); if (itB == id_map.end()) continue; tStringAddrMap::iterator itE = id_map.find(el->Attribute("id_e")); if (itE == id_map.end()) continue; // create arc created = true; addr = sc_memory_arc_new(mContext, convertType(el->Attribute("type")), itB->second, itE->second); appendScAddr(addr, idtf); id_map[id] = addr; if (!idtf.empty()) sc_helper_set_system_identifier(mContext, addr, idtf.c_str(), (sc_uint32)idtf.size()); } } // now append elemnts into contours itEnd = all.end(); for (it = all.begin(); it != itEnd; ++it) { el = *it; tStringAddrMap::iterator itSelf = id_map.find(el->Attribute("id")); if (itSelf == id_map.end()) continue; tStringAddrMap::iterator itP = id_map.find(el->Attribute("parent")); if (itP == id_map.end()) continue; sc_memory_arc_new(mContext, sc_type_arc_pos_const_perm, itP->second, itSelf->second); } return false; } bool GwfTranslator::getScAddr(const String &idtf, sc_addr &addr) { tStringAddrMap::iterator it = mLocalIdtfAddrs.find(idtf); if (it != mLocalIdtfAddrs.end()) { addr = it->second; return true; } it = mSysIdtfAddrs.find(idtf); if (it != mSysIdtfAddrs.end()) { addr = it->second; return true; } it = msGlobalIdtfAddrs.find(idtf); if (it != msGlobalIdtfAddrs.end()) { addr = it->second; return true; } if (sc_helper_find_element_by_system_identifier(mContext, idtf.c_str(), (sc_uint32)idtf.size(), &addr) == SC_RESULT_OK) return true; return false; } sc_type GwfTranslator::convertType(const String &type) { if (type == "node/-/not_define") return sc_type_node; if (type == "node/const/general_node" || type == "node/const/general") return sc_type_node | sc_type_const; if (type == "node/var/general_node" || type == "node/const/var") return sc_type_node | sc_type_var; if (type == "node/const/relation") return sc_type_node | sc_type_node_norole | sc_type_const; if (type == "node/var/relation") return sc_type_node | sc_type_node_norole | sc_type_var; if (type == "node/const/attribute") return sc_type_node | sc_type_node_role | sc_type_const; if (type == "node/var/attribute") return sc_type_node | sc_type_node_role | sc_type_var; if (type == "node/const/nopredmet") return sc_type_node | sc_type_node_struct | sc_type_const; if (type == "node/var/nopredmet") return sc_type_node | sc_type_node_struct | sc_type_var; if (type == "node/const/predmet") return sc_type_node | sc_type_node_abstract | sc_type_const; if (type == "node/var/predmet") return sc_type_node | sc_type_node_abstract | sc_type_var; if (type == "node/const/group") return sc_type_node | sc_type_node_class | sc_type_const; if (type == "node/var/group") return sc_type_node | sc_type_node_class | sc_type_var; if (type == "node/const/asymmetry" || type == "node/const/symmetry" || type == "node/const/tuple") return sc_type_node | sc_type_node_tuple | sc_type_const; if (type == "node/var/asymmetry" || type == "node/var/symmetry" || type == "node/var/tuple") return sc_type_node | sc_type_node_tuple | sc_type_var; // ------- if (type == "arc/-/-") return sc_type_arc_access; if (type == "pair/orient") return sc_type_arc_common; if (type == "pair/noorient") return sc_type_edge_common; if (type == "pair/const/synonym" || type == "pair/const/noorient") return sc_type_edge_common | sc_type_const; if (type == "pair/var/synonym" || type == "pair/var/noorient") return sc_type_edge_common | sc_type_var; if (type == "pair/const/orient") return sc_type_arc_common | sc_type_const; if (type == "pair/var/orient") return sc_type_arc_common | sc_type_var; if (type == "arc/const/fuz") return sc_type_arc_access | sc_type_const | sc_type_arc_fuz | sc_type_arc_perm; if (type == "arc/var/fuz") return sc_type_arc_access | sc_type_var | sc_type_arc_fuz | sc_type_arc_perm; if (type == "arc/const/fuz/temp") return sc_type_arc_access | sc_type_const | sc_type_arc_fuz | sc_type_arc_temp; if (type == "arc/var/fuz/temp") return sc_type_arc_access | sc_type_var | sc_type_arc_fuz | sc_type_arc_temp; if (type == "arc/const/neg") return sc_type_arc_access | sc_type_const | sc_type_arc_neg | sc_type_arc_perm; if (type == "arc/var/neg") return sc_type_arc_access | sc_type_var | sc_type_arc_neg | sc_type_arc_perm; if (type == "arc/const/neg/temp") return sc_type_arc_access | sc_type_const | sc_type_arc_neg | sc_type_arc_temp; if (type == "arc/var/neg/temp") return sc_type_arc_access | sc_type_var | sc_type_arc_neg | sc_type_arc_temp; if (type == "arc/const/pos") return sc_type_arc_access | sc_type_const | sc_type_arc_pos | sc_type_arc_perm; if (type == "arc/var/pos") return sc_type_arc_access | sc_type_var | sc_type_arc_pos | sc_type_arc_perm; if (type == "arc/const/pos/temp") return sc_type_arc_access | sc_type_const | sc_type_arc_pos | sc_type_arc_temp; if (type == "arc/var/pos/temp") return sc_type_arc_access | sc_type_var | sc_type_arc_pos | sc_type_arc_temp; THROW_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Can't determine type for " << type, mParams.fileName, -1); return 0; } // ------------------- const String GwfTranslatorFactory::EXTENSION = "gwf"; GwfTranslatorFactory::GwfTranslatorFactory() { } GwfTranslatorFactory::~GwfTranslatorFactory() { } iTranslator* GwfTranslatorFactory::createInstance(sc_memory_context *ctx) { return new GwfTranslator(ctx); } const String& GwfTranslatorFactory::getFileExt() const { return EXTENSION; }
26.326139
121
0.642011
[ "vector" ]
54eb47103d965f41eacee5ace1d4301c4290ccf7
4,605
hpp
C++
armnn-ethos-n-backend/workloads/EthosNPreCompiledWorkload.hpp
ARM-software/ethos-n-driver-stack
9f652630c0ff94d8c8b51fd04f6e4dbc34a57e4b
[ "Apache-2.0" ]
25
2020-03-26T19:08:55.000Z
2022-03-14T07:25:44.000Z
armnn-ethos-n-backend/workloads/EthosNPreCompiledWorkload.hpp
ARM-software/ethos-n-driver-stack
9f652630c0ff94d8c8b51fd04f6e4dbc34a57e4b
[ "Apache-2.0" ]
11
2021-01-13T14:37:10.000Z
2022-02-28T10:05:10.000Z
armnn-ethos-n-backend/workloads/EthosNPreCompiledWorkload.hpp
ARM-software/ethos-n-driver-stack
9f652630c0ff94d8c8b51fd04f6e4dbc34a57e4b
[ "Apache-2.0" ]
12
2020-09-13T18:02:47.000Z
2022-03-04T17:00:45.000Z
// // Copyright © 2018-2021 Arm Limited. // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "../EthosNConfig.hpp" #include "backendsCommon/Workload.hpp" #include <ethosn_driver_library/Buffer.hpp> #include <ethosn_driver_library/Inference.hpp> #include <ethosn_driver_library/Network.hpp> #include <ethosn_support_library/Support.hpp> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace armnn { bool EthosNPreCompiledWorkloadValidate(std::string* reasonIfUnsupported); /// The data type stored as the m_PreCompiledObject in the PreCompiledLayer. /// This is the mechanism to pass data between the conversion stage (EthosNSubgraphViewConverter) /// and the execution stage (EthosNPreCompiledWorkload). class EthosNPreCompiledObject { public: /// The data type stored as the m_PreCompiledObject in the PreCompiledLayer. /// This is the mechanism to pass data between the conversion stage (EthosNSubgraphViewConverter) /// and the execution stage (EthosNPreCompiledWorkload). struct Network { Network(std::vector<char> serializedCompiledNetwork, std::unordered_map<uint32_t, uint32_t> inputSlotsToEthosNInputs, std::unordered_map<uint32_t, uint32_t> outputSlotsToEthosNOutputs) : m_SerializedCompiledNetwork(std::move(serializedCompiledNetwork)) , m_InputSlotsToEthosNInputs(std::move(inputSlotsToEthosNInputs)) , m_OutputSlotsToEthosNOutputs(std::move(outputSlotsToEthosNOutputs)) {} std::vector<char> m_SerializedCompiledNetwork; /// Maps from the Arm NN input/output slot index to the Ethos-N input/output buffer index. /// In some cases these may be equivalent but it is not guaranteed. /// @{ std::unordered_map<uint32_t, uint32_t> m_InputSlotsToEthosNInputs; std::unordered_map<uint32_t, uint32_t> m_OutputSlotsToEthosNOutputs; /// @} }; struct PerfData { std::string m_PerfOutFile; ethosn::support_library::EthosNVariant m_PerfVariant; uint32_t m_PerfSramSizeBytesOverride; ethosn::support_library::NetworkPerformanceData m_Data; ethosn::support_library::EstimationOptions m_EstimationOptions; }; EthosNPreCompiledObject(Network network, std::map<uint32_t, std::string> ethosnOperationNameMapping) : m_IsPerfEstimationOnly(false) , m_Network(std::move(network)) , m_EthosNOperationNameMapping(ethosnOperationNameMapping) {} EthosNPreCompiledObject(PerfData perfData, std::map<uint32_t, std::string> ethosnOperationNameMapping) : m_IsPerfEstimationOnly(true) , m_PerfData(std::move(perfData)) , m_EthosNOperationNameMapping(ethosnOperationNameMapping) {} ~EthosNPreCompiledObject() { if (m_IsPerfEstimationOnly) { m_PerfData.~PerfData(); } else { m_Network.~Network(); } } bool IsPerfEstimationOnly() const { return m_IsPerfEstimationOnly; } const Network* GetNetwork() const { return !m_IsPerfEstimationOnly ? &m_Network : nullptr; } const PerfData* GetPerfData() const { return m_IsPerfEstimationOnly ? &m_PerfData : nullptr; } const std::map<uint32_t, std::string>& GetEthosNOperationNameMapping() const { return m_EthosNOperationNameMapping; } private: const bool m_IsPerfEstimationOnly; union { Network m_Network; PerfData m_PerfData; }; /// Map from Ethos-N operation ID to the corresponding Arm NN layer name. std::map<uint32_t, std::string> m_EthosNOperationNameMapping; }; class EthosNPreCompiledWorkload : public BaseWorkload<PreCompiledQueueDescriptor> { public: EthosNPreCompiledWorkload(const PreCompiledQueueDescriptor& descriptor, const WorkloadInfo& info); void Execute() const override; private: void Init(const PreCompiledDescriptor& descriptor, const EthosNPreCompiledObject::Network& network); void SavePerformanceJson() const; // The workload does not own the EthosNPreCompiledObject, the ownership is still retained by the pre-compiled layer const EthosNPreCompiledObject* m_PreCompiledObject; // The workload does own the network and the inference instances mutable std::unique_ptr<ethosn::driver_library::Network> m_Network; std::vector<ethosn::driver_library::Buffer*> m_InputBuffers{}; std::vector<ethosn::driver_library::Buffer*> m_OutputBuffers{}; }; } //namespace armnn
32.659574
119
0.715744
[ "vector" ]
54eb54570c4a144c822deaf9f373dce7dbbf075e
11,273
cpp
C++
build-easypaint-Qt_5_9_5_qt5_temporary-Debug/build/moc_mainwindow.cpp
maifeeulasad/EasyPaint
4af126c6d94c840e5cc02ffd8d967b584959145c
[ "MIT" ]
null
null
null
build-easypaint-Qt_5_9_5_qt5_temporary-Debug/build/moc_mainwindow.cpp
maifeeulasad/EasyPaint
4af126c6d94c840e5cc02ffd8d967b584959145c
[ "MIT" ]
null
null
null
build-easypaint-Qt_5_9_5_qt5_temporary-Debug/build/moc_mainwindow.cpp
maifeeulasad/EasyPaint
4af126c6d94c840e5cc02ffd8d967b584959145c
[ "MIT" ]
1
2022-03-01T18:06:05.000Z
2022-03-01T18:06:05.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../sources/mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_MainWindow_t { QByteArrayData data[46]; char stringdata0[590]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 0, 10), // "MainWindow" QT_MOC_LITERAL(1, 11, 21), // "sendInstrumentChecked" QT_MOC_LITERAL(2, 33, 0), // "" QT_MOC_LITERAL(3, 34, 15), // "InstrumentsEnum" QT_MOC_LITERAL(4, 50, 11), // "activateTab" QT_MOC_LITERAL(5, 62, 5), // "index" QT_MOC_LITERAL(6, 68, 21), // "setNewSizeToSizeLabel" QT_MOC_LITERAL(7, 90, 4), // "size" QT_MOC_LITERAL(8, 95, 19), // "setNewPosToPosLabel" QT_MOC_LITERAL(9, 115, 3), // "pos" QT_MOC_LITERAL(10, 119, 22), // "setCurrentPipetteColor" QT_MOC_LITERAL(11, 142, 5), // "color" QT_MOC_LITERAL(12, 148, 19), // "clearStatusBarColor" QT_MOC_LITERAL(13, 168, 20), // "setInstrumentChecked" QT_MOC_LITERAL(14, 189, 10), // "instrument" QT_MOC_LITERAL(15, 200, 6), // "newAct" QT_MOC_LITERAL(16, 207, 7), // "openAct" QT_MOC_LITERAL(17, 215, 7), // "helpAct" QT_MOC_LITERAL(18, 223, 7), // "saveAct" QT_MOC_LITERAL(19, 231, 9), // "saveAsAct" QT_MOC_LITERAL(20, 241, 8), // "printAct" QT_MOC_LITERAL(21, 250, 7), // "copyAct" QT_MOC_LITERAL(22, 258, 8), // "pasteAct" QT_MOC_LITERAL(23, 267, 6), // "cutAct" QT_MOC_LITERAL(24, 274, 11), // "settingsAct" QT_MOC_LITERAL(25, 286, 10), // "effectsAct" QT_MOC_LITERAL(26, 297, 14), // "resizeImageAct" QT_MOC_LITERAL(27, 312, 15), // "resizeCanvasAct" QT_MOC_LITERAL(28, 328, 18), // "rotateLeftImageAct" QT_MOC_LITERAL(29, 347, 19), // "rotateRightImageAct" QT_MOC_LITERAL(30, 367, 9), // "zoomInAct" QT_MOC_LITERAL(31, 377, 10), // "zoomOutAct" QT_MOC_LITERAL(32, 388, 15), // "advancedZoomAct" QT_MOC_LITERAL(33, 404, 11), // "closeTabAct" QT_MOC_LITERAL(34, 416, 8), // "closeTab" QT_MOC_LITERAL(35, 425, 26), // "setAllInstrumentsUnchecked" QT_MOC_LITERAL(36, 452, 8), // "QAction*" QT_MOC_LITERAL(37, 461, 6), // "action" QT_MOC_LITERAL(38, 468, 13), // "instumentsAct" QT_MOC_LITERAL(39, 482, 5), // "state" QT_MOC_LITERAL(40, 488, 13), // "enableActions" QT_MOC_LITERAL(41, 502, 20), // "enableCopyCutActions" QT_MOC_LITERAL(42, 523, 6), // "enable" QT_MOC_LITERAL(43, 530, 19), // "clearImageSelection" QT_MOC_LITERAL(44, 550, 25), // "restorePreviousInstrument" QT_MOC_LITERAL(45, 576, 13) // "setInstrument" }, "MainWindow\0sendInstrumentChecked\0\0" "InstrumentsEnum\0activateTab\0index\0" "setNewSizeToSizeLabel\0size\0" "setNewPosToPosLabel\0pos\0setCurrentPipetteColor\0" "color\0clearStatusBarColor\0" "setInstrumentChecked\0instrument\0newAct\0" "openAct\0helpAct\0saveAct\0saveAsAct\0" "printAct\0copyAct\0pasteAct\0cutAct\0" "settingsAct\0effectsAct\0resizeImageAct\0" "resizeCanvasAct\0rotateLeftImageAct\0" "rotateRightImageAct\0zoomInAct\0zoomOutAct\0" "advancedZoomAct\0closeTabAct\0closeTab\0" "setAllInstrumentsUnchecked\0QAction*\0" "action\0instumentsAct\0state\0enableActions\0" "enableCopyCutActions\0enable\0" "clearImageSelection\0restorePreviousInstrument\0" "setInstrument" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 34, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 184, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 4, 1, 187, 2, 0x08 /* Private */, 6, 1, 190, 2, 0x08 /* Private */, 8, 1, 193, 2, 0x08 /* Private */, 10, 1, 196, 2, 0x08 /* Private */, 12, 0, 199, 2, 0x08 /* Private */, 13, 1, 200, 2, 0x08 /* Private */, 15, 0, 203, 2, 0x08 /* Private */, 16, 0, 204, 2, 0x08 /* Private */, 17, 0, 205, 2, 0x08 /* Private */, 18, 0, 206, 2, 0x08 /* Private */, 19, 0, 207, 2, 0x08 /* Private */, 20, 0, 208, 2, 0x08 /* Private */, 21, 0, 209, 2, 0x08 /* Private */, 22, 0, 210, 2, 0x08 /* Private */, 23, 0, 211, 2, 0x08 /* Private */, 24, 0, 212, 2, 0x08 /* Private */, 25, 0, 213, 2, 0x08 /* Private */, 26, 0, 214, 2, 0x08 /* Private */, 27, 0, 215, 2, 0x08 /* Private */, 28, 0, 216, 2, 0x08 /* Private */, 29, 0, 217, 2, 0x08 /* Private */, 30, 0, 218, 2, 0x08 /* Private */, 31, 0, 219, 2, 0x08 /* Private */, 32, 0, 220, 2, 0x08 /* Private */, 33, 0, 221, 2, 0x08 /* Private */, 34, 1, 222, 2, 0x08 /* Private */, 35, 1, 225, 2, 0x08 /* Private */, 38, 1, 228, 2, 0x08 /* Private */, 40, 1, 231, 2, 0x08 /* Private */, 41, 1, 234, 2, 0x08 /* Private */, 43, 0, 237, 2, 0x08 /* Private */, 44, 0, 238, 2, 0x08 /* Private */, 45, 1, 239, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, 0x80000000 | 3, 2, // slots: parameters QMetaType::Void, QMetaType::Int, 5, QMetaType::Void, QMetaType::QSize, 7, QMetaType::Void, QMetaType::QPoint, 9, QMetaType::Void, QMetaType::QColor, 11, QMetaType::Void, QMetaType::Void, 0x80000000 | 3, 14, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Int, 5, QMetaType::Void, 0x80000000 | 36, 37, QMetaType::Void, QMetaType::Bool, 39, QMetaType::Void, QMetaType::Int, 5, QMetaType::Void, QMetaType::Bool, 42, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 3, 14, 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { MainWindow *_t = static_cast<MainWindow *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->sendInstrumentChecked((*reinterpret_cast< InstrumentsEnum(*)>(_a[1]))); break; case 1: _t->activateTab((*reinterpret_cast< const int(*)>(_a[1]))); break; case 2: _t->setNewSizeToSizeLabel((*reinterpret_cast< const QSize(*)>(_a[1]))); break; case 3: _t->setNewPosToPosLabel((*reinterpret_cast< const QPoint(*)>(_a[1]))); break; case 4: _t->setCurrentPipetteColor((*reinterpret_cast< const QColor(*)>(_a[1]))); break; case 5: _t->clearStatusBarColor(); break; case 6: _t->setInstrumentChecked((*reinterpret_cast< InstrumentsEnum(*)>(_a[1]))); break; case 7: _t->newAct(); break; case 8: _t->openAct(); break; case 9: _t->helpAct(); break; case 10: _t->saveAct(); break; case 11: _t->saveAsAct(); break; case 12: _t->printAct(); break; case 13: _t->copyAct(); break; case 14: _t->pasteAct(); break; case 15: _t->cutAct(); break; case 16: _t->settingsAct(); break; case 17: _t->effectsAct(); break; case 18: _t->resizeImageAct(); break; case 19: _t->resizeCanvasAct(); break; case 20: _t->rotateLeftImageAct(); break; case 21: _t->rotateRightImageAct(); break; case 22: _t->zoomInAct(); break; case 23: _t->zoomOutAct(); break; case 24: _t->advancedZoomAct(); break; case 25: _t->closeTabAct(); break; case 26: _t->closeTab((*reinterpret_cast< int(*)>(_a[1]))); break; case 27: _t->setAllInstrumentsUnchecked((*reinterpret_cast< QAction*(*)>(_a[1]))); break; case 28: _t->instumentsAct((*reinterpret_cast< bool(*)>(_a[1]))); break; case 29: _t->enableActions((*reinterpret_cast< int(*)>(_a[1]))); break; case 30: _t->enableCopyCutActions((*reinterpret_cast< bool(*)>(_a[1]))); break; case 31: _t->clearImageSelection(); break; case 32: _t->restorePreviousInstrument(); break; case 33: _t->setInstrument((*reinterpret_cast< InstrumentsEnum(*)>(_a[1]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { typedef void (MainWindow::*_t)(InstrumentsEnum ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&MainWindow::sendInstrumentChecked)) { *result = 0; return; } } } } const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data, qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(this); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 34) qt_static_metacall(this, _c, _id, _a); _id -= 34; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 34) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 34; } return _id; } // SIGNAL 0 void MainWindow::sendInstrumentChecked(InstrumentsEnum _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE
38.606164
104
0.606582
[ "object" ]
54eb9d8a20380a28fe6efc4a5ffc8b5f5800523a
7,208
cpp
C++
Test/Test-Convert.cpp
karannewatia/SCALE-MAMBA
467b33a6c80050789204ea3ee3b5cf0113354f85
[ "BSD-2-Clause" ]
196
2018-05-25T11:41:56.000Z
2022-03-12T05:49:50.000Z
Test/Test-Convert.cpp
karannewatia/SCALE-MAMBA
467b33a6c80050789204ea3ee3b5cf0113354f85
[ "BSD-2-Clause" ]
49
2018-07-17T15:49:41.000Z
2021-01-19T11:35:31.000Z
Test/Test-Convert.cpp
karannewatia/SCALE-MAMBA
467b33a6c80050789204ea3ee3b5cf0113354f85
[ "BSD-2-Clause" ]
90
2018-05-25T11:41:42.000Z
2022-03-23T19:15:10.000Z
/* Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom. Copyright (c) 2021, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium. All rights reserved */ #include <fstream> #include <iostream> using namespace std; #include "GC/Circuit.h" #include "GC/SimplifyCircuit.h" #include "Math/bigint.h" #include "Tools/random.h" /* This routine tests the conversion and simplification done in the * Circuits directory, to ensure we get the correct functionality * for the main circuits we use */ /* This routine here is used to test simplification on the main circuits * within this file. This is helpful for debugging purposes sometimes */ void Simplify(Circuit &C, int iter) { SimplifyCircuit SC(C); SC.Simplify(); bool flag= true; int numI= 0; while (flag && numI < iter) { C= SC.Get_Circuit(); cout << "\t" << numI << " : "; cout << "nwires : " << C.get_nWires() << " "; cout << "ngates : " << C.get_nGates() << " "; cout << "and gt : " << C.num_AND_gates() << endl; flag= SC.Search_SubCircuit(); SC.Simplify(); numI++; } C= SC.Get_Circuit(); } unsigned long bits_to_ulong(const vector<int> &bits, int bound) { unsigned long x= 0; for (int i= bound - 1; i >= 0; i--) { x= 2 * x + bits[i]; } return x; } unsigned long random_int(PRNG &G) { unsigned long x= G.get_uint(); unsigned long y= G.get_uint(); x= (x << 32) + y; return x; } void test_adder64(PRNG &G) { Circuit C; ifstream inpf("Circuits/Bristol/adder64.txt"); inpf >> C; inpf.close(); vector<vector<int>> inp, outp; inp.resize(2); outp.resize(1); inp[0].resize(64); inp[1].resize(64); outp[0].resize(64); unsigned long x, y, z, zz; for (unsigned long i= 0; i < 100; i++) { x= random_int(G); y= random_int(G); z= x + y; ulong_to_bits(inp[0], x); ulong_to_bits(inp[1], y); C.evaluate(inp, outp); zz= bits_to_ulong(outp[0], 64); if (z != zz) { cout << "Error test_adder64: " << z << " " << zz << endl; } } } void test_mult64(PRNG &G) { Circuit C; ifstream inpf("Circuits/Bristol/mult64.txt"); inpf >> C; inpf.close(); vector<vector<int>> inp, outp; inp.resize(2); outp.resize(1); inp[0].resize(64); inp[1].resize(64); outp[0].resize(64); unsigned long x, y, z, zz; for (unsigned long i= 0; i < 100; i++) { x= random_int(G); y= random_int(G); z= x * y; ulong_to_bits(inp[0], x); ulong_to_bits(inp[1], y); C.evaluate(inp, outp); zz= bits_to_ulong(outp[0], 64); //cout<<zz<<" z=x*y "<< z<<"="<<x<<"*"<<y<<endl; if (z != zz) { cout << "Error test_mult64: " << z << " " << zz << endl; } } } void test_divide64(PRNG &G) { Circuit C; ifstream inpf("Circuits/Bristol/divide64.txt"); inpf >> C; inpf.close(); vector<vector<int>> inp, outp; inp.resize(2); outp.resize(1); inp[0].resize(64); inp[1].resize(64); outp[0].resize(64); unsigned long x, y, z, zz; for (unsigned long i= 0; i < 100; i++) { x= random_int(G); y= random_int(G); z= (signed long) x / (signed long) y; ulong_to_bits(inp[0], x); ulong_to_bits(inp[1], y); C.evaluate(inp, outp); zz= bits_to_ulong(outp[0], 64); if (z != zz) { cout << "Error test_divide64: " << i << endl; cout << "\t x = " << x << " " << (signed long) x << endl; cout << "\t y = " << y << " " << (signed long) y << endl; cout << "\t z = " << z << " " << (signed long) z << endl; cout << "\t zz = " << zz << " " << (signed long) zz << endl; } } } void test_sub64(PRNG &G) { Circuit C; ifstream inpf("Circuits/Bristol/sub64.txt"); inpf >> C; inpf.close(); vector<vector<int>> inp, outp; inp.resize(2); outp.resize(1); inp[0].resize(64); inp[1].resize(64); outp[0].resize(64); unsigned long x, y, z, zz; for (unsigned long i= 0; i < 100; i++) { x= random_int(G); y= random_int(G); z= x - y; ulong_to_bits(inp[0], x); ulong_to_bits(inp[1], y); C.evaluate(inp, outp); zz= bits_to_ulong(outp[0], 64); if (z != zz) { cout << "Error test_sub64: " << z << " " << zz << endl; } } } void test_neg64(PRNG &G) { Circuit C; ifstream inpf("Circuits/Bristol/neg64.txt"); inpf >> C; inpf.close(); vector<vector<int>> inp, outp; inp.resize(1); outp.resize(1); inp[0].resize(64); outp[0].resize(64); unsigned long x, z, zz; for (unsigned long i= 0; i < 100; i++) { x= random_int(G); z= -x; ulong_to_bits(inp[0], x); C.evaluate(inp, outp); zz= bits_to_ulong(outp[0], 64); if (z != zz) { cout << i << " Error test_neg64: " << "x=" << x << " z=" << z << " zz=" << zz << endl; } } } void test_mult2_64(PRNG &G) { Circuit C; ifstream inpf("Circuits/Bristol/mult2_64.txt"); inpf >> C; inpf.close(); vector<vector<int>> inp, outp; vector<int> v; inp.resize(2); outp.resize(1); inp[0].resize(64); inp[1].resize(64); outp[0].resize(64); outp[1].resize(64); unsigned __int128 x, y, z, zz; unsigned long top, bot, top1, bot1; for (unsigned long i= 0; i < 100; i++) { x= random_int(G); y= random_int(G); z= x * y; ulong_to_bits(inp[0], (unsigned long) x); ulong_to_bits(inp[1], (unsigned long) y); C.evaluate(inp, outp); top= bits_to_ulong(outp[0], 64); bot= bits_to_ulong(outp[1], 64); top1= z >> 64; bot1= z & 0xFFFFFFFFFFFFFFFF; zz= (((unsigned __int128) top) << 64) + bot; if (z != zz) { cout << "Error test_mult2_64: " << i << "\n\t"; cout << (unsigned long) x << " " << (unsigned long) y << " : "; cout << top << " " << top1 << " : "; cout << bot << " " << bot1 << " : " << endl; } } } void test_zero_equal(PRNG &G) { Circuit C; ifstream inpf("Circuits/Bristol/zero_equal.txt"); inpf >> C; inpf.close(); vector<vector<int>> inp, outp; inp.resize(1); outp.resize(1); inp[0].resize(64); outp[0].resize(1); unsigned long x, z, zz; for (unsigned long i= 0; i < 100; i++) { x= random_int(G); if (x == 0) { z= 1; } else { z= 0; } ulong_to_bits(inp[0], x); C.evaluate(inp, outp); zz= bits_to_ulong(outp[0], 1); if (z != zz) { cout << "Error test_zeroEqual: " << z << " " << zz << endl; } } } int main() { PRNG G; G.ReSeed(0); cout << "Testing adder64" << endl; test_adder64(G); cout << "Testing sub64" << endl; test_sub64(G); cout << "Testing neg64" << endl; test_neg64(G); cout << "Testing mult64" << endl; test_mult64(G); cout << "Testing mult2_64" << endl; test_mult2_64(G); cout << "Testing zero_equal" << endl; test_zero_equal(G); cout << "Testing divide64" << endl; test_divide64(G); return 0; }
22.666667
110
0.531354
[ "vector" ]
54f035711a23df47037693d0a66eab5037c46485
4,363
cpp
C++
runtime/modules.cpp
creativemindplus/skybison
d1740e08d8de85a0a56b650675717da67de171a0
[ "CNRI-Python-GPL-Compatible" ]
278
2021-08-31T00:46:51.000Z
2022-02-13T19:43:28.000Z
runtime/modules.cpp
creativemindplus/skybison
d1740e08d8de85a0a56b650675717da67de171a0
[ "CNRI-Python-GPL-Compatible" ]
9
2021-11-05T22:28:43.000Z
2021-11-23T08:39:04.000Z
runtime/modules.cpp
tekknolagi/skybison
bea8fc2af0a70e7203b4c19f36c14a745512a335
[ "CNRI-Python-GPL-Compatible" ]
12
2021-08-31T07:49:54.000Z
2021-10-08T01:09:01.000Z
// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) #include "modules.h" #include "builtins.h" #include "capi.h" #include "frozen-modules.h" #include "globals.h" #include "marshal.h" #include "module-builtins.h" #include "object-builtins.h" #include "runtime.h" #include "symbols.h" #include "type-builtins.h" namespace py { static word builtinModuleIndex(const Str& name) { for (word i = 0; i < kNumFrozenModules; i++) { if (name.equalsCStr(kFrozenModules[i].name)) { return i; } } return -1; } static RawObject createBuiltinModule(Thread* thread, const Str& name) { HandleScope scope(thread); Runtime* runtime = thread->runtime(); word builtin_index = builtinModuleIndex(name); if (builtin_index >= 0) { const FrozenModule* frozen_module = &kFrozenModules[builtin_index]; Module module(&scope, runtime->newModule(name)); Object modules(&scope, runtime->modules()); Object result(&scope, objectSetItem(thread, modules, name, module)); if (result.isErrorException()) return *result; ModuleInitFunc init = frozen_module->init; if (init == nullptr) { init = executeFrozenModule; } View<byte> bytecode(frozen_module->marshalled_code, frozen_module->marshalled_code_length); init(thread, module, bytecode); return *module; } Object module(&scope, moduleInitBuiltinExtension(thread, name)); if (module.isErrorException()) return *module; Object modules(&scope, runtime->modules()); Object result(&scope, objectSetItem(thread, modules, name, module)); if (result.isErrorException()) return *result; return *module; } RawObject ensureBuiltinModule(Thread* thread, const Str& name) { DCHECK(Runtime::isInternedStr(thread, name), "expected interned str"); Runtime* runtime = thread->runtime(); HandleScope scope(thread); Object result(&scope, runtime->findModule(name)); if (!result.isErrorNotFound()) return *result; return createBuiltinModule(thread, name); } RawObject ensureBuiltinModuleById(Thread* thread, SymbolId id) { Runtime* runtime = thread->runtime(); HandleScope scope(thread); Object result(&scope, runtime->findModuleById(id)); if (!result.isErrorNotFound()) return *result; Str name(&scope, runtime->symbols()->at(id)); return createBuiltinModule(thread, name); } void executeFrozenModule(Thread* thread, const Module& module, View<byte> bytecode) { HandleScope scope(thread); Marshal::Reader reader(&scope, thread, bytecode); reader.setBuiltinFunctions(kBuiltinFunctions, kNumBuiltinFunctions, kIntrinsicFunctions, kNumIntrinsicFunctions); Str filename(&scope, module.name()); // We don't write pyc headers for frozen modules because it would make // bootstrapping tricky. Don't read the pyc header. Code code(&scope, reader.readObject()); Object result(&scope, executeModule(thread, code, module)); CHECK(!result.isErrorException(), "Failed to execute %s module", filename.toCStr()); } RawObject executeModule(Thread* thread, const Code& code, const Module& module) { HandleScope scope(thread); DCHECK(code.argcount() == 0, "invalid argcount %ld", code.argcount()); Object none(&scope, NoneType::object()); return thread->exec(code, module, none); } RawObject executeModuleFromCode(Thread* thread, const Code& code, const Object& name) { HandleScope scope(thread); Runtime* runtime = thread->runtime(); Module module(&scope, runtime->newModule(name)); Object modules(&scope, runtime->modules()); Object result(&scope, objectSetItem(thread, modules, name, module)); if (result.isErrorException()) return *result; result = executeModule(thread, code, module); if (result.isError()) return *result; return *module; } bool isFrozenModule(const Str& name) { return builtinModuleIndex(name) >= 0; } bool isFrozenPackage(const Str& name) { word index = builtinModuleIndex(name); if (index < 0) { return false; } const FrozenModule* frozen_module = &kFrozenModules[index]; return frozen_module->is_package; } const FrozenModule* frozenModuleByName(const Str& name) { word index = builtinModuleIndex(name); if (index < 0) { return nullptr; } return &kFrozenModules[index]; } } // namespace py
34.085938
78
0.698831
[ "object" ]
54f250dc810fb2435e1cb6e0a797b90cd48afc1a
2,806
cc
C++
caffe2/operators/batch_matmul_op_test.cc
kickers18/caffe2
f69232c9237174f8e272c0fc59d3e28af52842f2
[ "Apache-2.0" ]
585
2015-08-10T02:48:52.000Z
2021-12-01T08:46:59.000Z
caffe2/operators/batch_matmul_op_test.cc
mingzhe09088/caffe2
8f41717c46d214aaf62b53e5b3b9b308b5b8db91
[ "Apache-2.0" ]
23
2015-08-30T11:54:51.000Z
2017-03-06T03:01:07.000Z
caffe2/operators/batch_matmul_op_test.cc
mingzhe09088/caffe2
8f41717c46d214aaf62b53e5b3b9b308b5b8db91
[ "Apache-2.0" ]
183
2015-08-10T02:49:04.000Z
2021-12-01T08:47:13.000Z
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <memory> #include <vector> #include <gtest/gtest.h> #include "caffe2/operators/batch_matmul_op.h" namespace caffe2 { namespace { class BatchMatMulOpTest : public testing::Test { protected: void SetUp() override { cpu_context_ = make_unique<CPUContext>(option_); def_.set_name("test"); def_.set_type("BatchMatMul"); def_.add_input("A"); def_.add_input("B"); def_.add_output("Y"); } void AddConstInput( const std::vector<TIndex>& dims, const float value, const string& name) { Blob* blob = ws_.CreateBlob(name); auto* tensor = blob->GetMutable<TensorCPU>(); tensor->Resize(dims); math::Set<float, CPUContext>( tensor->size(), value, tensor->mutable_data<float>(), cpu_context_.get()); } void VerifyOutput(const std::vector<TIndex>& dims, const float value) const { const Blob* Y_blob = ws_.GetBlob("Y"); ASSERT_NE(nullptr, Y_blob); const auto& Y = Y_blob->Get<TensorCPU>(); const auto& Y_dims = Y.dims(); ASSERT_EQ(dims.size(), Y_dims.size()); for (std::size_t i = 0; i < dims.size(); ++i) { ASSERT_EQ(dims[i], Y_dims[i]); } for (int i = 0; i < Y.size(); ++i) { EXPECT_FLOAT_EQ(value, Y.data<float>()[i]); } } DeviceOption option_; std::unique_ptr<CPUContext> cpu_context_; Workspace ws_; OperatorDef def_; }; TEST_F(BatchMatMulOpTest, BatchMatMulOpNormalTest) { AddConstInput(std::vector<TIndex>{3, 5, 10}, 1.0f, "A"); AddConstInput(std::vector<TIndex>{3, 10, 6}, 1.0f, "B"); std::unique_ptr<OperatorBase> op(CreateOperator(def_, &ws_)); ASSERT_NE(nullptr, op); ASSERT_TRUE(op->Run()); VerifyOutput(std::vector<TIndex>{3, 5, 6}, 10.0f); } TEST_F(BatchMatMulOpTest, BatchMatMulOpBroadcastTest) { auto* arg = def_.add_arg(); arg->set_name("broadcast"); arg->set_i(1); AddConstInput(std::vector<TIndex>{3, 5, 10}, 1.0f, "A"); AddConstInput(std::vector<TIndex>{2, 3, 10, 6}, 1.0f, "B"); std::unique_ptr<OperatorBase> op(CreateOperator(def_, &ws_)); ASSERT_NE(nullptr, op); ASSERT_TRUE(op->Run()); VerifyOutput(std::vector<TIndex>{2, 3, 5, 6}, 10.0f); } } // namespace } // namespace caffe2
29.536842
79
0.662865
[ "vector" ]
54fb91a41e21a7c01784902b6270479256451db2
3,892
cc
C++
aos/events/event_scheduler_test.cc
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
39
2021-06-18T03:22:30.000Z
2022-03-21T15:23:43.000Z
aos/events/event_scheduler_test.cc
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
10
2021-06-18T03:22:19.000Z
2022-03-18T22:14:15.000Z
aos/events/event_scheduler_test.cc
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
4
2021-08-19T19:20:04.000Z
2022-03-08T07:33:18.000Z
#include "aos/events/event_scheduler.h" #include <chrono> #include "gtest/gtest.h" namespace aos { namespace chrono = std::chrono; using aos::logger::BootTimestamp; // Legacy time converter for keeping old tests working. Has numerical precision // problems. class SlopeOffsetTimeConverter final : public TimeConverter { public: SlopeOffsetTimeConverter(size_t nodes_count) : distributed_offset_(nodes_count, std::chrono::seconds(0)), distributed_slope_(nodes_count, 1.0) { uuids_.reserve(nodes_count); while (uuids_.size() < nodes_count) { uuids_.emplace_back(UUID::Random()); } } // Sets the offset between the distributed and monotonic clock. // monotonic = distributed * slope + offset; void SetDistributedOffset(size_t node_index, std::chrono::nanoseconds distributed_offset, double distributed_slope) { distributed_offset_[node_index] = distributed_offset; distributed_slope_[node_index] = distributed_slope; } distributed_clock::time_point ToDistributedClock( size_t node_index, BootTimestamp time) override { CHECK_EQ(time.boot, 0u); return distributed_clock::epoch() + std::chrono::duration_cast<std::chrono::nanoseconds>( (time.time_since_epoch() - distributed_offset_[node_index]) / distributed_slope_[node_index]); } BootTimestamp FromDistributedClock(size_t node_index, distributed_clock::time_point time, size_t boot_index) override { CHECK_EQ(boot_index, 0u); return { .boot = 0u, .time = monotonic_clock::epoch() + std::chrono::duration_cast<std::chrono::nanoseconds>( time.time_since_epoch() * distributed_slope_[node_index]) + distributed_offset_[node_index]}; } UUID boot_uuid(size_t node_index, size_t boot_count) override { CHECK_EQ(boot_count, 0u); return uuids_[node_index]; } void ObserveTimePassed(distributed_clock::time_point /*time*/) override {} private: // Offset to the distributed clock. // distributed = monotonic + offset; std::vector<std::chrono::nanoseconds> distributed_offset_; std::vector<double> distributed_slope_; std::vector<UUID> uuids_; }; // Tests that the default parameters (slope of 1, offest of 0) behave as // an identity. TEST(EventSchedulerTest, IdentityTimeConversion) { SlopeOffsetTimeConverter time(1); EventScheduler s(0); s.SetTimeConverter(0u, &time); EXPECT_EQ(s.FromDistributedClock(distributed_clock::epoch()), BootTimestamp::epoch()); EXPECT_EQ( s.FromDistributedClock(distributed_clock::epoch() + chrono::seconds(1)), BootTimestamp::epoch() + chrono::seconds(1)); EXPECT_EQ(s.ToDistributedClock(monotonic_clock::epoch()), distributed_clock::epoch()); EXPECT_EQ(s.ToDistributedClock(monotonic_clock::epoch() + chrono::seconds(1)), distributed_clock::epoch() + chrono::seconds(1)); } // Tests that a non-unity slope is computed correctly. TEST(EventSchedulerTest, DoubleTimeConversion) { SlopeOffsetTimeConverter time(1); EventScheduler s(0); s.SetTimeConverter(0u, &time); time.SetDistributedOffset(0u, std::chrono::seconds(7), 2.0); EXPECT_EQ(s.FromDistributedClock(distributed_clock::epoch()), BootTimestamp::epoch() + chrono::seconds(7)); EXPECT_EQ( s.FromDistributedClock(distributed_clock::epoch() + chrono::seconds(1)), BootTimestamp::epoch() + chrono::seconds(9)); EXPECT_EQ(s.ToDistributedClock(monotonic_clock::epoch() + chrono::seconds(7)), distributed_clock::epoch()); EXPECT_EQ(s.ToDistributedClock(monotonic_clock::epoch() + chrono::seconds(9)), distributed_clock::epoch() + chrono::seconds(1)); } } // namespace aos
34.75
80
0.683453
[ "vector" ]
07003d2b37ff30d288bc5a47d4fa9befbc470a55
5,823
cpp
C++
test/src/CastTest.cpp
DmitrySkiba/itoa-jnipp
e106061b85dbfbee7cc7f2b14350b1e06dd34237
[ "Apache-2.0" ]
17
2015-01-14T14:23:05.000Z
2022-01-08T16:28:00.000Z
test/src/CastTest.cpp
DmitrySkiba/itoa-jnipp
e106061b85dbfbee7cc7f2b14350b1e06dd34237
[ "Apache-2.0" ]
null
null
null
test/src/CastTest.cpp
DmitrySkiba/itoa-jnipp
e106061b85dbfbee7cc7f2b14350b1e06dd34237
[ "Apache-2.0" ]
15
2015-01-14T06:10:45.000Z
2020-05-01T23:59:35.000Z
/* * Copyright (C) 2011 Dmitry Skiba * * 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 "Common.h" #define TEST_NAME "CastsTest" ///////////////////////////////////////////////////////////////////// classes class Interface: public java::Object { JB_WRAPPER_CLASS(Interface); public: Interface(const jni::LObject& object); }; typedef java::ObjectPointer<Interface> PInterface; class Base: public java::Object { JB_WRAPPER_CLASS(Base); public: Base(); Base(const jni::LObject& object); }; typedef java::ObjectPointer<Base> PBase; class Derived: public Base { JB_WRAPPER_CLASS(Derived); public: Derived(); Derived(const jni::LObject& object); }; typedef java::ObjectPointer<Derived> PDerived; class Implementation: public java::Object { JB_WRAPPER_CLASS(Implementation); public: Implementation(); Implementation(const jni::LObject& object); }; typedef java::ObjectPointer<Implementation> PImplementation; ///////////////////////////////////////////////////////////////////// implementation ///////////////////////////////////////////////// Interface #define JB_CURRENT_CLASS Interface JB_DEFINE_WRAPPER_CLASS( "com/itoa/jnipp/test/Casts$Interface" , NoFields , NoMethods ) Interface::Interface(const jni::LObject& object): java::Object(object) { } #undef JB_CURRENT_CLASS ///////////////////////////////////////////////// Base #define JB_CURRENT_CLASS Base JB_DEFINE_WRAPPER_CLASS( "com/itoa/jnipp/test/Casts$Base" , NoFields , Methods (Constructor,"<init>","()V") ) Base::Base(): java::Object(JB_NEW(Constructor)) { } Base::Base(const jni::LObject& object): java::Object(object) { } #undef JB_CURRENT_CLASS ///////////////////////////////////////////////// Derived #define JB_CURRENT_CLASS Derived JB_DEFINE_WRAPPER_CLASS( "com/itoa/jnipp/test/Casts$Derived" , NoFields , Methods (Constructor,"<init>","()V") ) Derived::Derived(): Base(JB_NEW(Constructor)) { } Derived::Derived(const jni::LObject& object): Base(object) { } #undef JB_CURRENT_CLASS ///////////////////////////////////////////////// Implementation #define JB_CURRENT_CLASS Implementation JB_DEFINE_WRAPPER_CLASS( "com/itoa/jnipp/test/Casts$Implementation" , NoFields , Methods (Constructor,"<init>","()V") ) Implementation::Implementation(): java::Object(JB_NEW(Constructor)) { } Implementation::Implementation(const jni::LObject& object): java::Object(object) { } #undef JB_CURRENT_CLASS ///////////////////////////////////////////////// check template <class OtherObjectType> static void CheckedCast(const jni::AbstractObject& object,bool shouldSucceed) { typedef typename java::ObjectTypeExtractor<OtherObjectType>::Type RealOOType; try { java::ObjectPointer<RealOOType> result=java::Cast<OtherObjectType>(object); if (!shouldSucceed) { TEST_FAILED("Cast to '%s' should have failed.", RealOOType::GetTypeClass()->GetName()->GetUTF()); } if (object.GetJObject() && !result) { TEST_FAILED("Casting to '%s' yeilded null object.", RealOOType::GetTypeClass()->GetName()->GetUTF()); } } catch (const jni::AbstractObject& exception) { if (shouldSucceed) { TEST_FAILED("Cast to %s failed.", java::Object::GetClass(object)->GetName()->GetUTF()); } else { java::PString exceptionClassName=java::Object::GetClass(exception)->GetName(); if (strcmp(exceptionClassName->GetUTF(),"java.lang.ClassCastException")) { TEST_FAILED("Cast threw invalid exception '%s'.", exceptionClassName->GetUTF()); } java::PString exceptionMessage=java::Cast<java::Throwable>(exception)->GetMessage(); java::PClass classTo=RealOOType::GetTypeClass(); java::PString classToName=classTo->GetName(); if (strcmp(classTo->GetName()->GetUTF(),exceptionMessage->GetUTF())) { TEST_FAILED("Cast threw wrong message '%s'.", exceptionMessage->GetUTF()); } } } } ///////////////////////////////////////////////////////////////////// test void RunCastsTest() { { jni::LObject null; CheckedCast<java::Object>(null,true); CheckedCast<Interface>(null,true); CheckedCast<Base>(null,true); } { java::PString string=java::PString::New("Hello!"); CheckedCast<java::Object>(string,true); CheckedCast<Interface>(string,false); CheckedCast<Base>(string,false); } { PDerived derived=new Derived(); CheckedCast<java::Object>(derived,true); CheckedCast<Base>(derived,true); CheckedCast<Interface>(derived,true); CheckedCast<Implementation>(derived,false); CheckedCast<java::PString>(derived,false); } { PImplementation implementation=new Implementation(); CheckedCast<java::Object>(implementation,true); CheckedCast<Interface>(implementation,true); CheckedCast<Base>(implementation,false); CheckedCast<java::PString>(implementation,false); } TEST_PASSED(); }
25.099138
96
0.606045
[ "object" ]
070b71ddac254dfbfbc04604b54b9275a205e105
2,427
cpp
C++
MP-APS/Core/GUISystem.cpp
MaximumProgrammer/OpenGL-Renderer
018211ff3bd559d6912784d3dfdec97f03838e35
[ "MIT" ]
1
2021-12-21T17:57:17.000Z
2021-12-21T17:57:17.000Z
MP-APS/Core/GUISystem.cpp
MaximumProgrammer/OpenGL-Renderer
018211ff3bd559d6912784d3dfdec97f03838e35
[ "MIT" ]
null
null
null
MP-APS/Core/GUISystem.cpp
MaximumProgrammer/OpenGL-Renderer
018211ff3bd559d6912784d3dfdec97f03838e35
[ "MIT" ]
null
null
null
#include "GUISystem.h" #include "../FrameStats.h" #include <fmt/core.h> #include <cstddef> #include <glad/glad.h> #include <GLFW/glfw3.h> #define NK_INCLUDE_FIXED_TYPES #define NK_INCLUDE_STANDARD_IO #define NK_INCLUDE_STANDARD_VARARGS #define NK_INCLUDE_DEFAULT_ALLOCATOR #define NK_INCLUDE_VERTEX_BUFFER_OUTPUT #define NK_INCLUDE_FONT_BAKING #define NK_INCLUDE_DEFAULT_FONT #define NK_IMPLEMENTATION #define NK_GLFW_GL4_IMPLEMENTATION #define NK_KEYSTATE_BASED_INPUT #include <nuklear/nuklear.h> #include <nuklear/nuklear_glfw_gl4.h> // https://github.com/Immediate-Mode-UI/Nuklear/blob/master/demo/glfw_opengl4/main.c const constexpr std::size_t MaxVertexBuffer{ 512 * 1024 }; const constexpr std::size_t MaxElementBuffer{ 128 * 1024 }; /***********************************************************************************/ void GUISystem::Init(GLFWwindow* windowPtr) { m_nuklearContext = nk_glfw3_init(windowPtr, NK_GLFW3_INSTALL_CALLBACKS, MaxVertexBuffer, MaxElementBuffer); /* Load Fonts: if none of these are loaded a default font will be used */ /* Load Cursor: if you uncomment cursor loading please hide the cursor */ { struct nk_font_atlas* atlas; nk_glfw3_font_stash_begin(&atlas); nk_glfw3_font_stash_end(); } } /***********************************************************************************/ void GUISystem::Render(const int framebufferWidth, const int framebufferHeight, const FrameStats& frameStats) { struct nk_colorf bg; bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; nk_glfw3_new_frame(); const auto frameStatFlags = NK_WINDOW_BORDER | NK_WINDOW_NO_SCROLLBAR | NK_WINDOW_NO_INPUT; if (nk_begin(m_nuklearContext, "Frame Stats", nk_rect(0, framebufferHeight - 40, 500, 40), frameStatFlags)) { nk_layout_row_begin(m_nuklearContext, NK_STATIC, 0, 1); { nk_layout_row_push(m_nuklearContext, 500); nk_label( m_nuklearContext, fmt::format("Frame Time: {:.2f} ms ({:.0f} fps) | GPU VRAM Usage: {} MB", frameStats.frameTimeMilliseconds, 1.0 / (frameStats.frameTimeMilliseconds / 1000.0), frameStats.videoMemoryUsageKB / 1000 ).c_str(), NK_TEXT_LEFT ); } nk_layout_row_end(m_nuklearContext); } nk_end(m_nuklearContext); nk_glfw3_render(NK_ANTI_ALIASING_ON); } /***********************************************************************************/ void GUISystem::Shutdown() const { nk_glfw3_shutdown(); }
30.721519
110
0.675731
[ "render" ]
070e1664d3ca9a5aa29456d80dddef6ef325d0e1
3,025
hpp
C++
src/headers/Bread.hpp
ViralTaco/Toast
476ee8eb9b0c852bd17cfdd296c06c43f7ab1f25
[ "Unlicense" ]
null
null
null
src/headers/Bread.hpp
ViralTaco/Toast
476ee8eb9b0c852bd17cfdd296c06c43f7ab1f25
[ "Unlicense" ]
1
2018-12-26T00:14:06.000Z
2018-12-27T13:11:58.000Z
src/headers/Bread.hpp
ViralTaco/Toast
476ee8eb9b0c852bd17cfdd296c06c43f7ab1f25
[ "Unlicense" ]
null
null
null
/* * Copyright (c) 2018 Capobianco A. * SPDX-License-Identifier: MIT * <http://www.opensource.org/licenses/MIT> */ #pragma once #include <string> #include <vector> #include <utility> #include <fstream> #include <cstdlib> struct Element { public: bool is_checked_; std::string content_; std::string mark_; Element(bool is_checked, std::string content) noexcept : is_checked_{is_checked} , content_{std::move(content)} , mark_{(is_checked) ? " [\x1b[92m*\x1b[0m] " : " [] "} {} Element(std::string content) noexcept : is_checked_{false} , content_{content} , mark_{" [] "} {} std::string to_string() const noexcept { return mark_ + content_ + "\n"; } void check() noexcept { is_checked_ = true; mark_ = " [\x1b[92m*\x1b[0m] "; } }; class Bread { private: const std::string kPath_; std::vector<Element> elements_; public: Bread(std::string path) noexcept : kPath_{ path } { set_elements(); } private: void set_elements() { std::ifstream filestream(kPath_, std::ios::in); // for all lines in the file for (std::string line; std::getline(filestream, line); ) { // if there is a '*' in the line the toast is done bool done{line.find_first_of('*') != std::string::npos}; // The line is as follows: ID (int) [MARK (char)] STRING // We just want the string. elements_.push_back(Element(done, line.substr(line.find(']') + 2))); } } public: void add(const std::string& element) { elements_.push_back(Element(element)); } void operator += (const std::string& element) { this->add(element); } void rm(const std::size_t id) { elements_.erase(elements_.begin() + static_cast<long>(id)); elements_.shrink_to_fit(); } void push_to_file() const { std::ofstream push_toast(kPath_, std::ios::trunc); push_toast << this->to_string(); } [[noreturn]] void clear() const { static constexpr auto kOpenMode{ std::ofstream::out | std::ios::trunc }; std::ofstream clear_toast(kPath_, kOpenMode); clear_toast.close(); std::exit(EXIT_SUCCESS); } void check(std::size_t id) noexcept { elements_.at(id).check(); } public: std::size_t get_bread_count() const noexcept { return elements_.size(); } std::string to_string() const noexcept { std::string result; std::size_t i = 0; for (const auto& element: elements_) { result += std::to_string(++i) + element.to_string(); } return result; } std::string to_string(const std::size_t index) const { return elements_.at(index).to_string(); } std::pair<bool, std::string> at(const std::size_t index) const { const auto e{elements_.at(index)}; return std::make_pair(e.is_checked_, e.content_); // This isn't good enough. // at should return an actual ref to the element. } std::pair<bool, std::string> operator [] (const std::size_t index) const { return this->at(index); } };
23.269231
76
0.625124
[ "vector" ]
070e371b0135867b2cbe39d81605ee1457ce08ed
1,013
hpp
C++
src/toolkits/coreml_export/mldata_exporter.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
src/toolkits/coreml_export/mldata_exporter.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
src/toolkits/coreml_export/mldata_exporter.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #ifndef COREML_MLDATA_EXPORTER_HPP #define COREML_MLDATA_EXPORTER_HPP #include <toolkits/coreml_export/mlmodel_include.hpp> #include <ml/ml_data/metadata.hpp> namespace turi { /** * Initiates a pipeline from an MLData metadata object so that it takes the input * in the form of the input from the mldata, then outputs it as a final * vector named __vectorized_features__ that can then be used by other algorithms. * The pipeline is returned. The input variables of the pipeline are the same * as those given in the ml_data metadata object. The classifier or regressor * needs to be added to the pipeline, along with the appropriate output variables. * */ void setup_pipeline_from_mldata( CoreML::Pipeline& pipeline, std::shared_ptr<ml_metadata> metadata); } #endif
33.766667
86
0.76308
[ "object", "vector" ]
07108efbf26744ec9fc63d40cfd3bf71cc453b4b
17,727
cpp
C++
HTN_Plugin/Source/HTN_Plugin/Private/JSHOP2_Experiments/SimpleFPS/HTNWorldState_SimpleFPS.cpp
DennisSoemers/HTN_Plan_Reuse
acdf5e6f808f50b98a4be4da653a7c27b6e713df
[ "MIT" ]
43
2016-09-29T11:50:43.000Z
2022-02-01T19:48:40.000Z
HTN_Plugin/Source/HTN_Plugin/Private/JSHOP2_Experiments/SimpleFPS/HTNWorldState_SimpleFPS.cpp
DennisSoemers/HTN_Plan_Reuse
acdf5e6f808f50b98a4be4da653a7c27b6e713df
[ "MIT" ]
null
null
null
HTN_Plugin/Source/HTN_Plugin/Private/JSHOP2_Experiments/SimpleFPS/HTNWorldState_SimpleFPS.cpp
DennisSoemers/HTN_Plan_Reuse
acdf5e6f808f50b98a4be4da653a7c27b6e713df
[ "MIT" ]
13
2016-08-04T01:54:29.000Z
2021-09-22T06:47:20.000Z
#include "HTN_PluginPrivatePCH.h" #include "JSHOP2_Experiments/SimpleFPS/HTNWorldState_SimpleFPS.h" #include "JSHOP2_Experiments/SimpleFPS/JSHOP2_ExperimenterSimpleFPS.h" #include "JSHOP2_Experiments/SimpleFPS/SimpleFPSObject.h" #include "JSHOP2_Experiments/SimpleFPS/Tasks/HTNTask_MoveToAreaSimpleFPS.h" TSharedPtr<FHTNWorldState> FHTNWorldState_SimpleFPS::Copy() const { FHTNWorldState_SimpleFPS* NewWorldState = new FHTNWorldState_SimpleFPS(); // everything in the data arrays is plain old data structs, so we can safely just copy memory NewWorldState->AmmoData.AddUninitialized(AmmoData.Num()); FMemory::Memcpy(NewWorldState->AmmoData.GetData(), AmmoData.GetData(), AmmoData.Num() * sizeof(FSimpleFPSAmmoData)); NewWorldState->AreaData.AddUninitialized(AreaData.Num()); FMemory::Memcpy(NewWorldState->AreaData.GetData(), AreaData.GetData(), AreaData.Num() * sizeof(FSimpleFPSAreaData)); NewWorldState->ControlBoxData.AddUninitialized(ControlBoxData.Num()); FMemory::Memcpy(NewWorldState->ControlBoxData.GetData(), ControlBoxData.GetData(), ControlBoxData.Num() * sizeof(FSimpleFPSControlBoxData)); NewWorldState->CoverPointData.AddUninitialized(CoverPointData.Num()); FMemory::Memcpy(NewWorldState->CoverPointData.GetData(), CoverPointData.GetData(), CoverPointData.Num() * sizeof(FSimpleFPSCoverPointData)); NewWorldState->GunData.AddUninitialized(GunData.Num()); FMemory::Memcpy(NewWorldState->GunData.GetData(), GunData.GetData(), GunData.Num() * sizeof(FSimpleFPSGunData)); NewWorldState->KeycardData.AddUninitialized(KeycardData.Num()); FMemory::Memcpy(NewWorldState->KeycardData.GetData(), KeycardData.GetData(), KeycardData.Num() * sizeof(FSimpleFPSKeycardData)); NewWorldState->KnifeData.AddUninitialized(KnifeData.Num()); FMemory::Memcpy(NewWorldState->KnifeData.GetData(), KnifeData.GetData(), KnifeData.Num() * sizeof(FSimpleFPSKnifeData)); NewWorldState->MedikitData.AddUninitialized(MedikitData.Num()); FMemory::Memcpy(NewWorldState->MedikitData.GetData(), MedikitData.GetData(), MedikitData.Num() * sizeof(FSimpleFPSMedikitData)); NewWorldState->PlayerData.AddUninitialized(PlayerData.Num()); FMemory::Memcpy(NewWorldState->PlayerData.GetData(), PlayerData.GetData(), PlayerData.Num() * sizeof(FSimpleFPSPlayerData)); NewWorldState->WaypointData.AddUninitialized(WaypointData.Num()); FMemory::Memcpy(NewWorldState->WaypointData.GetData(), WaypointData.GetData(), WaypointData.Num() * sizeof(FSimpleFPSWaypointData)); // need to copy the NPC-related properties NewWorldState->NPCInventory.Append(NPCInventory); NewWorldState->NPCNearbyPOI = NPCNearbyPOI; NewWorldState->NPCArea = NPCArea; NewWorldState->bNPCAware = bNPCAware; NewWorldState->bNPCCovered = bNPCCovered; NewWorldState->bNPCInjured = bNPCInjured; // finally need to make sure we share the correct pointer to constant data NewWorldState->SetConstData(ConstData); return MakeShareable<FHTNWorldState>(NewWorldState); } void FHTNWorldState_SimpleFPS::CopyFrom(const FHTNWorldState_SimpleFPS* Other) { // everything in the data arrays is plain old data structs, so we can safely just copy memory AmmoData.AddUninitialized(Other->AmmoData.Num()); FMemory::Memcpy(AmmoData.GetData(), Other->AmmoData.GetData(), Other->AmmoData.Num() * sizeof(FSimpleFPSAmmoData)); AreaData.AddUninitialized(Other->AreaData.Num()); FMemory::Memcpy(AreaData.GetData(), Other->AreaData.GetData(), Other->AreaData.Num() * sizeof(FSimpleFPSAreaData)); ControlBoxData.AddUninitialized(Other->ControlBoxData.Num()); FMemory::Memcpy(ControlBoxData.GetData(), Other->ControlBoxData.GetData(), Other->ControlBoxData.Num() * sizeof(FSimpleFPSControlBoxData)); CoverPointData.AddUninitialized(Other->CoverPointData.Num()); FMemory::Memcpy(CoverPointData.GetData(), Other->CoverPointData.GetData(), Other->CoverPointData.Num() * sizeof(FSimpleFPSCoverPointData)); GunData.AddUninitialized(Other->GunData.Num()); FMemory::Memcpy(GunData.GetData(), Other->GunData.GetData(), Other->GunData.Num() * sizeof(FSimpleFPSGunData)); KeycardData.AddUninitialized(Other->KeycardData.Num()); FMemory::Memcpy(KeycardData.GetData(), Other->KeycardData.GetData(), Other->KeycardData.Num() * sizeof(FSimpleFPSKeycardData)); KnifeData.AddUninitialized(Other->KnifeData.Num()); FMemory::Memcpy(KnifeData.GetData(), Other->KnifeData.GetData(), Other->KnifeData.Num() * sizeof(FSimpleFPSKnifeData)); MedikitData.AddUninitialized(Other->MedikitData.Num()); FMemory::Memcpy(MedikitData.GetData(), Other->MedikitData.GetData(), Other->MedikitData.Num() * sizeof(FSimpleFPSMedikitData)); PlayerData.AddUninitialized(Other->PlayerData.Num()); FMemory::Memcpy(PlayerData.GetData(), Other->PlayerData.GetData(), Other->PlayerData.Num() * sizeof(FSimpleFPSPlayerData)); WaypointData.AddUninitialized(Other->WaypointData.Num()); FMemory::Memcpy(WaypointData.GetData(), Other->WaypointData.GetData(), Other->WaypointData.Num() * sizeof(FSimpleFPSWaypointData)); // need to copy the NPC-related properties NPCInventory.Append(Other->NPCInventory); NPCNearbyPOI = Other->NPCNearbyPOI; NPCArea = Other->NPCArea; bNPCAware = Other->bNPCAware; bNPCCovered = Other->bNPCCovered; bNPCInjured = Other->bNPCInjured; // finally need to make sure we share the correct pointer to constant data SetConstData(Other->ConstData); } void FHTNWorldState_SimpleFPS::Initialize(AActor* Owner, UBlackboardComponent* BlackboardComponent) { if(AJSHOP2_ExperimenterSimpleFPS* Experimenter = Cast<AJSHOP2_ExperimenterSimpleFPS>(Owner)) { Experimenter->InitializeWorldState(this); } } FSimpleFPSObject* FHTNWorldState_SimpleFPS::CreateAmmo(int32 Area, FString Name) { // create the object FSimpleFPSObject* Ammo = new FSimpleFPSObject(); // set up properties Ammo->ObjectName = Name; Ammo->Index = ConstData->Ammo.Num(); Ammo->ObjectType = ESimpleFPSObjectTypes::Ammo; // add the object ConstData->Ammo.Add(Ammo); ConstData->ObjectPool.Add(MakeShareable<FSimpleFPSObject>(Ammo)); // create and add the non-constant data AmmoData.Add(FSimpleFPSAmmoData(Area)); // return the object return Ammo; } FSimpleFPSObject* FHTNWorldState_SimpleFPS::CreateArea(bool bLighted, FString Name) { // create the object FSimpleFPSObject* Area = new FSimpleFPSObject(); // set up properties Area->ObjectName = Name; Area->Index = ConstData->Areas.Num(); Area->ObjectType = ESimpleFPSObjectTypes::Area; // add the object ConstData->Areas.Add(Area); ConstData->ObjectPool.Add(MakeShareable<FSimpleFPSObject>(Area)); // create and add the non-constant data AreaData.Add(FSimpleFPSAreaData(bLighted)); // return the object return Area; } FSimpleFPSObject* FHTNWorldState_SimpleFPS::CreateControlBox(int32 Area, FString Name) { // create the object FSimpleFPSObject* ControlBox = new FSimpleFPSObject(); // set up properties ControlBox->ObjectName = Name; ControlBox->Index = ConstData->ControlBoxes.Num(); ControlBox->ObjectType = ESimpleFPSObjectTypes::ControlBox; // add the object ConstData->ControlBoxes.Add(ControlBox); ConstData->ObjectPool.Add(MakeShareable<FSimpleFPSObject>(ControlBox)); // create and add the non-constant data ControlBoxData.Add(FSimpleFPSControlBoxData(Area)); // return the object return ControlBox; } FSimpleFPSObject* FHTNWorldState_SimpleFPS::CreateCoverPoint(int32 Area, FString Name) { // create the object FSimpleFPSObject* CoverPoint = new FSimpleFPSObject(); // set up properties CoverPoint->ObjectName = Name; CoverPoint->Index = ConstData->CoverPoints.Num(); CoverPoint->ObjectType = ESimpleFPSObjectTypes::CoverPoint; // add the object ConstData->CoverPoints.Add(CoverPoint); ConstData->ObjectPool.Add(MakeShareable<FSimpleFPSObject>(CoverPoint)); // create and add the non-constant data CoverPointData.Add(FSimpleFPSCoverPointData(Area)); // return the object return CoverPoint; } FSimpleFPSObject* FHTNWorldState_SimpleFPS::CreateGun(int32 Area, bool bLoaded, int32 AmmoIndex, bool bNightVision, FString Name) { // create the object FSimpleFPSObject* Gun = new FSimpleFPSObject(); // set up properties Gun->ObjectName = Name; Gun->Index = ConstData->Guns.Num(); Gun->ObjectType = ESimpleFPSObjectTypes::Gun; // add the object ConstData->Guns.Add(Gun); ConstData->ObjectPool.Add(MakeShareable<FSimpleFPSObject>(Gun)); // create and add the non-constant data GunData.Add(FSimpleFPSGunData(AmmoIndex, Area, bNightVision, bLoaded)); // return the object return Gun; } FSimpleFPSObject* FHTNWorldState_SimpleFPS::CreateKeycard(int32 Area, FString Name) { // create the object FSimpleFPSObject* Keycard = new FSimpleFPSObject(); // set up properties Keycard->ObjectName = Name; Keycard->Index = ConstData->Keycards.Num(); Keycard->ObjectType = ESimpleFPSObjectTypes::Keycard; // add the object ConstData->Keycards.Add(Keycard); ConstData->ObjectPool.Add(MakeShareable<FSimpleFPSObject>(Keycard)); // create and add the non-constant data KeycardData.Add(FSimpleFPSKeycardData(Area)); // return the object return Keycard; } FSimpleFPSObject* FHTNWorldState_SimpleFPS::CreateKnife(int32 Area, FString Name) { // create the object FSimpleFPSObject* Knife = new FSimpleFPSObject(); // set up properties Knife->ObjectName = Name; Knife->Index = ConstData->Knives.Num(); Knife->ObjectType = ESimpleFPSObjectTypes::Knife; // add the object ConstData->Knives.Add(Knife); ConstData->ObjectPool.Add(MakeShareable<FSimpleFPSObject>(Knife)); // create and add the non-constant data KnifeData.Add(FSimpleFPSKnifeData(Area)); // return the object return Knife; } FSimpleFPSObject* FHTNWorldState_SimpleFPS::CreateMedikit(int32 Area, FString Name) { // create the object FSimpleFPSObject* Medikit = new FSimpleFPSObject(); // set up properties Medikit->ObjectName = Name; Medikit->Index = ConstData->Medikits.Num(); Medikit->ObjectType = ESimpleFPSObjectTypes::Medikit; // add the object ConstData->Medikits.Add(Medikit); ConstData->ObjectPool.Add(MakeShareable<FSimpleFPSObject>(Medikit)); // create and add the non-constant data MedikitData.Add(FSimpleFPSMedikitData(Area)); // return the object return Medikit; } FSimpleFPSObject* FHTNWorldState_SimpleFPS::CreatePlayer(int32 Area, FString Name) { // create the object FSimpleFPSObject* Player = new FSimpleFPSObject(); // set up properties Player->ObjectName = Name; Player->Index = ConstData->Players.Num(); Player->ObjectType = ESimpleFPSObjectTypes::Player; // add the object ConstData->Players.Add(Player); ConstData->ObjectPool.Add(MakeShareable<FSimpleFPSObject>(Player)); // create and add the non-constant data PlayerData.Add(FSimpleFPSPlayerData(Area)); // return the object return Player; } FSimpleFPSObject* FHTNWorldState_SimpleFPS::CreateWaypoint(int32 Area1, int32 Area2, bool bOpen, int32 Keycard, FString Name) { // create the object FSimpleFPSObject* Waypoint = new FSimpleFPSObject(); // set up properties Waypoint->ObjectName = Name; Waypoint->Index = ConstData->Waypoints.Num(); Waypoint->ObjectType = ESimpleFPSObjectTypes::Waypoint; // add the object ConstData->Waypoints.Add(Waypoint); ConstData->ObjectPool.Add(MakeShareable<FSimpleFPSObject>(Waypoint)); // create and add the non-constant data WaypointData.Add(FSimpleFPSWaypointData(Area1, Area2, Keycard, bOpen)); // return the object return Waypoint; } float FHTNWorldState_SimpleFPS::GetHeuristicCost(const TArray<TSharedPtr<FHTNTaskInstance>>& TaskInstances) const { int32 MaxMoveDistance = 0; for(const TSharedPtr<FHTNTaskInstance>& TaskInstance : TaskInstances) { UHTNTask* Task = TaskInstance->Task; if(UHTNTask_MoveToAreaSimpleFPS* MoveToAreaTask = Cast<UHTNTask_MoveToAreaSimpleFPS>(Task)) { FHTNTask_MoveToAreaSimpleFPSMemory* MoveToAreaMemory = (FHTNTask_MoveToAreaSimpleFPSMemory*)TaskInstance->GetMemory(); int32 Distance = GetDistance(NPCArea, MoveToAreaMemory->Area); if(Distance > MaxMoveDistance) { MaxMoveDistance = Distance; } } } // for every point of distance, we'll have at least a move-to-point task to move to the waypoint // connecting 2 areas, and then a moving task to use the waypoint to move between the 2 areas. // each of those tasks always has a cost of 1.f // // the move-to-area task itself has a heuristic cost of 0.f to cover cases where the NPC already is // in the correct area, so we won't be counting any heuristics double here return 2.f * MaxMoveDistance; } const TArray<FSimpleFPSObject*>& FHTNWorldState_SimpleFPS::GetAmmo() const { return ConstData->Ammo; } const TArray<FSimpleFPSObject*>& FHTNWorldState_SimpleFPS::GetAreas() const { return ConstData->Areas; } const TArray<FSimpleFPSObject*>& FHTNWorldState_SimpleFPS::GetControlBoxes() const { return ConstData->ControlBoxes; } const TArray<FSimpleFPSObject*>& FHTNWorldState_SimpleFPS::GetCoverPoints() const { return ConstData->CoverPoints; } const TArray<FSimpleFPSObject*>& FHTNWorldState_SimpleFPS::GetGuns() const { return ConstData->Guns; } const TArray<FSimpleFPSObject*>& FHTNWorldState_SimpleFPS::GetKeycards() const { return ConstData->Keycards; } const TArray<FSimpleFPSObject*>& FHTNWorldState_SimpleFPS::GetKnives() const { return ConstData->Knives; } const TArray<FSimpleFPSObject*>& FHTNWorldState_SimpleFPS::GetMedikits() const { return ConstData->Medikits; } const TArray<FSimpleFPSObject*>& FHTNWorldState_SimpleFPS::GetPlayers() const { return ConstData->Players; } const TArray<FSimpleFPSObject*>& FHTNWorldState_SimpleFPS::GetWaypoints() const { return ConstData->Waypoints; } int32 FHTNWorldState_SimpleFPS::GetArea(FSimpleFPSObject* Object) const { if(Object->ObjectType == ESimpleFPSObjectTypes::Ammo) { return AmmoData[Object->Index].Area; } else if(Object->ObjectType == ESimpleFPSObjectTypes::ControlBox) { return ControlBoxData[Object->Index].Area; } else if(Object->ObjectType == ESimpleFPSObjectTypes::CoverPoint) { return CoverPointData[Object->Index].Area; } else if(Object->ObjectType == ESimpleFPSObjectTypes::Gun) { return GunData[Object->Index].Area; } else if(Object->ObjectType == ESimpleFPSObjectTypes::Keycard) { return KeycardData[Object->Index].Area; } else if(Object->ObjectType == ESimpleFPSObjectTypes::Knife) { return KnifeData[Object->Index].Area; } else if(Object->ObjectType == ESimpleFPSObjectTypes::Medikit) { return MedikitData[Object->Index].Area; } else if(Object->ObjectType == ESimpleFPSObjectTypes::Player) { return PlayerData[Object->Index].Area; } else { return -1; } } TSharedPtr<const FHTNWorldState_SimpleFPS_ConstData> FHTNWorldState_SimpleFPS::GetConstData() const { return ConstData; } int32 FHTNWorldState_SimpleFPS::GetDistance(int32 Area1, int32 Area2) const { return ConstData->DistanceMatrix[Area1][Area2]; } const TArray<int32>& FHTNWorldState_SimpleFPS::GetDistanceRow(int32 Area) const { return ConstData->DistanceMatrix[Area]; } bool FHTNWorldState_SimpleFPS::IsInArea(FSimpleFPSObject* Object, int32 Area) const { if(Object->ObjectType == ESimpleFPSObjectTypes::Waypoint) { return (WaypointData[Object->Index].Area1 == Area || WaypointData[Object->Index].Area2 == Area ); } else { return (Area == GetArea(Object)); } } bool FHTNWorldState_SimpleFPS::IsLocked(const FSimpleFPSObject* Waypoint) const { if(ConstData->bExecutionMode) { return !WaypointData[Waypoint->Index].bOpen; } else { return (!WaypointData[Waypoint->Index].bOpen && ConstData->KnownLockedWaypoints.Contains(Waypoint)); } } bool FHTNWorldState_SimpleFPS::IsReachable(int32 Area1, int32 Area2) const { return ConstData->DistanceMatrix[Area1][Area2] < 10000; // TO DO should probably use same variable here as in problem generator, no magic number } void FHTNWorldState_SimpleFPS::SetArea(FSimpleFPSObject* Object, int32 NewArea) { if(Object->ObjectType == ESimpleFPSObjectTypes::Ammo) { AmmoData[Object->Index].Area = NewArea; } else if(Object->ObjectType == ESimpleFPSObjectTypes::ControlBox) { ControlBoxData[Object->Index].Area = NewArea; } else if(Object->ObjectType == ESimpleFPSObjectTypes::CoverPoint) { CoverPointData[Object->Index].Area = NewArea; } else if(Object->ObjectType == ESimpleFPSObjectTypes::Gun) { GunData[Object->Index].Area = NewArea; } else if(Object->ObjectType == ESimpleFPSObjectTypes::Keycard) { KeycardData[Object->Index].Area = NewArea; } else if(Object->ObjectType == ESimpleFPSObjectTypes::Knife) { KnifeData[Object->Index].Area = NewArea; } else if(Object->ObjectType == ESimpleFPSObjectTypes::Medikit) { MedikitData[Object->Index].Area = NewArea; } else if(Object->ObjectType == ESimpleFPSObjectTypes::Player) { PlayerData[Object->Index].Area = NewArea; } } void FHTNWorldState_SimpleFPS::SetConstData(TSharedPtr<FHTNWorldState_SimpleFPS_ConstData> Data) { ConstData = Data; } void FHTNWorldState_SimpleFPS::SetDistanceMatrix(const TArray<TArray<int32>>& DistanceMatrix) { ConstData->DistanceMatrix = TArray<TArray<int32>>(); ConstData->DistanceMatrix.Reserve(DistanceMatrix.Num()); for(int32 Row = 0; Row < DistanceMatrix.Num(); ++Row) { ConstData->DistanceMatrix.Add(TArray<int32>()); TArray<int32>& DistanceRow = ConstData->DistanceMatrix[Row]; DistanceRow.Reserve(DistanceMatrix.Num()); for(int32 Col = 0; Col < DistanceMatrix.Num(); ++Col) { DistanceRow.Add(DistanceMatrix[Row][Col]); } } } void FHTNWorldState_SimpleFPS::SetExecutionMode(bool bMode) { ConstData->bExecutionMode = bMode; } void FHTNWorldState_SimpleFPS::SetKnownLock(FSimpleFPSObject* Waypoint) { ConstData->KnownLockedWaypoints.Add(Waypoint); } void FHTNWorldState_SimpleFPS::SetPreferredWeaponChoice(uint8 WeaponChoice) { ConstData->PreferredWeaponChoice = WeaponChoice; }
32.056058
145
0.773114
[ "object" ]
071de024a3fa400ec201d8a300e9bc3194d4cba6
2,527
cpp
C++
lib/MC/MCXCOFFStreamer.cpp
URSec/Silhouette-Compiler-Legacy
28b37f3617c5543a87537decc074b168f4803d87
[ "Apache-2.0" ]
173
2015-01-14T00:05:41.000Z
2022-02-22T05:47:18.000Z
lib/MC/MCXCOFFStreamer.cpp
URSec/Silhouette-Compiler-Legacy
28b37f3617c5543a87537decc074b168f4803d87
[ "Apache-2.0" ]
9
2015-01-02T06:20:32.000Z
2017-10-19T13:21:02.000Z
lib/MC/MCXCOFFStreamer.cpp
URSec/Silhouette-Compiler-Legacy
28b37f3617c5543a87537decc074b168f4803d87
[ "Apache-2.0" ]
45
2018-06-16T08:51:03.000Z
2022-02-11T09:52:02.000Z
//===- lib/MC/MCXCOFFStreamer.cpp - XCOFF Object Output -------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file assembles .s files and emits XCOFF .o object files. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCXCOFFStreamer.h" #include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCCodeEmitter.h" #include "llvm/MC/MCObjectWriter.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; MCXCOFFStreamer::MCXCOFFStreamer(MCContext &Context, std::unique_ptr<MCAsmBackend> MAB, std::unique_ptr<MCObjectWriter> OW, std::unique_ptr<MCCodeEmitter> Emitter) : MCObjectStreamer(Context, std::move(MAB), std::move(OW), std::move(Emitter)) {} bool MCXCOFFStreamer::EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) { report_fatal_error("Symbol attributes not implemented for XCOFF."); } void MCXCOFFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) { report_fatal_error("Emiting common symbols not implemented for XCOFF."); } void MCXCOFFStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment, SMLoc Loc) { report_fatal_error("Zero fill not implemented for XCOFF."); } void MCXCOFFStreamer::EmitInstToData(const MCInst &Inst, const MCSubtargetInfo &) { report_fatal_error("Instruction emission not implemented for XCOFF."); } MCStreamer *llvm::createXCOFFStreamer(MCContext &Context, std::unique_ptr<MCAsmBackend> &&MAB, std::unique_ptr<MCObjectWriter> &&OW, std::unique_ptr<MCCodeEmitter> &&CE, bool RelaxAll) { MCXCOFFStreamer *S = new MCXCOFFStreamer(Context, std::move(MAB), std::move(OW), std::move(CE)); if (RelaxAll) S->getAssembler().setRelaxAll(true); return S; }
42.116667
80
0.555204
[ "object" ]
0721eb56a022b33606949f316e85c0f6d882bd84
13,555
cpp
C++
plugins/community/repos/Bogaudio/src/Matrix88.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/Bogaudio/src/Matrix88.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/Bogaudio/src/Matrix88.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-14T21:55:30.000Z
2021-05-04T04:20:34.000Z
#include "Matrix88.hpp" void Matrix88::step() { for (int i = 0; i < 8; ++i) { int paramOffset = MIX11_PARAM + i * 8; float out = 0.0f; for (int j = 0; j < 8; ++j) { out += inputs[IN1_INPUT + j].value * params[paramOffset + j].value; } outputs[OUT1_OUTPUT + i].value = _saturators[i].next(params[LEVEL_PARAM].value * out); } } struct Matrix88Widget : ModuleWidget { static constexpr int hp = 22; Matrix88Widget(Matrix88* module) : ModuleWidget(module) { box.size = Vec(RACK_GRID_WIDTH * hp, RACK_GRID_HEIGHT); { SVGPanel *panel = new SVGPanel(); panel->box.size = box.size; panel->setBackground(SVG::load(assetPlugin(plugin, "res/Matrix88.svg"))); addChild(panel); } addChild(Widget::create<ScrewSilver>(Vec(15, 0))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 30, 0))); addChild(Widget::create<ScrewSilver>(Vec(15, 365))); addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 30, 365))); // generated by svg_widgets.rb auto mix11ParamPosition = Vec(53.7, 32.2); auto mix21ParamPosition = Vec(53.7, 69.2); auto mix31ParamPosition = Vec(53.7, 106.2); auto mix41ParamPosition = Vec(53.7, 143.2); auto mix51ParamPosition = Vec(53.7, 180.2); auto mix61ParamPosition = Vec(53.7, 217.2); auto mix71ParamPosition = Vec(53.7, 254.2); auto mix81ParamPosition = Vec(53.7, 291.2); auto mix12ParamPosition = Vec(88.7, 32.2); auto mix22ParamPosition = Vec(88.7, 69.2); auto mix32ParamPosition = Vec(88.7, 106.2); auto mix42ParamPosition = Vec(88.7, 143.2); auto mix52ParamPosition = Vec(88.7, 180.2); auto mix62ParamPosition = Vec(88.7, 217.2); auto mix72ParamPosition = Vec(88.7, 254.2); auto mix82ParamPosition = Vec(88.7, 291.2); auto mix13ParamPosition = Vec(123.7, 32.2); auto mix23ParamPosition = Vec(123.7, 69.2); auto mix33ParamPosition = Vec(123.7, 106.2); auto mix43ParamPosition = Vec(123.7, 143.2); auto mix53ParamPosition = Vec(123.7, 180.2); auto mix63ParamPosition = Vec(123.7, 217.2); auto mix73ParamPosition = Vec(123.7, 254.2); auto mix83ParamPosition = Vec(123.7, 291.2); auto mix14ParamPosition = Vec(158.7, 32.2); auto mix24ParamPosition = Vec(158.7, 69.2); auto mix34ParamPosition = Vec(158.7, 106.2); auto mix44ParamPosition = Vec(158.7, 143.2); auto mix54ParamPosition = Vec(158.7, 180.2); auto mix64ParamPosition = Vec(158.7, 217.2); auto mix74ParamPosition = Vec(158.7, 254.2); auto mix84ParamPosition = Vec(158.7, 291.2); auto mix15ParamPosition = Vec(193.7, 32.2); auto mix25ParamPosition = Vec(193.7, 69.2); auto mix35ParamPosition = Vec(193.7, 106.2); auto mix45ParamPosition = Vec(193.7, 143.2); auto mix55ParamPosition = Vec(193.7, 180.2); auto mix65ParamPosition = Vec(193.7, 217.2); auto mix75ParamPosition = Vec(193.7, 254.2); auto mix85ParamPosition = Vec(193.7, 291.2); auto mix16ParamPosition = Vec(228.7, 32.2); auto mix26ParamPosition = Vec(228.7, 69.2); auto mix36ParamPosition = Vec(228.7, 106.2); auto mix46ParamPosition = Vec(228.7, 143.2); auto mix56ParamPosition = Vec(228.7, 180.2); auto mix66ParamPosition = Vec(228.7, 217.2); auto mix76ParamPosition = Vec(228.7, 254.2); auto mix86ParamPosition = Vec(228.7, 291.2); auto mix17ParamPosition = Vec(263.7, 32.2); auto mix27ParamPosition = Vec(263.7, 69.2); auto mix37ParamPosition = Vec(263.7, 106.2); auto mix47ParamPosition = Vec(263.7, 143.2); auto mix57ParamPosition = Vec(263.7, 180.2); auto mix67ParamPosition = Vec(263.7, 217.2); auto mix77ParamPosition = Vec(263.7, 254.2); auto mix87ParamPosition = Vec(263.7, 291.2); auto mix18ParamPosition = Vec(298.7, 32.2); auto mix28ParamPosition = Vec(298.7, 69.2); auto mix38ParamPosition = Vec(298.7, 106.2); auto mix48ParamPosition = Vec(298.7, 143.2); auto mix58ParamPosition = Vec(298.7, 180.2); auto mix68ParamPosition = Vec(298.7, 217.2); auto mix78ParamPosition = Vec(298.7, 254.2); auto mix88ParamPosition = Vec(298.7, 291.2); auto levelParamPosition = Vec(14.5, 339.5); auto in1InputPosition = Vec(10.5, 30.0); auto in2InputPosition = Vec(10.5, 67.0); auto in3InputPosition = Vec(10.5, 104.0); auto in4InputPosition = Vec(10.5, 141.0); auto in5InputPosition = Vec(10.5, 178.0); auto in6InputPosition = Vec(10.5, 215.0); auto in7InputPosition = Vec(10.5, 252.0); auto in8InputPosition = Vec(10.5, 289.0); auto out1OutputPosition = Vec(51.5, 328.0); auto out2OutputPosition = Vec(86.5, 328.0); auto out3OutputPosition = Vec(121.5, 328.0); auto out4OutputPosition = Vec(156.5, 328.0); auto out5OutputPosition = Vec(191.5, 328.0); auto out6OutputPosition = Vec(226.5, 328.0); auto out7OutputPosition = Vec(261.5, 328.0); auto out8OutputPosition = Vec(296.5, 328.0); // end generated by svg_widgets.rb addParam(ParamWidget::create<Knob19>(mix11ParamPosition, module, Matrix88::MIX11_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix21ParamPosition, module, Matrix88::MIX21_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix31ParamPosition, module, Matrix88::MIX31_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix41ParamPosition, module, Matrix88::MIX41_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix51ParamPosition, module, Matrix88::MIX51_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix61ParamPosition, module, Matrix88::MIX61_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix71ParamPosition, module, Matrix88::MIX71_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix81ParamPosition, module, Matrix88::MIX81_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix12ParamPosition, module, Matrix88::MIX12_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix22ParamPosition, module, Matrix88::MIX22_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix32ParamPosition, module, Matrix88::MIX32_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix42ParamPosition, module, Matrix88::MIX42_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix52ParamPosition, module, Matrix88::MIX52_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix62ParamPosition, module, Matrix88::MIX62_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix72ParamPosition, module, Matrix88::MIX72_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix82ParamPosition, module, Matrix88::MIX82_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix13ParamPosition, module, Matrix88::MIX13_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix23ParamPosition, module, Matrix88::MIX23_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix33ParamPosition, module, Matrix88::MIX33_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix43ParamPosition, module, Matrix88::MIX43_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix53ParamPosition, module, Matrix88::MIX53_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix63ParamPosition, module, Matrix88::MIX63_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix73ParamPosition, module, Matrix88::MIX73_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix83ParamPosition, module, Matrix88::MIX83_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix14ParamPosition, module, Matrix88::MIX14_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix24ParamPosition, module, Matrix88::MIX24_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix34ParamPosition, module, Matrix88::MIX34_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix44ParamPosition, module, Matrix88::MIX44_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix54ParamPosition, module, Matrix88::MIX54_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix64ParamPosition, module, Matrix88::MIX64_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix74ParamPosition, module, Matrix88::MIX74_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix84ParamPosition, module, Matrix88::MIX84_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix15ParamPosition, module, Matrix88::MIX15_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix25ParamPosition, module, Matrix88::MIX25_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix35ParamPosition, module, Matrix88::MIX35_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix45ParamPosition, module, Matrix88::MIX45_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix55ParamPosition, module, Matrix88::MIX55_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix65ParamPosition, module, Matrix88::MIX65_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix75ParamPosition, module, Matrix88::MIX75_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix85ParamPosition, module, Matrix88::MIX85_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix16ParamPosition, module, Matrix88::MIX16_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix26ParamPosition, module, Matrix88::MIX26_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix36ParamPosition, module, Matrix88::MIX36_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix46ParamPosition, module, Matrix88::MIX46_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix56ParamPosition, module, Matrix88::MIX56_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix66ParamPosition, module, Matrix88::MIX66_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix76ParamPosition, module, Matrix88::MIX76_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix86ParamPosition, module, Matrix88::MIX86_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix17ParamPosition, module, Matrix88::MIX17_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix27ParamPosition, module, Matrix88::MIX27_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix37ParamPosition, module, Matrix88::MIX37_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix47ParamPosition, module, Matrix88::MIX47_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix57ParamPosition, module, Matrix88::MIX57_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix67ParamPosition, module, Matrix88::MIX67_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix77ParamPosition, module, Matrix88::MIX77_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix87ParamPosition, module, Matrix88::MIX87_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix18ParamPosition, module, Matrix88::MIX18_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix28ParamPosition, module, Matrix88::MIX28_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix38ParamPosition, module, Matrix88::MIX38_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix48ParamPosition, module, Matrix88::MIX48_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix58ParamPosition, module, Matrix88::MIX58_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix68ParamPosition, module, Matrix88::MIX68_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix78ParamPosition, module, Matrix88::MIX78_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob19>(mix88ParamPosition, module, Matrix88::MIX88_PARAM, -1.0, 1.0, 0.0)); addParam(ParamWidget::create<Knob16>(levelParamPosition, module, Matrix88::LEVEL_PARAM, 0.0, 1.0, 1.0)); addInput(Port::create<Port24>(in1InputPosition, Port::INPUT, module, Matrix88::IN1_INPUT)); addInput(Port::create<Port24>(in2InputPosition, Port::INPUT, module, Matrix88::IN2_INPUT)); addInput(Port::create<Port24>(in3InputPosition, Port::INPUT, module, Matrix88::IN3_INPUT)); addInput(Port::create<Port24>(in4InputPosition, Port::INPUT, module, Matrix88::IN4_INPUT)); addInput(Port::create<Port24>(in5InputPosition, Port::INPUT, module, Matrix88::IN5_INPUT)); addInput(Port::create<Port24>(in6InputPosition, Port::INPUT, module, Matrix88::IN6_INPUT)); addInput(Port::create<Port24>(in7InputPosition, Port::INPUT, module, Matrix88::IN7_INPUT)); addInput(Port::create<Port24>(in8InputPosition, Port::INPUT, module, Matrix88::IN8_INPUT)); addOutput(Port::create<Port24>(out1OutputPosition, Port::OUTPUT, module, Matrix88::OUT1_OUTPUT)); addOutput(Port::create<Port24>(out2OutputPosition, Port::OUTPUT, module, Matrix88::OUT2_OUTPUT)); addOutput(Port::create<Port24>(out3OutputPosition, Port::OUTPUT, module, Matrix88::OUT3_OUTPUT)); addOutput(Port::create<Port24>(out4OutputPosition, Port::OUTPUT, module, Matrix88::OUT4_OUTPUT)); addOutput(Port::create<Port24>(out5OutputPosition, Port::OUTPUT, module, Matrix88::OUT5_OUTPUT)); addOutput(Port::create<Port24>(out6OutputPosition, Port::OUTPUT, module, Matrix88::OUT6_OUTPUT)); addOutput(Port::create<Port24>(out7OutputPosition, Port::OUTPUT, module, Matrix88::OUT7_OUTPUT)); addOutput(Port::create<Port24>(out8OutputPosition, Port::OUTPUT, module, Matrix88::OUT8_OUTPUT)); } }; RACK_PLUGIN_MODEL_INIT(Bogaudio, Matrix88) { Model* modelMatrix88 = createModel<Matrix88, Matrix88Widget>("Bogaudio-Matrix88", "Matrix88", "signal routing matrix", MIXER_TAG); return modelMatrix88; }
64.856459
133
0.726817
[ "model" ]
0725104b7395d8f5308fb402a09840e6b95c4647
3,075
hpp
C++
src/libraries/thermophysicalModels/radiation/submodels/absorptionEmissionModel/binaryAbsorptionEmission/binaryAbsorptionEmission.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/thermophysicalModels/radiation/submodels/absorptionEmissionModel/binaryAbsorptionEmission/binaryAbsorptionEmission.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/thermophysicalModels/radiation/submodels/absorptionEmissionModel/binaryAbsorptionEmission/binaryAbsorptionEmission.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2018 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::radiation::binaryAbsorptionEmission Description Radiation coefficient based on two absorption models SourceFiles binaryAbsorptionEmission.cpp \*---------------------------------------------------------------------------*/ #ifndef radiationBinaryAbsorptionEmission_HPP #define radiationBinaryAbsorptionEmission_HPP #include "absorptionEmissionModel.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { namespace radiation { /*---------------------------------------------------------------------------*\ Class binaryAbsorptionEmission Declaration \*---------------------------------------------------------------------------*/ class binaryAbsorptionEmission : public absorptionEmissionModel { //- Coefficients dictionary dictionary coeffsDict_; //- First absorption model autoPtr<absorptionEmissionModel> model1_; //- Second absorption model autoPtr<absorptionEmissionModel> model2_; public: //- Runtime type information TypeName("binaryAbsorptionEmission"); //- Construct from components binaryAbsorptionEmission(const dictionary& dict, const fvMesh& mesh); //- Destructor virtual ~binaryAbsorptionEmission() {} // Member Functions // Access // Absorption coefficient //- Absorption coefficient for continuous phase virtual tmp<volScalarField> aCont(const label bandI = 0) const; //- Absorption coefficient for dispersed phase virtual tmp<volScalarField> aDisp(const label bandI = 0) const; // Emission coefficient //- Emission coefficient for continuous phase virtual tmp<volScalarField> eCont(const label bandI = 0) const; //- Emission coefficient for dispersed phase virtual tmp<volScalarField> eDisp(const label bandI = 0) const; // Emission contribution //- Emission contribution for continuous phase virtual tmp<volScalarField> ECont(const label bandI = 0) const; //- Emission contribution for continuous phase virtual tmp<volScalarField> EDisp(const label bandI = 0) const; }; } // End namespace radiation } // End namespace CML #endif
26.73913
79
0.620163
[ "mesh", "model" ]
07287f278ecc4d7a160eb3b9d59e202e3984f889
2,205
hpp
C++
src/FreeAge/common/building_types.hpp
grst/freeage
529cfd4d7db5b4c98251caacfb383730df0bf670
[ "BSD-3-Clause" ]
2
2020-06-28T19:06:09.000Z
2020-07-01T16:31:49.000Z
src/FreeAge/common/building_types.hpp
grst/freeage
529cfd4d7db5b4c98251caacfb383730df0bf670
[ "BSD-3-Clause" ]
null
null
null
src/FreeAge/common/building_types.hpp
grst/freeage
529cfd4d7db5b4c98251caacfb383730df0bf670
[ "BSD-3-Clause" ]
1
2020-06-28T15:19:27.000Z
2020-06-28T15:19:27.000Z
// Copyright 2020 The FreeAge authors // This file is part of FreeAge, licensed under the new BSD license. // See the COPYING file in the project root for the license text. #pragma once #include <QRect> #include <QSize> #include <QString> #include "FreeAge/common/resources.hpp" /// Building types. The numbers must be sequential, starting from zero, /// since they are used to index into a std::vector of Sprite. enum class BuildingType { // Player buildings TownCenter = 0, TownCenterBack, // Not used as building, just for loading the sprite TownCenterCenter, // Not used as building, just for loading the sprite TownCenterFront, // Not used as building, just for loading the sprite TownCenterMain, // Not used as building, just for loading the sprite House, Mill, MiningCamp, LumberCamp, Dock, Barracks, Outpost, PalisadeWall, PalisadeGate, // Gaia "buildings" TreeOak, FirstTree = TreeOak, LastTree = TreeOak, ForageBush, GoldMine, StoneMine, NumBuildings }; inline bool IsTree(BuildingType type) { return type >= BuildingType::FirstTree && type <= BuildingType::LastTree; } QSize GetBuildingSize(BuildingType type); QRect GetBuildingOccupancy(BuildingType type); QString GetBuildingName(BuildingType type); double GetBuildingConstructionTime(BuildingType type); /// TODO: This needs to consider the player's civilization and researched technologies ResourceAmount GetBuildingCost(BuildingType type); /// Returns whether the given building type acts as a drop-off point for the given resource type. bool IsDropOffPointForResource(BuildingType building, ResourceType resource); /// TODO: This needs to consider the player's civilization and researched technologies u32 GetBuildingMaxHP(BuildingType type); u32 GetBuildingMeleeArmor(BuildingType type); /// Returns the max number of the given building type that the player can build. /// Returns -1 if unlimited. /// TODO: This needs to consider the player's age. /// TODO: use infinity instead of -1 ? int GetBuildingMaxInstances(BuildingType type); int GetBuildingProvidedPopulationSpace(BuildingType type); float GetBuildingLineOfSight(BuildingType type);
29.4
97
0.760091
[ "vector" ]
072c96e611c589593ca59f39eb46b403870747a6
6,458
hpp
C++
include/System/Text/EncodingHelper.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/System/Text/EncodingHelper.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/System/Text/EncodingHelper.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include <initializer_list> #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: Encoding class Encoding; } // Forward declaring namespace: System::Reflection namespace System::Reflection { // Forward declaring type: Assembly class Assembly; } // Completed forward declares // Type namespace: System.Text namespace System::Text { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.Text.EncodingHelper // [TokenAttribute] Offset: FFFFFFFF class EncodingHelper : public ::Il2CppObject { public: // Creating value type constructor for type: EncodingHelper EncodingHelper() noexcept {} // Get static field: static private System.Text.Encoding utf8EncodingWithoutMarkers static System::Text::Encoding* _get_utf8EncodingWithoutMarkers(); // Set static field: static private System.Text.Encoding utf8EncodingWithoutMarkers static void _set_utf8EncodingWithoutMarkers(System::Text::Encoding* value); // Get static field: static private readonly System.Object lockobj static ::Il2CppObject* _get_lockobj(); // Set static field: static private readonly System.Object lockobj static void _set_lockobj(::Il2CppObject* value); // Get static field: static private System.Reflection.Assembly i18nAssembly static System::Reflection::Assembly* _get_i18nAssembly(); // Set static field: static private System.Reflection.Assembly i18nAssembly static void _set_i18nAssembly(System::Reflection::Assembly* value); // Get static field: static private System.Boolean i18nDisabled static bool _get_i18nDisabled(); // Set static field: static private System.Boolean i18nDisabled static void _set_i18nDisabled(bool value); // static System.Text.Encoding get_UTF8Unmarked() // Offset: 0x1D71310 static System::Text::Encoding* get_UTF8Unmarked(); // static private System.Void .cctor() // Offset: 0x1D7154C static void _cctor(); // static System.String InternalCodePage(ref System.Int32 code_page) // Offset: 0x1D71548 static ::Il2CppString* InternalCodePage(ByRef<int> code_page); // static System.Text.Encoding GetDefaultEncoding() // Offset: 0x1D6FA68 static System::Text::Encoding* GetDefaultEncoding(); // static System.Object InvokeI18N(System.String name, params System.Object[] args) // Offset: 0x1D6DF88 static ::Il2CppObject* InvokeI18N(::Il2CppString* name, ::Array<::Il2CppObject*>* args); // Creating initializer_list -> params proxy for: System.Object InvokeI18N(System.String name, params System.Object[] args) static ::Il2CppObject* InvokeI18N(::Il2CppString* name, std::initializer_list<::Il2CppObject*> args); // Creating TArgs -> initializer_list proxy for: System.Object InvokeI18N(System.String name, params System.Object[] args) template<class ...TParams> static ::Il2CppObject* InvokeI18N(::Il2CppString* name, TParams&&... args) { return InvokeI18N(name, {args...}); } }; // System.Text.EncodingHelper #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::Text::EncodingHelper*, "System.Text", "EncodingHelper"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Text::EncodingHelper::get_UTF8Unmarked // Il2CppName: get_UTF8Unmarked template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Text::Encoding* (*)()>(&System::Text::EncodingHelper::get_UTF8Unmarked)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Text::EncodingHelper*), "get_UTF8Unmarked", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Text::EncodingHelper::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::Text::EncodingHelper::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Text::EncodingHelper*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Text::EncodingHelper::InternalCodePage // Il2CppName: InternalCodePage template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (*)(ByRef<int>)>(&System::Text::EncodingHelper::InternalCodePage)> { static const MethodInfo* get() { static auto* code_page = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::EncodingHelper*), "InternalCodePage", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{code_page}); } }; // Writing MetadataGetter for method: System::Text::EncodingHelper::GetDefaultEncoding // Il2CppName: GetDefaultEncoding template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Text::Encoding* (*)()>(&System::Text::EncodingHelper::GetDefaultEncoding)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Text::EncodingHelper*), "GetDefaultEncoding", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Text::EncodingHelper::InvokeI18N // Il2CppName: InvokeI18N template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (*)(::Il2CppString*, ::Array<::Il2CppObject*>*)>(&System::Text::EncodingHelper::InvokeI18N)> { static const MethodInfo* get() { static auto* name = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* args = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Object"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::EncodingHelper*), "InvokeI18N", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{name, args}); } };
54.268908
180
0.72205
[ "object", "vector" ]
072df7e34eabefbe09f7cc79301785d183f5f498
2,634
cc
C++
remoting/host/chromeos/remote_support_host_ash.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
remoting/host/chromeos/remote_support_host_ash.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
remoting/host/chromeos/remote_support_host_ash.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/chromeos/remote_support_host_ash.h" #include <utility> #include <stddef.h> #include "base/notreached.h" #include "base/strings/stringize_macros.h" #include "remoting/host/chromeos/remoting_service.h" #include "remoting/host/chromoting_host_context.h" #include "remoting/host/it2me/it2me_constants.h" #include "remoting/host/it2me/it2me_native_messaging_host_ash.h" #include "remoting/host/policy_watcher.h" namespace remoting { RemoteSupportHostAsh::RemoteSupportHostAsh(base::OnceClosure cleanup_callback) : cleanup_callback_(std::move(cleanup_callback)) {} RemoteSupportHostAsh::~RemoteSupportHostAsh() = default; void RemoteSupportHostAsh::StartSession( mojom::SupportSessionParamsPtr params, const absl::optional<ChromeOsEnterpriseParams>& enterprise_params, StartSessionCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Ensure there is at most one active remote support connection. // Since we are initiating the disconnect, don't run the cleanup callback. if (it2me_native_message_host_ash_) { auto temp = std::move(it2me_native_message_host_ash_); temp->Disconnect(); } it2me_native_message_host_ash_ = std::make_unique<It2MeNativeMessageHostAsh>(); mojo::PendingReceiver<mojom::SupportHostObserver> pending_receiver = it2me_native_message_host_ash_->Start( RemotingService::Get().CreateHostContext(), RemotingService::Get().CreatePolicyWatcher()); mojom::StartSupportSessionResponsePtr response = mojom::StartSupportSessionResponse::New(); response->set_observer(std::move(pending_receiver)); it2me_native_message_host_ash_->Connect( std::move(params), enterprise_params, base::BindOnce(std::move(callback), std::move(response)), base::BindOnce(&RemoteSupportHostAsh::OnSessionDisconnected, base::Unretained(this))); } // static mojom::SupportHostDetailsPtr RemoteSupportHostAsh::GetHostDetails() { return mojom::SupportHostDetails::New( STRINGIZE(VERSION), std::vector<std::string>({kFeatureAccessTokenAuth})); } void RemoteSupportHostAsh::OnSessionDisconnected() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (it2me_native_message_host_ash_) { // Do not access any instance members after |cleanup_callback_| is run as // this instance will be destroyed by running this. std::move(cleanup_callback_).Run(); } } } // namespace remoting
35.594595
79
0.764996
[ "vector" ]
072ee87e467d6c234d1b7070376981b30014906e
13,495
cc
C++
CondTools/Ecal/src/EcalTPGLutGroupHandler.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
2
2017-09-29T13:32:51.000Z
2019-01-31T00:40:58.000Z
CondTools/Ecal/src/EcalTPGLutGroupHandler.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
7
2016-07-17T02:34:54.000Z
2019-08-13T07:58:37.000Z
CondTools/Ecal/src/EcalTPGLutGroupHandler.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
3
2017-06-07T15:22:28.000Z
2019-02-28T20:48:30.000Z
#include "CondTools/Ecal/interface/EcalTPGLutGroupHandler.h" #include "OnlineDB/EcalCondDB/interface/EcalLogicID.h" #include "OnlineDB/EcalCondDB/interface/RunTPGConfigDat.h" #include "OnlineDB/EcalCondDB/interface/FEConfigMainInfo.h" #include "OnlineDB/EcalCondDB/interface/FEConfigLUTInfo.h" #include "OnlineDB/EcalCondDB/interface/FEConfigLUTDat.h" #include "FWCore/ParameterSet/interface/ParameterSetfwd.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "CondFormats/EcalObjects/interface/EcalTPGLutGroup.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h" #include "Geometry/CaloGeometry/interface/CaloCellGeometry.h" #include "Geometry/Records/interface/CaloGeometryRecord.h" #include "Geometry/EcalMapping/interface/EcalElectronicsMapping.h" #include "Geometry/EcalMapping/interface/EcalMappingRcd.h" #include "DataFormats/EcalDetId/interface/EcalSubdetector.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "DataFormats/EcalDetId/interface/EcalTrigTowerDetId.h" #include <iostream> #include <fstream> #include <ctime> #include <unistd.h> #include <string> #include <cstdio> #include <typeinfo> #include <sstream> popcon::EcalTPGLutGroupHandler::EcalTPGLutGroupHandler(const edm::ParameterSet &ps) : m_name(ps.getUntrackedParameter<std::string>("name", "EcalTPGLutGroupHandler")) { edm::LogInfo("EcalTPGLutGroupHandler") << "EcalTPGLutGroup Source handler constructor"; m_firstRun = static_cast<unsigned int>(atoi(ps.getParameter<std::string>("firstRun").c_str())); m_lastRun = static_cast<unsigned int>(atoi(ps.getParameter<std::string>("lastRun").c_str())); m_sid = ps.getParameter<std::string>("OnlineDBSID"); m_user = ps.getParameter<std::string>("OnlineDBUser"); m_pass = ps.getParameter<std::string>("OnlineDBPassword"); m_locationsource = ps.getParameter<std::string>("LocationSource"); m_location = ps.getParameter<std::string>("Location"); m_gentag = ps.getParameter<std::string>("GenTag"); m_runtype = ps.getParameter<std::string>("RunType"); edm::LogInfo("EcalTPGLutGroupHandler") << m_sid << "/" << m_user << "/" << m_location << "/" << m_gentag; } popcon::EcalTPGLutGroupHandler::~EcalTPGLutGroupHandler() {} void popcon::EcalTPGLutGroupHandler::getNewObjects() { using namespace edm; using namespace std; edm::LogInfo("EcalTPGLutGroupHandler") << "Started GetNewObjects!!!"; /* // geometry ESHandle<CaloGeometry> theGeometry; ESHandle<CaloSubdetectorGeometry> theEndcapGeometry_handle, theBarrelGeometry_handle; evtSetup.get<CaloGeometryRecord>().get( theGeometry ); evtSetup.get<EcalEndcapGeometryRecord>().get("EcalEndcap",theEndcapGeometry_handle); evtSetup.get<EcalBarrelGeometryRecord>().get("EcalBarrel",theBarrelGeometry_handle); evtSetup.get<IdealGeometryRecord>().get(eTTmap_); theEndcapGeometry_ = &(*theEndcapGeometry_handle); theBarrelGeometry_ = &(*theBarrelGeometry_handle); // electronics mapping ESHandle< EcalElectronicsMapping > ecalmapping; evtSetup.get< EcalMappingRcd >().get(ecalmapping); theMapping_ = ecalmapping.product(); const std::vector<DetId> & eeCells = theEndcapGeometry_->getValidDetIds(DetId::Ecal, EcalEndcap); */ //check whats already inside of database if (tagInfo().size) { //check whats already inside of database std::cout << "got offlineInfo = " << std::endl; std::cout << "tag name = " << tagInfo().name << std::endl; std::cout << "size = " << tagInfo().size << std::endl; } else { std::cout << " First object for this tag " << std::endl; } unsigned int max_since = 0; max_since = static_cast<unsigned int>(tagInfo().lastInterval.first); edm::LogInfo("EcalTPGLutGroupHandler") << "max_since : " << max_since; edm::LogInfo("EcalTPGLutGroupHandler") << "retrieved last payload "; // here we retrieve all the runs after the last from online DB edm::LogInfo("EcalTPGLutGroupHandler") << "Retrieving run list from ONLINE DB ... "; edm::LogInfo("EcalTPGLutGroupHandler") << "Making connection..."; econn = new EcalCondDBInterface(m_sid, m_user, m_pass); edm::LogInfo("EcalTPGLutGroupHandler") << "Done."; if (!econn) { std::cout << " connection parameters " << m_sid << "/" << m_user << std::endl; // cerr << e.what() << std::endl; throw cms::Exception("OMDS not available"); } LocationDef my_locdef; my_locdef.setLocation(m_location); RunTypeDef my_rundef; my_rundef.setRunType(m_runtype); RunTag my_runtag; my_runtag.setLocationDef(my_locdef); my_runtag.setRunTypeDef(my_rundef); my_runtag.setGeneralTag(m_gentag); readFromFile("last_tpg_lutGroup_settings.txt"); unsigned int min_run = m_i_run_number + 1; if (m_firstRun < m_i_run_number) { min_run = m_i_run_number + 1; } else { min_run = m_firstRun; } if (min_run < max_since) { min_run = max_since + 1; // we have to add 1 to the last transferred one } std::cout << "m_i_run_number" << m_i_run_number << "m_firstRun " << m_firstRun << "max_since " << max_since << std::endl; unsigned int max_run = m_lastRun; edm::LogInfo("EcalTPGLutGroupHandler") << "min_run= " << min_run << " max_run= " << max_run; RunList my_list; my_list = econn->fetchGlobalRunListByLocation(my_runtag, min_run, max_run, my_locdef); // my_list=econn->fetchRunListByLocation(my_runtag,min_run,max_run,my_locdef); std::vector<RunIOV> run_vec = my_list.getRuns(); size_t num_runs = run_vec.size(); std::cout << "number of runs is : " << num_runs << std::endl; std::string str = ""; unsigned int irun; if (num_runs > 0) { // going to query the ecal logic id std::vector<EcalLogicID> my_TTEcalLogicId_EE; my_TTEcalLogicId_EE = econn->getEcalLogicIDSetOrdered( "EE_trigger_tower", 1, 200, 1, 70, EcalLogicID::NULLID, EcalLogicID::NULLID, "EE_offline_towerid", 12); std::cout << " GOT the logic ID for the EE trigger towers " << std::endl; for (size_t kr = 0; kr < run_vec.size(); kr++) { irun = static_cast<unsigned int>(run_vec[kr].getRunNumber()); std::cout << " **************** " << std::endl; std::cout << " run= " << irun << std::endl; // retrieve the data : std::map<EcalLogicID, RunTPGConfigDat> dataset; econn->fetchDataSet(&dataset, &run_vec[kr]); std::string the_config_tag = ""; int the_config_version = 0; std::map<EcalLogicID, RunTPGConfigDat>::const_iterator it; int nr = 0; for (it = dataset.begin(); it != dataset.end(); it++) { ++nr; //EcalLogicID ecalid = it->first; RunTPGConfigDat dat = it->second; the_config_tag = dat.getConfigTag(); the_config_version = dat.getVersion(); } // it is all the same for all SM... get the last one std::cout << " run= " << irun << " tag " << the_config_tag << " version=" << the_config_version << std::endl; // here we should check if it is the same as previous run. if ((the_config_tag != m_i_tag || the_config_version != m_i_version) && nr > 0) { std::cout << "the tag is different from last transferred run ... retrieving last config set from DB" << std::endl; FEConfigMainInfo fe_main_info; fe_main_info.setConfigTag(the_config_tag); fe_main_info.setVersion(the_config_version); try { std::cout << " before fetch config set" << std::endl; econn->fetchConfigSet(&fe_main_info); std::cout << " after fetch config set" << std::endl; // now get TPGLutGroup int lutId = fe_main_info.getLUTId(); if (lutId != m_i_lutGroup) { FEConfigLUTInfo fe_lut_info; fe_lut_info.setId(lutId); econn->fetchConfigSet(&fe_lut_info); std::map<EcalLogicID, FEConfigLUTDat> dataset_TpgLut; econn->fetchDataSet(&dataset_TpgLut, &fe_lut_info); EcalTPGLutGroup *lut = new EcalTPGLutGroup(); typedef std::map<EcalLogicID, FEConfigLUTDat>::const_iterator CIfelut; EcalLogicID ecid_xt; FEConfigLUTDat rd_lut; int itowers = 0; for (CIfelut p = dataset_TpgLut.begin(); p != dataset_TpgLut.end(); p++) { ecid_xt = p->first; rd_lut = p->second; std::string ecid_name = ecid_xt.getName(); if (ecid_name == "EB_trigger_tower") { // SM number int smid = ecid_xt.getID1(); // TT number int towerid = ecid_xt.getID2(); int tow_eta = (towerid - 1) / 4; int tow_phi = ((towerid - 1) - tow_eta * 4); int axt = (tow_eta * 5) * 20 + tow_phi * 5 + 1; EBDetId id(smid, axt, EBDetId::SMCRYSTALMODE); const EcalTrigTowerDetId towid = id.tower(); /* char ch[10]; sprintf(ch,"%d%d", smid, towerid); std::string S=""; S.insert(0,ch); unsigned int towerEBId = 0; towerEBId = atoi(S.c_str()); */ lut->setValue(towid.rawId(), rd_lut.getLUTGroupId()); ++itowers; } else if (ecid_name == "EE_trigger_tower") { // EE data // TCC number int tccid = ecid_xt.getID1(); // TT number int towerid = ecid_xt.getID2(); bool set_the_tower = false; int towid; for (size_t itower = 0; itower < my_TTEcalLogicId_EE.size(); itower++) { if (!set_the_tower) { if (my_TTEcalLogicId_EE[itower].getID1() == tccid && my_TTEcalLogicId_EE[itower].getID2() == towerid) { towid = my_TTEcalLogicId_EE[itower].getLogicID(); set_the_tower = true; break; } } } if (set_the_tower) { lut->setValue(towid, rd_lut.getLUTGroupId()); } else { std::cout << " these may be the additional towers TCC/TT " << tccid << "/" << towerid << std::endl; } ++itowers; } } Time_t snc = (Time_t)irun; m_to_transfer.push_back(std::make_pair((EcalTPGLutGroup *)lut, snc)); m_i_run_number = irun; m_i_tag = the_config_tag; m_i_version = the_config_version; m_i_lutGroup = lutId; writeFile("last_tpg_lutGroup_settings.txt"); } else { m_i_run_number = irun; m_i_tag = the_config_tag; m_i_version = the_config_version; writeFile("last_tpg_lutGroup_settings.txt"); std::cout << " even if the tag/version is not the same, the lutGroup id is the same -> no transfer needed " << std::endl; } } catch (std::exception &e) { std::cout << "ERROR: THIS CONFIG DOES NOT EXIST: tag=" << the_config_tag << " version=" << the_config_version << std::endl; std::cout << e.what() << std::endl; m_i_run_number = irun; } std::cout << " **************** " << std::endl; } else if (nr == 0) { m_i_run_number = irun; std::cout << " no tag saved to RUN_TPGCONFIG_DAT by EcalSupervisor -> no transfer needed " << std::endl; std::cout << " **************** " << std::endl; } else { m_i_run_number = irun; m_i_tag = the_config_tag; m_i_version = the_config_version; std::cout << " the tag/version is the same -> no transfer needed " << std::endl; std::cout << " **************** " << std::endl; writeFile("last_tpg_lutGroup_settings.txt"); } } } delete econn; edm::LogInfo("EcalTPGLutGroupHandler") << "Ecal - > end of getNewObjects -----------"; } void popcon::EcalTPGLutGroupHandler::readFromFile(const char *inputFile) { //------------------------------------------------------------- m_i_tag = ""; m_i_version = 0; m_i_run_number = 0; m_i_lutGroup = 0; FILE *inpFile; // input file inpFile = fopen(inputFile, "r"); if (!inpFile) { edm::LogError("EcalTPGLutGroupHandler") << "*** Can not open file: " << inputFile; return; } char line[256]; std::ostringstream str; fgets(line, 255, inpFile); m_i_tag = to_string(line); str << "gen tag " << m_i_tag << std::endl; // should I use this? fgets(line, 255, inpFile); m_i_version = atoi(line); str << "version= " << m_i_version << std::endl; fgets(line, 255, inpFile); m_i_run_number = atoi(line); str << "run_number= " << m_i_run_number << std::endl; fgets(line, 255, inpFile); m_i_lutGroup = atoi(line); str << "lutGroup_config= " << m_i_lutGroup << std::endl; fclose(inpFile); // close inp. file } void popcon::EcalTPGLutGroupHandler::writeFile(const char *inputFile) { //------------------------------------------------------------- std::ofstream myfile; myfile.open(inputFile); myfile << m_i_tag << std::endl; myfile << m_i_version << std::endl; myfile << m_i_run_number << std::endl; myfile << m_i_lutGroup << std::endl; myfile.close(); }
35.234987
119
0.616376
[ "geometry", "object", "vector" ]
0733834702af8da8aa2a841bf981651b511d63e1
651
cpp
C++
8/835. Image Overlap.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
null
null
null
8/835. Image Overlap.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
1
2021-12-25T10:33:23.000Z
2022-02-16T00:34:05.000Z
8/835. Image Overlap.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
null
null
null
class Solution { public: int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) { int n = A.size(), offset = (n << 1) - 1; vector<int> vA, vB, count(offset * offset); for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) { if(A[i][j]) vA.emplace_back(i * offset + j); if(B[i][j]) vB.emplace_back(i * offset + j); } offset = (n - 1) * (offset + 1); for(int a : vA) for(int b : vB) ++count[a - b + offset]; return *max_element(count.begin(), count.end()); } };
32.55
72
0.419355
[ "vector" ]
0734045feaec70e4c952c34b217236611d63c27b
2,503
hpp
C++
lib/rendering/rendering.hpp
aditya2592/PoseCNN
a763120ce0ceb55cf3432980287ef463728f8052
[ "MIT" ]
655
2018-03-21T19:55:45.000Z
2022-03-25T20:41:21.000Z
lib/rendering/rendering.hpp
SergioRAgostinho/PoseCNN
da9eaae850eed7521a2a48a4d27474d655caab42
[ "MIT" ]
122
2018-04-04T13:57:49.000Z
2022-03-18T09:28:44.000Z
lib/rendering/rendering.hpp
SergioRAgostinho/PoseCNN
da9eaae850eed7521a2a48a4d27474d655caab42
[ "MIT" ]
226
2018-03-22T01:40:04.000Z
2022-03-17T11:56:14.000Z
#include <stdio.h> #include <cfloat> #include <math.h> #include <vector> #include <ctime> #include <cstdlib> #include <unistd.h> #include <iostream> #include <fstream> #include <string> #include <cstddef> #include "opencv2/opencv.hpp" #define GL_GLEXT_PROTOTYPES #include "GL/gl.h" #include "GL/glext.h" #include "GL/osmesa.h" #include <cuda_runtime.h> #include <Eigen/Core> #include <Eigen/Geometry> #include <sophus/se3.hpp> #include <assimp/cimport.h> #include <assimp/scene.h> template <typename Derived> inline void operator >>(std::istream & stream, Eigen::MatrixBase<Derived> & M) { for (int r = 0; r < M.rows(); ++r) { for (int c = 0; c < M.cols(); ++c) { stream >> M(r,c); } } } template<typename P> inline void OpenGlMatrix(const Eigen::Matrix<P,4,4>& mat, float* m) { for(int r=0; r<4; ++r ) { for(int c=0; c<4; ++c ) { m[c*4+r] = mat(r,c); } } } unsigned char class_colors[22][3] = {{255, 255, 255}, {255, 0, 0}, {0, 255, 0}, {0, 0, 255}, {255, 255, 0}, {255, 0, 255}, {0, 255, 255}, {128, 0, 0}, {0, 128, 0}, {0, 0, 128}, {128, 128, 0}, {128, 0, 128}, {0, 128, 128}, {64, 0, 0}, {0, 64, 0}, {0, 0, 64}, {64, 64, 0}, {64, 0, 64}, {0, 64, 64}, {192, 0, 0}, {0, 192, 0}, {0, 0, 192}}; typedef struct { int num_vertices; int num_faces; void* vertices; void* faces; }MyModel; class Render { public: Render() {}; Render(std::string model_file); ~Render(); void setup(std::string model_file); float render(const float* data, const int* labels, const float* rois, int num_rois, int num_gt, int num_classes, int width, int height, const float* poses_gt, const float* poses_pred, const float* poses_init, float* bottom_diff, const float* meta_data, int num_meta_data); void loadModels(const std::string filename); void loadTexturedMesh(const std::string filename, std::string & texture_name, MyModel* model); void initializeBuffers(MyModel* model, std::string textureName, GLuint vertexbuffer, GLuint indexbuffer); void ProjectionMatrixRDF_TopLeft(float* m, int w, int h, float fu, float fv, float u0, float v0, float zNear, float zFar ); void write_ppm(const char *filename, const GLubyte *buffer, int width, int height); void print_matrix(float *m); private: int counter_; // 3D models std::vector<MyModel*> models_; std::vector<std::string> texture_names_; };
28.123596
151
0.616061
[ "geometry", "render", "vector", "model", "3d" ]
074152fe325682be4bb457dd1475f38ee006e1f9
1,127
cpp
C++
src/process.cpp
ajaxuk/CppND-System-Monitor
6edb50654b4ada814f6595f1eac277da3ce572b4
[ "MIT" ]
1
2021-11-01T08:52:45.000Z
2021-11-01T08:52:45.000Z
src/process.cpp
ajaxuk/CppND-System-Monitor
6edb50654b4ada814f6595f1eac277da3ce572b4
[ "MIT" ]
null
null
null
src/process.cpp
ajaxuk/CppND-System-Monitor
6edb50654b4ada814f6595f1eac277da3ce572b4
[ "MIT" ]
null
null
null
#include "process.h" #include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> using std::string; using std::to_string; using std::vector; // TODO: Return this process's ID int Process::Pid() const { return pid_; } string Process::User() const { return user_; } float Process::CpuUtilization() const { return cpuutilization_; } string Process::Ram() const { return ram_; } std::string Process::Command() const { return command_; } long int Process::UpTime() const { return uptime_; } void Process::Command(std::string command) { command_ = command; } void Process::UpTime(long int uptime) { uptime_ = uptime; }; void Process::Pid(int pid) { pid_ = pid; } void Process::User(std::string user) { user_ = user; } void Process::CpuUtilization(float cpuutilization) { cpuutilization_ = cpuutilization; } void Process::Ram(std::string ram) { ram_ = ram; } // DONE: Overload the "less than" comparison operator for Process objects // REMOVE: [[maybe_unused]] once you define the function bool Process::operator<(Process const& a) const { return this->cpuutilization_ < a.cpuutilization_; }
32.2
73
0.723159
[ "vector" ]
0748215cee3e20196bf155dff7a4da2077a2f699
3,422
cpp
C++
SortingHugeFile.cpp
Kuzame/SortingHugeFile
d20a3412c12660eb361165310461fd04bbbb38cc
[ "Apache-2.0" ]
null
null
null
SortingHugeFile.cpp
Kuzame/SortingHugeFile
d20a3412c12660eb361165310461fd04bbbb38cc
[ "Apache-2.0" ]
null
null
null
SortingHugeFile.cpp
Kuzame/SortingHugeFile
d20a3412c12660eb361165310461fd04bbbb38cc
[ "Apache-2.0" ]
null
null
null
//============================================================================ // Name : SortingHugeFile.cpp // Author : Adrian Harminto // Comparing library sort (stable_sort) vs manually written sort //============================================================================ #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <ctime> #include "Student.cpp" using namespace std; Student* readStudentsFromFile(string filename, int num) { ifstream studentsStream; studentsStream.open(filename.c_str()); if (!studentsStream.is_open()) { cerr << "Couldn't open the file " << filename << endl; return NULL; } Student* students = new Student[num]; string name, school, sid; int id; for (int i = 0; i < num; i++) { getline(studentsStream, name, ','); getline(studentsStream, sid, ','); getline(studentsStream, school); istringstream idConv(sid); idConv >> id; students[i] = Student(id, name, school); } studentsStream.close(); return students; } void writeStudentsToFile(Student students[], int num, string filename) { ofstream output(filename.c_str()); for (int i = 0; i < num; i++) { output << students[i].toString(); if (i < num - 1) { output << endl; } } output.close(); } bool compareBySchoolName(Student s1, Student s2) { return s1.getSchool()<s2.getSchool(); } void sortByGroupById1(Student students[], int len) { stable_sort(students, students+len, compareBySchoolName); } int schoolToIndex(string school) { if (school == "UCB") return 0; if (school == "UCD") return 1; if (school == "UCI") return 2; if (school == "UCLA") return 3; if (school == "UCM") return 4; if (school == "UCSD") return 5; if (school == "UCSF") return 6; cerr << "Unknown school " << school << endl; return -1; } void sortByGroupById2(Student students[], int len) { int temp [7]={0}, //for counting schools temp2 [7]={0}; //for index of each schools Student *tempStudent = new Student[len]; for (int i =0; i<len; i++) { //counting how many students per school inside temp temp[schoolToIndex(students[i].getSchool())]++; } for (int i=0; i<7; i++) { //putting initial position to assign/put student on each school for (int j=0; j<i;j++) { //this is k^2, but k is for schools. Regard to n (students), this is still a constant time temp2[i]+=temp[j]; } } for (int i = 0; i<len; i++) { //now use that position recorded in temp2 (int) to fetch student, & copy it to tempStudent tempStudent[temp2[schoolToIndex(students[i].getSchool())]++] = students[i]; } for (int i=0;i<len;i++) { //copy-pasting tempStudent to the original students[i]=tempStudent[i]; } delete [] tempStudent; //free-ing object } int main() { const int LEN = 350000; time_t start, end; Student* uc1 = readStudentsFromFile("uc_students_sorted_by_id", LEN); time(&start); sortByGroupById1(uc1, LEN); time(&end); cout << "Using library sort it took " << difftime(end, start) << " seconds." << endl; Student* uc2 = readStudentsFromFile("uc_students_sorted_by_id", LEN); time(&start); sortByGroupById2(uc2, LEN); time(&end); cout << "Using counting sort it took " << difftime(end, start) << " seconds." << endl; writeStudentsToFile(uc1, LEN, "uc_by_school_by_id1.txt"); writeStudentsToFile(uc2, LEN, "uc_by_school_by_id2.txt"); return 0; }
29
124
0.624489
[ "object" ]
07499538c6238d1fb64a92a2999e624014da9893
2,605
cpp
C++
third_party/WebKit/Source/platform/bindings/V8ObjectConstructor.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/platform/bindings/V8ObjectConstructor.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/platform/bindings/V8ObjectConstructor.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2012 Google 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 "platform/bindings/V8ObjectConstructor.h" #include "platform/bindings/RuntimeCallStats.h" #include "platform/bindings/V8Binding.h" #include "platform/bindings/V8ThrowException.h" #include "platform/instrumentation/tracing/TraceEvent.h" namespace blink { v8::MaybeLocal<v8::Object> V8ObjectConstructor::NewInstance( v8::Isolate* isolate, v8::Local<v8::Function> function, int argc, v8::Local<v8::Value> argv[]) { DCHECK(!function.IsEmpty()); TRACE_EVENT0("v8", "v8.newInstance"); RUNTIME_CALL_TIMER_SCOPE(isolate, RuntimeCallStats::CounterId::kV8); ConstructorMode constructor_mode(isolate); v8::MicrotasksScope microtasks_scope( isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::MaybeLocal<v8::Object> result = function->NewInstance(isolate->GetCurrentContext(), argc, argv); CHECK(!isolate->IsDead()); return result; } void V8ObjectConstructor::IsValidConstructorMode( const v8::FunctionCallbackInfo<v8::Value>& info) { if (ConstructorMode::Current(info.GetIsolate()) == ConstructorMode::kCreateNewObject) { V8ThrowException::ThrowTypeError(info.GetIsolate(), "Illegal constructor"); return; } V8SetReturnValue(info, info.Holder()); } } // namespace blink
42.016129
80
0.753551
[ "object" ]
074e5fc2c6d8314b173293d6afc3601d84902add
5,866
cpp
C++
ogles_gpgpu/common/proc/base/procinterface.cpp
hunter-packages/ogles_gpgpu
ada7029481ddf9e4d001b191e86d712e9d8839f7
[ "Apache-2.0" ]
7
2017-05-19T17:41:38.000Z
2018-10-31T09:35:20.000Z
ogles_gpgpu/common/proc/base/procinterface.cpp
hunter-packages/ogles_gpgpu
ada7029481ddf9e4d001b191e86d712e9d8839f7
[ "Apache-2.0" ]
20
2017-07-09T21:03:37.000Z
2018-04-27T02:02:35.000Z
ogles_gpgpu/common/proc/base/procinterface.cpp
hunter-packages/ogles_gpgpu
ada7029481ddf9e4d001b191e86d712e9d8839f7
[ "Apache-2.0" ]
6
2016-07-09T13:06:38.000Z
2021-07-01T07:43:48.000Z
#include "procinterface.h" using namespace ogles_gpgpu; // ########## Filter chain void ProcInterface::setOutputPboCount(int count) { outputPboCount = count; } void ProcInterface::setPreProcessCallback(const ProcDelegate& cb) { m_preProcessCallback = cb; } void ProcInterface::setPostProcessCallback(const ProcDelegate& cb) { m_postProcessCallback = cb; } void ProcInterface::setPreRenderCallback(const ProcDelegate& cb) { m_preRenderCallback = cb; } void ProcInterface::setPostRenderCallback(const ProcDelegate& cb) { m_postRenderCallback = cb; } void ProcInterface::setPreInitCallback(const ProcDelegate& cb) { m_preInitCallback = cb; } void ProcInterface::setPostInitCallback(const ProcDelegate& cb) { m_postInitCallback = cb; } std::string ProcInterface::getFilterTag() { std::stringstream ss; ss << "[" << getOutputTexId() << "] " << getProcName() << " : " << getOutFrameW() << "x" << getOutFrameH(); return ss.str(); } void ProcInterface::setActive(bool state) { active = state; } void ProcInterface::add(ProcInterface* filter, int position) { subscribers.emplace_back(filter, position); } // Top level recursive filter chain processing, set input texture for first filter as needed void ProcInterface::process(GLuint id, GLuint useTexUnit, GLenum target, int index, int position, Logger logger) { if (!active) { return; } if (m_preProcessCallback) { m_preProcessCallback(this); } if (logger) logger(getFilterTag() + " begin"); if (m_preRenderCallback) { m_preRenderCallback(this); } if (index == 0) { // set input texture id useTexture(id, useTexUnit, target, position); Tools::checkGLErr(getProcName(), "useTexture"); } int result = render(position); if (m_postRenderCallback) { m_postRenderCallback(this); } if (logger) logger(getFilterTag() + " end"); if (result == 0) { for (auto& subscriber : subscribers) { subscriber.first->useTexture(getOutputTexId(), getTextureUnit(), GL_TEXTURE_2D, subscriber.second); subscriber.first->process(subscriber.second, logger); } } if (m_postProcessCallback) { m_postProcessCallback(this); } } // Recursive helper method for process() where index >= 1 void ProcInterface::process(int position, Logger logger) { if (m_preProcessCallback) { m_preProcessCallback(this); } if (logger) logger(getFilterTag() + " begin"); if (m_preRenderCallback) { m_preRenderCallback(this); } int result = render(position); if (m_postRenderCallback) { m_postRenderCallback(this); } if (logger) logger(getFilterTag() + " end"); if (result == 0) { // Only trigger subscribers 1x (non active render() should return non-zero error code) for (auto& subscriber : subscribers) { // Update: FIFO and other filters may change the output texture id on each step: subscriber.first->useTexture(getOutputTexId(), getTextureUnit(), GL_TEXTURE_2D, subscriber.second); subscriber.first->process(subscriber.second, logger); } } if (m_postProcessCallback) { m_postProcessCallback(this); } } #define DO_MIPMAP_TEST 0 // Top level filter chain preparation, set input format for first filter void ProcInterface::prepare(int inW, int inH, GLenum inFmt, int index, int position) { if (index == 0) { setExternalInputDataFormat(inFmt); } // In case of multi-input textures, only (re)init for the first one if (position == 0) { if (m_preInitCallback) { m_preInitCallback(this); } if ((getInFrameW() == 0) && (getInFrameH() == 0)) { init(inW, inH, index, (index == 0) && (inFmt != GL_NONE)); } else { reinit(inW, inH, (index == 0) && (inFmt != GL_NONE)); } if (m_postInitCallback) { m_postInitCallback(this); } bool willDownScale = false; #if DO_MIPMAP_TEST if (subscribers.size() != 0) { for (auto& subscriber : subscribers) { willDownScale |= subscriber.first->getWillDownscale(); } } #endif // Create FBO for out single output texture createFBOTex(useMipmaps && willDownScale); // last one is false for (auto& subscriber : subscribers) { subscriber.first->prepare(getOutFrameW(), getOutFrameH(), index + 1, subscriber.second); subscriber.first->useTexture(getOutputTexId(), getTextureUnit(), GL_TEXTURE_2D, subscriber.second); } } } // Recursive helper method for prepare() where index >= 1 void ProcInterface::prepare(int inW, int inH, int index, int position) { if (position == 0) { if (m_preInitCallback) { m_preInitCallback(this); } if ((getInFrameW() == 0) && (getInFrameH() == 0)) { init(inW, inH, index, false); } else { reinit(inW, inH, false); } if (m_postInitCallback) { m_postInitCallback(this); } bool willDownScale = false; #if DO_MIPMAP_TEST if (subscribers.size() != 0) { for (auto& subscriber : subscribers) { willDownScale |= subscriber.first->getWillDownscale(); } } #endif // Create FBO for out single output texture createFBOTex(useMipmaps && willDownScale); // last one is false for (auto& subscriber : subscribers) { subscriber.first->prepare(getOutFrameW(), getOutFrameH(), index + 1, subscriber.second); subscriber.first->useTexture(getOutputTexId(), getTextureUnit(), GL_TEXTURE_2D, subscriber.second); } } }
27.411215
114
0.622059
[ "render" ]
075c62b13cd3f02abc472889b3e232e5c1375994
6,159
hh
C++
src/basepipeline.hh
aaszodi/multovl
00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8
[ "MIT" ]
2
2018-03-06T02:36:25.000Z
2020-01-13T10:55:35.000Z
src/basepipeline.hh
aaszodi/multovl
00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8
[ "MIT" ]
null
null
null
src/basepipeline.hh
aaszodi/multovl
00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8
[ "MIT" ]
null
null
null
/* <LICENSE> License for the MULTOVL multiple genomic overlap tools Copyright (c) 2007-2012, Dr Andras Aszodi, Campus Science Support Facilities GmbH (CSF), Dr-Bohr-Gasse 3, A-1030 Vienna, Austria, Europe. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Campus Science Support Facilities GmbH nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </LICENSE> */ #ifndef MULTOVL_BASEPIPELINE_HEADER #define MULTOVL_BASEPIPELINE_HEADER // == Header basepipeline.hh == /// \file Base class for multiple overlap "pipelines". /// \date 2012-02-27 /// \author Andras Aszodi // -- Own headers -- #include "errors.hh" // -- Boost headers -- #include "boost/noncopyable.hpp" // -- Standard headers -- #include <string> namespace multovl { /// Fwd declaration for command-line option processing class MultovlOptbase; // -- Classes -- /// Abstract class that provides a framework for detecting multiple overlaps. /// Running a Multovl program involves the following steps: read input, do the work, write output. /// The Pipeline subclasses implement variations on this theme, such as reading from files vs databases, /// running the Multovl algorithm on one CPU or in parallel, estimating the probabilities of random overlaps etc. /// The BasePipeline class lays the foundation by providing a means of storing input track metadata, /// error handling and a run() method with optional timing information. class BasePipeline: private boost::noncopyable { public: /// Default init of a BasePipeline object. BasePipeline(): _optpimpl(NULL), // derived classes allocate this _inputs(), _errors() {} /// Go through the whole analysis. /// \return true on success, false if something went wrong. bool run(); /// \return const access to the internal error/warning object. const Errors& errors() const { return _errors; } virtual ~BasePipeline() {} /// The Input structure stores the name of the input (a filename /// or track name in a database), an ID assigned by Multovl, /// and the number of regions that could be read from it. struct Input { std::string name; unsigned int trackid, regcnt; explicit Input(const std::string& nm = ""): name(nm), trackid(0), regcnt(0) {} }; protected: typedef std::vector<Input> input_seq_t; /// Reads the input tracks. Pure virtual. /// \return the number of tracks successfully read, 0 on error. virtual unsigned int read_input() = 0; /// Detects the overlaps. Pure virtual. /// \return the total number of overlaps found. virtual unsigned int detect_overlaps() = 0; /// Writes the results somewhere. Pure virtual. /// Implementations must make sure each overlap region and the corresponding /// ancestry information are properly written. /// This method is not run when timing is requested. /// \return true if all went well, false on errors. virtual bool write_output() = 0; /// Sets the option handling object (invoke in ctor) but only if the pimpl was NULL. /// \param optp pointer to an appropriate option handling object instance. /// \return /true/ on success, /false/ if opt_ptr() != NULL. bool set_optpimpl(MultovlOptbase* optp); /// \return access to the option-handling pointer itself MultovlOptbase* opt_pimpl() { return _optpimpl; } /// \return access to the option-handling object. virtual MultovlOptbase* opt_ptr() = 0; /// \return const access to the input records const input_seq_t& inputs() const { return _inputs; } /// \return non-const access to the input records input_seq_t& inputs() { return _inputs; } /// Adds an error message void add_error(const std::string& prefix, const std::string& what) { _errors.add_error(prefix + ": " + what); } /// Adds the full contents of another Errors object /// \param other another Errors object to be merged void add_all_errors(const Errors& other) { _errors += other; } /// Adds a warning message void add_warning(const std::string& prefix, const std::string& what) { _errors.add_warning(prefix + ": " + what); } /// Clears the errors void clear_errors() { _errors.clear(); } private: // Each derived class will have its option-handling object // which is derived from MultovlOptbase (parallel inheritance hierarchy). // The ptr to it remains NULL in this base class. MultovlOptbase* _optpimpl; input_seq_t _inputs; ///< vector of input track descriptors Errors _errors; ///< collect error messages here }; } // namespace multovl #endif // MULTOVL_BASEPIPELINE_HEADER
35.80814
113
0.703848
[ "object", "vector" ]
79eda0b6e65da30807286b029f8bed80d8896415
1,820
cpp
C++
data/transcoder_evaluation_gfg/cpp/MINIMUM_SUM_CHOOSING_MINIMUM_PAIRS_ARRAY.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
241
2021-07-20T08:35:20.000Z
2022-03-31T02:39:08.000Z
data/transcoder_evaluation_gfg/cpp/MINIMUM_SUM_CHOOSING_MINIMUM_PAIRS_ARRAY.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
49
2021-07-22T23:18:42.000Z
2022-03-24T09:15:26.000Z
data/transcoder_evaluation_gfg/cpp/MINIMUM_SUM_CHOOSING_MINIMUM_PAIRS_ARRAY.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
71
2021-07-21T05:17:52.000Z
2022-03-29T23:49:28.000Z
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // #include <iostream> #include <cstdlib> #include <string> #include <vector> #include <fstream> #include <iomanip> #include <bits/stdc++.h> using namespace std; int f_gold ( int A [ ], int n ) { int min_val = * min_element ( A, A + n ); return ( min_val * ( n - 1 ) ); } //TOFILL int main() { int n_success = 0; vector<vector<int>> param0 {{4,9,10,13,13,15,16,16,17,18,18,23,24,24,25,25,25,32,32,36,38,39,40,40,40,41,43,48,51,56,59,60,70,72,74,76,79,83,83,85,88,90,92,94,95,95},{46,-10,56,46,-30,-68,50,8,72,-2,38,-12,20,-30,-38,-78,-18,-34,16,94,30,-86,36,88,-26,-56,-98,-92,96,-70,-78,-60,20,-54,36,-12,78,24,14,98,-14,-88,76,12},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{59,64,29,99,29,63,29,63,88,94,82,92,99,56,51,74,73,22,42,37,21,36,68,69,16,81,3,85,67,13,41,87,67,99,83,47,95,90,24,31,1,54,61,35,51,13},{-98,-92,-82,-78,-76,-72,-64,-60,-44,-28,-22,-22,-14,-12,2,2,4,6,10,14,16,24,28,28,32,34,36,46,46,48,52,60,62,66,68,72,74,84,96},{1,1,1,1,1,0,1},{5,20,34,37,51,55,89},{-70,78,-52,-82,-24,96,-32,8,-50,38,-76,-56,64,-28,-22,94,52,-32,66,-34,-30,14,42,98,96,-56,50,50,-24,-56,70,6,78,86,52,-40,92,46,46,-14,-74,40},{0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{51,42,29,30,65,42,7,2,90,85,1,47,79,98,90,66,47,54,32,83}}; vector<int> param1 {26,25,32,45,31,6,3,33,26,19}; for(int i = 0; i < param0.size(); ++i) { if(f_filled(&param0[i].front(),param1[i]) == f_gold(&param0[i].front(),param1[i])) { n_success+=1; } } cout << "#Results:" << " " << n_success << ", " << param0.size(); return 0; }
49.189189
968
0.582418
[ "vector" ]
79ede84b6c8bd4af75248af3e467bc3b24135e2f
1,800
cpp
C++
demo-platformer/Level.cpp
leftidev/cpp-GEngine
fb1a000336f8295386c5e9e401072cfe0679b587
[ "MIT" ]
4
2016-04-02T05:52:59.000Z
2021-05-15T21:03:17.000Z
demo-platformer/Level.cpp
lefti-/cpp-GEngine
fb1a000336f8295386c5e9e401072cfe0679b587
[ "MIT" ]
null
null
null
demo-platformer/Level.cpp
lefti-/cpp-GEngine
fb1a000336f8295386c5e9e401072cfe0679b587
[ "MIT" ]
1
2016-04-13T17:25:44.000Z
2016-04-13T17:25:44.000Z
#include <fstream> #include <iostream> #include <algorithm> #include <cpp-GEngine/GEngineErrors.h> #include <cpp-GEngine/ResourceManager.h> #include "Level.h" Level::Level(const std::string& fileName) { std::ifstream file; file.open(fileName); // Error checking if (file.fail()) { GEngine::fatalError("Failed to open " + fileName); } // Throw away the first string in tmp std::string tmp; file >> tmp; std::getline(file, tmp); // Throw away the rest of the first line // Read the level data while (std::getline(file, tmp)) { _levelData.emplace_back(tmp); } // The level is flipped, reverse the vector std::reverse(_levelData.begin(), _levelData.end()); // Render all the tiles for (int y = 0; y < _levelData.size(); y++) { for (int x = 0; x < _levelData[y].size(); x++) { // Grab the tile char tile = _levelData[y][x]; // Process the tile switch (tile) { case '#': { Tile* temp = new Tile(); temp->init(GEngine::ResourceManager::getTexture("../assets/textures/black_tile.png").id, glm::fvec2(x * TILE_WIDTH, y * TILE_WIDTH)); _tiles.push_back(temp); } break; case '@': _startPlayerPos.x = x * TILE_WIDTH; _startPlayerPos.y = y * TILE_WIDTH; break; case '.': break; default: std::printf("Unexpected symbol %c at (%d,%d)", tile, x, y); break; } } } } Level::~Level() { // Delete the tiles for (int i = 0; i < _tiles.size(); i++) { delete _tiles[i]; } }
26.470588
153
0.507222
[ "render", "vector" ]
79f33abac81992cb77c3bd1fcfd0fcc8901810d7
2,249
cpp
C++
ImportantExample/tableprinter/Demo/tableprinterexample.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
ImportantExample/Demo/tableprinterexample.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
ImportantExample/Demo/tableprinterexample.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
/* * TableView Preview & Print demo * Copyright (C) 2004-2008 by Gordos Kund / QnD Co Bt. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * Please contact gordos.kund@gmail.com with any questions on this license. */ #include "tableprinterexample.h" #include "custommodel.h" #include <QMessageBox> #include <QDebug> TablePrinterExample::TablePrinterExample( QWidget* parent) : QWidget( parent) { grid=TDPreviewDialog::NoGrid; ui.setupUi(this); printer= new QPrinter(QPrinter::HighResolution); CustomModel *model=new CustomModel(this); ui.tableView->setModel(model); } //======================================== TablePrinterExample::~TablePrinterExample() { } //======================================== void TablePrinterExample::on_printPushButton_clicked() { TDPreviewDialog *dialog = new TDPreviewDialog(ui.tableView,printer,this); dialog->setGridMode(grid); dialog->print(); delete dialog; } //======================================== void TablePrinterExample::on_previewPushButton_clicked() { TDPreviewDialog *dialog = new TDPreviewDialog(ui.tableView,printer,this); dialog->setGridMode(grid); dialog->exec(); //do printing here... //... delete dialog; } //======================================== void TablePrinterExample::on_comboBox_currentIndexChanged ( int index ) { switch (index) { case 0: grid=TDPreviewDialog::NoGrid; break; case 1: grid=TDPreviewDialog::NormalGrid; break; case 2: grid=TDPreviewDialog::AlternateColor; break; case 3: grid= TDPreviewDialog::AlternateWithGrid; } }
27.426829
77
0.688306
[ "model" ]
0306caf81b69d6f395aaf15421336f95145057bb
3,173
hpp
C++
Simulator/Simulator.hpp
BartoszBartmanski/StoSpa
eee68f9b8b9be07aad435565f53b686ddcb876df
[ "MIT" ]
null
null
null
Simulator/Simulator.hpp
BartoszBartmanski/StoSpa
eee68f9b8b9be07aad435565f53b686ddcb876df
[ "MIT" ]
null
null
null
Simulator/Simulator.hpp
BartoszBartmanski/StoSpa
eee68f9b8b9be07aad435565f53b686ddcb876df
[ "MIT" ]
null
null
null
// // Created by bartosz on 31/12/18. // #ifndef STOSPA_SIMFUNCTIONS_HPP #define STOSPA_SIMFUNCTIONS_HPP #include "Simulation1d.hpp" #include "Simulation2d.hpp" /** * Brings together both constructors into a single line function. * (Templates are not used as they do not allow to specify dimension at runtime.) * @param params - parameters object that contains simulation parameters * @return - a pointer to the AbstractSimulation object */ unique_ptr<AbstractSimulation> simulator(Parameters params) { unique_ptr<AbstractSimulation> sim; if (params.GetNumDims() == 1) { sim = make_unique<Simulation1d>(params); } else { sim = make_unique<Simulation2d>(params); } return move(sim); } /** * Calculates the midpoint of the middle voxel (problems arise when even number of voxels) * @param domain_bounds - bounds of the domain * @param num_voxels - number of voxels in the x-direction * @param kappa - voxel aspect ratio * @return vector<double> */ vector<double> get_midpoint(const vector<double>& domain_bounds, const unsigned& num_voxels, const double& kappa) { vector<unsigned> voxels = {num_voxels, unsigned(kappa*num_voxels)}; vector<double> midpoint(2); for (unsigned i=0; i < 2; i++) { double size = (domain_bounds[1] - domain_bounds[0]) / voxels[i]; midpoint[i] = (voxels[i]/2 + 0.5 ) * size; } return midpoint; } /** * Returns pointer to JumpRate object that can give jump rates in specified directions. * @return unique_ptr<JumpRate> */ unique_ptr<JumpRate> get_jump_rates(vector<double> voxel_dims, const string &num_method="fdm", double alpha={}, vector<double> beta={}) { assert(!voxel_dims.empty()); unique_ptr<JumpRate> jump_rate; if (voxel_dims.size() == 1) { jump_rate = make_unique<JumpRate1d>(voxel_dims); } else { if (num_method == "fdm") { jump_rate = make_unique<FDM>(voxel_dims, alpha); } else if (num_method == "fem") { jump_rate = make_unique<FEM>(voxel_dims); } else if (num_method == "fvm") { jump_rate = make_unique<FVM>(voxel_dims); } else if (num_method == "fet") { jump_rate = make_unique<FET>(voxel_dims, beta, 1000); } else if (num_method == "fetU") { jump_rate = make_unique<FETUniform>(voxel_dims, beta, 1000); } else { throw runtime_error("Unknown input for numerical method from which to derive the jump coefficients!"); } } return move(jump_rate); } unique_ptr<JumpRate> get_jump_rates(Parameters &params) { double domain_size = params.GetDomainBounds()[1] - params.GetDomainBounds()[0]; vector<double> voxel_dims; double h_x = domain_size/params.GetNumVoxels(); if (params.GetNumDims() == 1) { voxel_dims = {h_x}; } else { voxel_dims = {h_x, h_x / params.GetKappa()}; } return move(get_jump_rates(voxel_dims, params.GetNumMethod(), params.GetAlpha(), params.GetBeta())); } #endif //STOSPA_SIMFUNCTIONS_HPP
27.833333
135
0.639773
[ "object", "vector" ]
030aaf066b2da3caa9a710650343f0d11d8ea6a0
682
cpp
C++
codeForces/#535/b.cpp
mmaximiliano/programming
72a7f4b3865d5a8d05944ba8081a5ab1cebf4c0d
[ "MIT" ]
null
null
null
codeForces/#535/b.cpp
mmaximiliano/programming
72a7f4b3865d5a8d05944ba8081a5ab1cebf4c0d
[ "MIT" ]
null
null
null
codeForces/#535/b.cpp
mmaximiliano/programming
72a7f4b3865d5a8d05944ba8081a5ab1cebf4c0d
[ "MIT" ]
null
null
null
#pragma GCC optimize("O3") //~ #pragma GCC optimize("Ofast") //~ #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") //~ #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> v(n); for (int i = 0; i < n; ++i) { cin >> v[i]; } int x = *max_element(v.begin(), v.end()); int ca = 0; for (int i = 0; i < v.size(); ++i) { if (v[i] == x) { ca++; } } if (ca > 1) { cout << x << " " << x; }else{ int y = 1; for (int i = 0; i < v.size(); ++i) { if (x % v[i] != 0) { y = lcm(y, v[i]); } } cout << x << " " << y; } return 0; }
13.115385
81
0.466276
[ "vector" ]
0315f29af4f5b2b35e2a36a5292c46b477d91093
4,627
cxx
C++
Filters/Core/Testing/Cxx/TestPartitionedDataSetCollectionConvertors.cxx
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
1,755
2015-01-03T06:55:00.000Z
2022-03-29T05:23:26.000Z
Filters/Core/Testing/Cxx/TestPartitionedDataSetCollectionConvertors.cxx
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
29
2015-04-23T20:58:30.000Z
2022-03-02T16:16:42.000Z
Filters/Core/Testing/Cxx/TestPartitionedDataSetCollectionConvertors.cxx
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
1,044
2015-01-05T22:48:27.000Z
2022-03-31T02:38:26.000Z
/*========================================================================= Program: Visualization Toolkit Module: TestPartitionedDataSetCollectionConvertors.cxx 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 "vtkConvertToMultiBlockDataSet.h" #include "vtkConvertToPartitionedDataSetCollection.h" #include "vtkDataAssembly.h" #include "vtkExodusIIReader.h" #include "vtkLogger.h" #include "vtkMultiBlockDataSet.h" #include "vtkMultiPieceDataSet.h" #include "vtkNew.h" #include "vtkPartitionedDataSetCollection.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include <vector> #define VERIFY(x) \ if (!(x)) \ { \ vtkLogF(ERROR, "Check Failed: '%s'", #x); \ return EXIT_FAILURE; \ } int TestPartitionedDataSetCollectionConvertors(int argc, char* argv[]) { vtkNew<vtkExodusIIReader> reader; char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/can.ex2"); reader->SetFileName(fname); delete[] fname; reader->UpdateInformation(); std::vector<int> obj_types{ vtkExodusIIReader::EDGE_BLOCK, vtkExodusIIReader::FACE_BLOCK, vtkExodusIIReader::ELEM_BLOCK, vtkExodusIIReader::NODE_SET, vtkExodusIIReader::EDGE_SET, vtkExodusIIReader::FACE_SET, vtkExodusIIReader::SIDE_SET, vtkExodusIIReader::ELEM_SET, vtkExodusIIReader::NODE_MAP, vtkExodusIIReader::EDGE_MAP, vtkExodusIIReader::FACE_MAP, vtkExodusIIReader::ELEM_MAP, }; for (const auto type : obj_types) { for (int cc = 0; cc < reader->GetNumberOfObjects(type); ++cc) { reader->SetObjectStatus(type, cc, 1); } } reader->Update(); //------------------------------------------------------------- // Test vtkMultiBlockDataSet to vtkPartitionedDataSetCollection. //------------------------------------------------------------- vtkNew<vtkConvertToPartitionedDataSetCollection> m2p; m2p->SetInputDataObject(reader->GetOutputDataObject(0)); m2p->Update(); auto ptc = vtkPartitionedDataSetCollection::SafeDownCast(m2p->GetOutputDataObject(0)); VERIFY(ptc->GetNumberOfPartitionedDataSets() == 5); // ptc->Print(cout); auto assembly = ptc->GetDataAssembly(); VERIFY(assembly != nullptr); vtkLogF(INFO, "Assembly XML:\n%s", assembly->SerializeToXML(vtkIndent(2)).c_str()); auto ids = assembly->SelectNodes({ "//*[@label='Element Blocks']" }); VERIFY(ids.size() == 1); VERIFY(assembly->GetDataSetIndices(ids.front()) == std::vector<unsigned int>({ 0, 1 })); ids = assembly->SelectNodes({ "//*[@label='Side Sets']" }); VERIFY(ids.size() == 1); VERIFY(assembly->GetDataSetIndices(ids.front()) == std::vector<unsigned int>({ 2 })); ids = assembly->SelectNodes({ "//*[@label='Node Sets']" }); VERIFY(ids.size() == 1); VERIFY(assembly->GetDataSetIndices(ids.front()) == std::vector<unsigned int>({ 3, 4 })); //------------------------------------------------------------- // Test vtkPartitionedDataSetCollection to vtkMultiBlockDataSet. // Note, the output vtkMultiBlockDataSet is not same as the original // vtkMultiBlockDataSet by design. //------------------------------------------------------------- vtkNew<vtkConvertToMultiBlockDataSet> p2m; p2m->SetInputConnection(m2p->GetOutputPort()); p2m->Update(); auto mb = p2m->GetOutput(); // mb->Print(cout); VERIFY(mb != nullptr); VERIFY(mb->GetNumberOfBlocks() == 5); VERIFY(vtkMultiPieceDataSet::SafeDownCast(mb->GetBlock(0))->GetNumberOfPieces() == 1); VERIFY(vtkMultiPieceDataSet::SafeDownCast(mb->GetBlock(1))->GetNumberOfPieces() == 1); VERIFY(vtkMultiPieceDataSet::SafeDownCast(mb->GetBlock(2))->GetNumberOfPieces() == 1); VERIFY(vtkMultiPieceDataSet::SafeDownCast(mb->GetBlock(3))->GetNumberOfPieces() == 1); VERIFY(vtkMultiPieceDataSet::SafeDownCast(mb->GetBlock(4))->GetNumberOfPieces() == 1); return EXIT_SUCCESS; }
40.587719
100
0.596283
[ "vector" ]
0316a874150a166fb84167016c1d12e3a1234875
6,274
hpp
C++
include/UnityEngine/CharacterController.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/UnityEngine/CharacterController.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/UnityEngine/CharacterController.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.Collider #include "UnityEngine/Collider.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Skipping declaration: Vector3 because it is already included! // Forward declaring type: CollisionFlags struct CollisionFlags; } // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Forward declaring type: CharacterController class CharacterController; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::CharacterController); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::CharacterController*, "UnityEngine", "CharacterController"); // Type namespace: UnityEngine namespace UnityEngine { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: UnityEngine.CharacterController // [TokenAttribute] Offset: FFFFFFFF // [NativeHeaderAttribute] Offset: 6C4294 class CharacterController : public ::UnityEngine::Collider { public: // public System.Boolean get_isGrounded() // Offset: 0x18F13B4 bool get_isGrounded(); // public System.Single get_height() // Offset: 0x18F13F4 float get_height(); // public UnityEngine.Vector3 get_center() // Offset: 0x18F1434 ::UnityEngine::Vector3 get_center(); // public System.Single get_stepOffset() // Offset: 0x18F14E4 float get_stepOffset(); // public UnityEngine.CollisionFlags Move(UnityEngine.Vector3 motion) // Offset: 0x18F130C ::UnityEngine::CollisionFlags Move(::UnityEngine::Vector3 motion); // private UnityEngine.CollisionFlags Move_Injected(ref UnityEngine.Vector3 motion) // Offset: 0x18F1364 ::UnityEngine::CollisionFlags Move_Injected(ByRef<::UnityEngine::Vector3> motion); // private System.Void get_center_Injected(out UnityEngine.Vector3 ret) // Offset: 0x18F1494 void get_center_Injected(ByRef<::UnityEngine::Vector3> ret); }; // UnityEngine.CharacterController #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::CharacterController::get_isGrounded // Il2CppName: get_isGrounded template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::CharacterController::*)()>(&UnityEngine::CharacterController::get_isGrounded)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::CharacterController*), "get_isGrounded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::CharacterController::get_height // Il2CppName: get_height template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (UnityEngine::CharacterController::*)()>(&UnityEngine::CharacterController::get_height)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::CharacterController*), "get_height", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::CharacterController::get_center // Il2CppName: get_center template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Vector3 (UnityEngine::CharacterController::*)()>(&UnityEngine::CharacterController::get_center)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::CharacterController*), "get_center", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::CharacterController::get_stepOffset // Il2CppName: get_stepOffset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (UnityEngine::CharacterController::*)()>(&UnityEngine::CharacterController::get_stepOffset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::CharacterController*), "get_stepOffset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::CharacterController::Move // Il2CppName: Move template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::CollisionFlags (UnityEngine::CharacterController::*)(::UnityEngine::Vector3)>(&UnityEngine::CharacterController::Move)> { static const MethodInfo* get() { static auto* motion = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::CharacterController*), "Move", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{motion}); } }; // Writing MetadataGetter for method: UnityEngine::CharacterController::Move_Injected // Il2CppName: Move_Injected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::CollisionFlags (UnityEngine::CharacterController::*)(ByRef<::UnityEngine::Vector3>)>(&UnityEngine::CharacterController::Move_Injected)> { static const MethodInfo* get() { static auto* motion = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->this_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::CharacterController*), "Move_Injected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{motion}); } }; // Writing MetadataGetter for method: UnityEngine::CharacterController::get_center_Injected // Il2CppName: get_center_Injected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::CharacterController::*)(ByRef<::UnityEngine::Vector3>)>(&UnityEngine::CharacterController::get_center_Injected)> { static const MethodInfo* get() { static auto* ret = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->this_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::CharacterController*), "get_center_Injected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{ret}); } };
52.283333
221
0.754702
[ "vector" ]
031974576be2f0c8fc827c97fcd9ebf72c93d1e7
327,015
cpp
C++
ds/security/cryptoapi/pki/certstor/frmtfunc.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/security/cryptoapi/pki/certstor/frmtfunc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/security/cryptoapi/pki/certstor/frmtfunc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1995 - 1999 // // File: frmtfunc.cpp // // Contents: OID format functions // // Functions: CryptFrmtFuncDllMain // CryptFormatObject // CryptQueryObject // // History: 15-05-97 xiaohs created // 27 Oct 1999 dsie add post win2k features. //-------------------------------------------------------------------------- #include "global.hxx" #include <dbgdef.h> #include "frmtfunc.h" HMODULE hFrmtFuncInst; static HCRYPTOIDFUNCSET hFormatFuncSet; //function type define typedef BOOL (WINAPI *PFN_FORMAT_FUNC)( IN DWORD dwCertEncodingType, IN DWORD dwFormatType, IN DWORD dwFormatStrType, IN void *pFormatStruct, IN LPCSTR lpszStructType, IN const BYTE *pbEncoded, IN DWORD cbEncoded, OUT void *pbFormat, IN OUT DWORD *pcbFormat ); static BOOL WINAPI FormatBytesToHex( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI CryptDllFormatAttr( DWORD dwEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pBuffer, DWORD *pcBuffer); static BOOL WINAPI CryptDllFormatName( DWORD dwEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbBuffer, DWORD *pcbBuffer); static BOOL WINAPI FormatBasicConstraints2( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatBasicConstraints( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatCRLReasonCode( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatEnhancedKeyUsage( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatAltName( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatAuthorityKeyID( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatAuthorityKeyID2( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatNextUpdateLocation( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatSubjectKeyID( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatFinancialCriteria( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatSMIMECapabilities( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatKeyUsage( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatAuthortiyInfoAccess( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatKeyAttributes( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatKeyRestriction( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatCRLDistPoints( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatCertPolicies( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatCAVersion( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatAnyUnicodeStringExtension( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatAnyNameValueStringAttr( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatNetscapeCertType( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatSPAgencyInfo( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); // // DSIE: Post Win2K. // static BOOL WINAPI FormatCrlNumber ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatCrlNextPublish ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatIssuingDistPoint ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatNameConstraints ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatCertSrvPreviousCertHash ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatPolicyMappings ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatPolicyConstraints ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatCertificateTemplate ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static BOOL WINAPI FormatXCertDistPoints( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat); static const CRYPT_OID_FUNC_ENTRY DefaultFormatTable[] = { CRYPT_DEFAULT_OID, FormatBytesToHex}; static const CRYPT_OID_FUNC_ENTRY OIDFormatTable[] = { szOID_COMMON_NAME, CryptDllFormatAttr, szOID_SUR_NAME, CryptDllFormatAttr, szOID_DEVICE_SERIAL_NUMBER, CryptDllFormatAttr, szOID_COUNTRY_NAME, CryptDllFormatAttr, szOID_LOCALITY_NAME, CryptDllFormatAttr, szOID_STATE_OR_PROVINCE_NAME, CryptDllFormatAttr, szOID_STREET_ADDRESS, CryptDllFormatAttr, szOID_ORGANIZATION_NAME, CryptDllFormatAttr, szOID_ORGANIZATIONAL_UNIT_NAME, CryptDllFormatAttr, szOID_TITLE, CryptDllFormatAttr, szOID_DESCRIPTION, CryptDllFormatAttr, szOID_SEARCH_GUIDE, CryptDllFormatAttr, szOID_BUSINESS_CATEGORY, CryptDllFormatAttr, szOID_POSTAL_ADDRESS, CryptDllFormatAttr, szOID_POSTAL_CODE, CryptDllFormatAttr, szOID_POST_OFFICE_BOX, CryptDllFormatAttr, szOID_PHYSICAL_DELIVERY_OFFICE_NAME, CryptDllFormatAttr, szOID_TELEPHONE_NUMBER, CryptDllFormatAttr, szOID_TELEX_NUMBER, CryptDllFormatAttr, szOID_TELETEXT_TERMINAL_IDENTIFIER, CryptDllFormatAttr, szOID_FACSIMILE_TELEPHONE_NUMBER, CryptDllFormatAttr, szOID_X21_ADDRESS, CryptDllFormatAttr, szOID_INTERNATIONAL_ISDN_NUMBER, CryptDllFormatAttr, szOID_REGISTERED_ADDRESS, CryptDllFormatAttr, szOID_DESTINATION_INDICATOR, CryptDllFormatAttr, szOID_PREFERRED_DELIVERY_METHOD, CryptDllFormatAttr, szOID_PRESENTATION_ADDRESS, CryptDllFormatAttr, szOID_SUPPORTED_APPLICATION_CONTEXT, CryptDllFormatAttr, szOID_MEMBER, CryptDllFormatAttr, szOID_OWNER, CryptDllFormatAttr, szOID_ROLE_OCCUPANT, CryptDllFormatAttr, szOID_SEE_ALSO, CryptDllFormatAttr, szOID_USER_PASSWORD, CryptDllFormatAttr, szOID_USER_CERTIFICATE, CryptDllFormatAttr, szOID_CA_CERTIFICATE, CryptDllFormatAttr, szOID_AUTHORITY_REVOCATION_LIST, CryptDllFormatAttr, szOID_CERTIFICATE_REVOCATION_LIST, CryptDllFormatAttr, szOID_CROSS_CERTIFICATE_PAIR, CryptDllFormatAttr, szOID_GIVEN_NAME, CryptDllFormatAttr, szOID_INITIALS, CryptDllFormatAttr, szOID_DOMAIN_COMPONENT, CryptDllFormatAttr, szOID_PKCS_12_FRIENDLY_NAME_ATTR, CryptDllFormatAttr, szOID_PKCS_12_LOCAL_KEY_ID, CryptDllFormatAttr, X509_NAME, CryptDllFormatName, X509_UNICODE_NAME, CryptDllFormatName, szOID_BASIC_CONSTRAINTS2, FormatBasicConstraints2, X509_BASIC_CONSTRAINTS2, FormatBasicConstraints2, szOID_BASIC_CONSTRAINTS, FormatBasicConstraints, X509_BASIC_CONSTRAINTS, FormatBasicConstraints, szOID_CRL_REASON_CODE, FormatCRLReasonCode, X509_CRL_REASON_CODE, FormatCRLReasonCode, szOID_ENHANCED_KEY_USAGE, FormatEnhancedKeyUsage, X509_ENHANCED_KEY_USAGE, FormatEnhancedKeyUsage, szOID_SUBJECT_ALT_NAME, FormatAltName, szOID_ISSUER_ALT_NAME, FormatAltName, szOID_SUBJECT_ALT_NAME2, FormatAltName, szOID_ISSUER_ALT_NAME2, FormatAltName, X509_ALTERNATE_NAME, FormatAltName, szOID_AUTHORITY_KEY_IDENTIFIER, FormatAuthorityKeyID, X509_AUTHORITY_KEY_ID, FormatAuthorityKeyID, szOID_AUTHORITY_KEY_IDENTIFIER2, FormatAuthorityKeyID2, X509_AUTHORITY_KEY_ID2, FormatAuthorityKeyID2, szOID_NEXT_UPDATE_LOCATION, FormatNextUpdateLocation, szOID_SUBJECT_KEY_IDENTIFIER, FormatSubjectKeyID, SPC_FINANCIAL_CRITERIA_OBJID, FormatFinancialCriteria, SPC_FINANCIAL_CRITERIA_STRUCT, FormatFinancialCriteria, szOID_RSA_SMIMECapabilities, FormatSMIMECapabilities, PKCS_SMIME_CAPABILITIES, FormatSMIMECapabilities, szOID_KEY_USAGE, FormatKeyUsage, X509_KEY_USAGE, FormatKeyUsage, szOID_AUTHORITY_INFO_ACCESS, FormatAuthortiyInfoAccess, X509_AUTHORITY_INFO_ACCESS, FormatAuthortiyInfoAccess, szOID_KEY_ATTRIBUTES, FormatKeyAttributes, X509_KEY_ATTRIBUTES, FormatKeyAttributes, szOID_KEY_USAGE_RESTRICTION, FormatKeyRestriction, X509_KEY_USAGE_RESTRICTION, FormatKeyRestriction, szOID_CRL_DIST_POINTS, FormatCRLDistPoints, X509_CRL_DIST_POINTS, FormatCRLDistPoints, szOID_FRESHEST_CRL, FormatCRLDistPoints, // Post Win2K szOID_CERT_POLICIES, FormatCertPolicies, X509_CERT_POLICIES, FormatCertPolicies, szOID_ENROLL_CERTTYPE_EXTENSION, FormatAnyUnicodeStringExtension, szOID_OS_VERSION, FormatAnyUnicodeStringExtension, szOID_NETSCAPE_CERT_TYPE, FormatNetscapeCertType, szOID_NETSCAPE_BASE_URL, FormatAnyUnicodeStringExtension, szOID_NETSCAPE_REVOCATION_URL, FormatAnyUnicodeStringExtension, szOID_NETSCAPE_CA_REVOCATION_URL, FormatAnyUnicodeStringExtension, szOID_NETSCAPE_CERT_RENEWAL_URL, FormatAnyUnicodeStringExtension, szOID_NETSCAPE_CA_POLICY_URL, FormatAnyUnicodeStringExtension, szOID_NETSCAPE_SSL_SERVER_NAME, FormatAnyUnicodeStringExtension, szOID_NETSCAPE_COMMENT, FormatAnyUnicodeStringExtension, szOID_ENROLLMENT_NAME_VALUE_PAIR, FormatAnyNameValueStringAttr, szOID_CERTSRV_CA_VERSION, FormatCAVersion, SPC_SP_AGENCY_INFO_OBJID, FormatSPAgencyInfo, SPC_SP_AGENCY_INFO_STRUCT, FormatSPAgencyInfo, // Post Win2K szOID_CRL_NUMBER, FormatCrlNumber, szOID_DELTA_CRL_INDICATOR, FormatCrlNumber, szOID_CRL_VIRTUAL_BASE, FormatCrlNumber, szOID_CRL_NEXT_PUBLISH, FormatCrlNextPublish, szOID_ISSUING_DIST_POINT, FormatIssuingDistPoint, X509_ISSUING_DIST_POINT, FormatIssuingDistPoint, szOID_NAME_CONSTRAINTS, FormatNameConstraints, X509_NAME_CONSTRAINTS, FormatNameConstraints, szOID_CERTSRV_PREVIOUS_CERT_HASH, FormatCertSrvPreviousCertHash, szOID_APPLICATION_CERT_POLICIES, FormatCertPolicies, X509_POLICY_MAPPINGS, FormatPolicyMappings, szOID_POLICY_MAPPINGS, FormatPolicyMappings, szOID_APPLICATION_POLICY_MAPPINGS, FormatPolicyMappings, X509_POLICY_CONSTRAINTS, FormatPolicyConstraints, szOID_POLICY_CONSTRAINTS, FormatPolicyConstraints, szOID_APPLICATION_POLICY_CONSTRAINTS, FormatPolicyConstraints, X509_CERTIFICATE_TEMPLATE, FormatCertificateTemplate, szOID_CERTIFICATE_TEMPLATE, FormatCertificateTemplate, szOID_CRL_SELF_CDP, FormatCRLDistPoints, X509_CROSS_CERT_DIST_POINTS, FormatXCertDistPoints, szOID_CROSS_CERT_DIST_POINTS, FormatXCertDistPoints, }; DWORD dwOIDFormatCount = sizeof(OIDFormatTable) / sizeof(OIDFormatTable[0]); //+------------------------------------------------------------------------- // Dll initialization //-------------------------------------------------------------------------- BOOL WINAPI CryptFrmtFuncDllMain( HMODULE hModule, DWORD fdwReason, LPVOID lpReserved) { BOOL fRet; switch (fdwReason) { case DLL_PROCESS_ATTACH: hFrmtFuncInst = hModule; if (NULL == (hFormatFuncSet = CryptInitOIDFunctionSet( CRYPT_OID_FORMAT_OBJECT_FUNC, 0))) // dwFlags goto CryptInitFrmtFuncError; //install the default formatting routine if (!CryptInstallOIDFunctionAddress( NULL, // hModule X509_ASN_ENCODING, CRYPT_OID_FORMAT_OBJECT_FUNC, 1, DefaultFormatTable, 0)) // dwFlags goto CryptInstallFrmtFuncError; //install the OID formatting routine if (!CryptInstallOIDFunctionAddress( NULL, // hModule X509_ASN_ENCODING, CRYPT_OID_FORMAT_OBJECT_FUNC, dwOIDFormatCount, OIDFormatTable, 0)) // dwFlags goto CryptInstallFrmtFuncError; break; case DLL_PROCESS_DETACH: case DLL_THREAD_DETACH: default: break; } fRet = TRUE; CommonReturn: return fRet; ErrorReturn: fRet = FALSE; goto CommonReturn; TRACE_ERROR(CryptInitFrmtFuncError) TRACE_ERROR(CryptInstallFrmtFuncError) } //------------------------------------------------------------------------ // Convert the byte to its Hex presentation. // // Precondition: byte is less than 15 // //------------------------------------------------------------------------ ULONG ByteToHex(BYTE byte, LPWSTR wszZero, LPWSTR wszA) { ULONG uValue=0; if(((ULONG)byte)<=9) { uValue=((ULONG)byte)+ULONG(*wszZero); } else { uValue=(ULONG)byte-10+ULONG(*wszA); } return uValue; } //-------------------------------------------------------------------------- // // Format the encoded bytes into a hex string in the format of // xxxx xxxx xxxx xxxx ... // // DSIE 6/28/2000: change format to xx xx xx xx, per VicH's request. //-------------------------------------------------------------------------- static BOOL WINAPI FormatBytesToHex( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszBuffer=NULL; DWORD dwBufferSize=0; DWORD dwBufferIndex=0; DWORD dwEncodedIndex=0; WCHAR wszSpace[CHAR_SIZE]; WCHAR wszZero[CHAR_SIZE]; WCHAR wszA[CHAR_SIZE]; WCHAR wszHex[HEX_SIZE]; //check for input parameters if(( pbEncoded!=NULL && cbEncoded==0) ||(pbEncoded==NULL && cbEncoded!=0) || (pcbFormat==NULL)) { SetLastError((DWORD) E_INVALIDARG); return FALSE; } #if (0) // DSIE: Fix bug 128630. //check for simple case. No work needed if(pbEncoded==NULL && cbEncoded==0) { *pcbFormat=0; return TRUE; } #endif //calculate the memory needed, in bytes //we need 3 wchars per byte, along with the NULL terminator dwBufferSize=sizeof(WCHAR)*(cbEncoded*3+1); //length only calculation if(pcbFormat!=NULL && pbFormat==NULL) { *pcbFormat=dwBufferSize; return TRUE; } //load the string if(!LoadStringU(hFrmtFuncInst, IDS_FRMT_SPACE, wszSpace, CHAR_SIZE) ||!LoadStringU(hFrmtFuncInst, IDS_FRMT_ZERO, wszZero, CHAR_SIZE) ||!LoadStringU(hFrmtFuncInst, IDS_FRMT_A, wszA, CHAR_SIZE) ||!LoadStringU(hFrmtFuncInst, IDS_FRMT_HEX, wszHex, HEX_SIZE) ) { SetLastError((DWORD) E_UNEXPECTED); return FALSE; } pwszBuffer=(LPWSTR)malloc(dwBufferSize); if(!pwszBuffer) { SetLastError((DWORD) E_OUTOFMEMORY); return FALSE; } dwBufferIndex=0; //format the wchar buffer one byte at a time for(dwEncodedIndex=0; dwEncodedIndex<cbEncoded; dwEncodedIndex++) { #if (0) // DSIE: //copy the space between every two bytes. Skip for the 1st byte if((0!=dwEncodedIndex) && (0==(dwEncodedIndex % 2))) #else //copy the space between every byte. Skip for the 1st byte if(dwEncodedIndex != 0) #endif { pwszBuffer[dwBufferIndex]=wszSpace[0]; dwBufferIndex++; } //format the higher 4 bits pwszBuffer[dwBufferIndex]=(WCHAR)ByteToHex( (BYTE)( (pbEncoded[dwEncodedIndex]&UPPER_BITS)>>4 ), wszZero, wszA); dwBufferIndex++; //format the lower 4 bits pwszBuffer[dwBufferIndex]=(WCHAR)ByteToHex( (BYTE)( pbEncoded[dwEncodedIndex]&LOWER_BITS ), wszZero, wszA); dwBufferIndex++; } //add the NULL terminator to the string pwszBuffer[dwBufferIndex]=wszSpace[1]; //calculate the real size for the buffer dwBufferSize=sizeof(WCHAR)*(wcslen(pwszBuffer)+1); //copy the buffer memcpy(pbFormat, pwszBuffer, (*pcbFormat>=dwBufferSize) ? dwBufferSize : *pcbFormat); free(pwszBuffer); //make sure the user has supplied enough memory if(*pcbFormat < dwBufferSize) { *pcbFormat=dwBufferSize; SetLastError((DWORD) ERROR_MORE_DATA); return FALSE; } *pcbFormat=dwBufferSize; return TRUE; } //+----------------------------------------------------------------------------- // // AllocateAnsiToUnicode // //------------------------------------------------------------------------------ static BOOL WINAPI AllocateAnsiToUnicode( LPCSTR pszAnsi, LPWSTR * ppwszUnicode) { BOOL fResult = FALSE; LPWSTR pwszUnicode = NULL; DWORD dwWideSize = 0; if (!ppwszUnicode) { goto InvalidArg; } *ppwszUnicode = NULL; if (!pszAnsi) { return TRUE; } if (!(dwWideSize = MultiByteToWideChar(CP_ACP, 0, pszAnsi, strlen(pszAnsi), NULL, 0))) { goto szTOwszError; } // // Allocate memory, including the NULL terminator. // if (!(pwszUnicode = (WCHAR *) malloc(sizeof(WCHAR) * (dwWideSize + 1)))) { goto MemoryError; } memset(pwszUnicode, 0, sizeof(WCHAR) * (dwWideSize + 1)); if (!MultiByteToWideChar(CP_ACP, 0, pszAnsi, strlen(pszAnsi), pwszUnicode, dwWideSize)) { free(pwszUnicode); goto szTOwszError; } *ppwszUnicode = pwszUnicode; fResult = TRUE; CommonReturn: return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(szTOwszError); } //+----------------------------------------------------------------------------- // // FormatObjectId // //------------------------------------------------------------------------------ static BOOL WINAPI FormatObjectId ( LPSTR pszObjId, DWORD dwGroupId, BOOL bMultiLines, LPWSTR * ppwszFormat) { BOOL fResult; PCCRYPT_OID_INFO pOIDInfo = NULL; LPWSTR pwszObjId = NULL; // // Initialize. // *ppwszFormat = NULL; // // Convert OID to Unicode. // if (!AllocateAnsiToUnicode(pszObjId, &pwszObjId)) { goto AnsiToUnicodeError; } // // Find OID info. // if (pOIDInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, (void *) pszObjId, dwGroupId)) { // // "%1!s!(%2!s!)%3!s!" // if (!FormatMessageUnicode(ppwszFormat, IDS_GENERIC_OBJECT_ID, pOIDInfo->pwszName, pwszObjId, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } } else { // // "%1!s!%2!s!" // if (!FormatMessageUnicode(ppwszFormat, IDS_STRING, pwszObjId, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } } fResult = TRUE; CommonReturn: if (pwszObjId) { free(pwszObjId); } return fResult; ErrorReturn: fResult = FALSE; goto CommonReturn; TRACE_ERROR(AnsiToUnicodeError); TRACE_ERROR(FormatMessageError); } //+----------------------------------------------------------------------------- // // FormatIPAddress // //------------------------------------------------------------------------------ static BOOL WINAPI FormatIPAddress( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, UINT idsPrefix, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult; DWORD cbNeeded = 0; LPWSTR pwszFormat = NULL; WCHAR wszPrefix[PRE_FIX_SIZE] = wszEMPTY; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; // // Check for input parameters. // if ((pbEncoded!=NULL && cbEncoded==0) || (pbEncoded==NULL && cbEncoded!=0) || (pcbFormat==NULL)) { goto InvalidArg; } if (bMultiLines && idsPrefix) { if(!LoadStringU(hFrmtFuncInst, idsPrefix, wszPrefix, sizeof(wszPrefix) / sizeof(wszPrefix[0]))) { goto LoadStringError; } } switch (cbEncoded) { case 4: { // // "%1!d!.%2!d!.%3!d!.%4!d!" // if (!FormatMessageUnicode(&pwszFormat, IDS_IPADDRESS_V4_4, (DWORD) pbEncoded[0], (DWORD) pbEncoded[1], (DWORD) pbEncoded[2], (DWORD) pbEncoded[3])) { goto FormatMessageError; } break; } case 8: { // // "%1!d!.%2!d!.%3!d!.%4!d!%5!s!%6!s!Mask=%7!d!.%8!d!.%9!d!.%10!d!" // if (!FormatMessageUnicode(&pwszFormat, IDS_IPADDRESS_V4_8, (DWORD) pbEncoded[0], (DWORD) pbEncoded[1], (DWORD) pbEncoded[2], (DWORD) pbEncoded[3], bMultiLines ? wszCRLF : wszEMPTY, bMultiLines ? wszPrefix : wszCOMMA, (DWORD) pbEncoded[4], (DWORD) pbEncoded[5], (DWORD) pbEncoded[6], (DWORD) pbEncoded[7])) { goto FormatMessageError; } break; } case 16: { // // "%1!02x!%2!02x!:%3!02x!%4!02x!:%5!02x!%6!02x!:%7!02x!%8!02x!:%9!02x!%10!02x!:%11!02x!%12!02x!:%13!02x!%14!02x!:%15!02x!%16!02x!" // if (!FormatMessageUnicode(&pwszFormat, IDS_IPADDRESS_V6_16, (DWORD) pbEncoded[0], (DWORD) pbEncoded[1], (DWORD) pbEncoded[2], (DWORD) pbEncoded[3], (DWORD) pbEncoded[4], (DWORD) pbEncoded[5], (DWORD) pbEncoded[6], (DWORD) pbEncoded[7], (DWORD) pbEncoded[8], (DWORD) pbEncoded[9], (DWORD) pbEncoded[10], (DWORD) pbEncoded[11], (DWORD) pbEncoded[12], (DWORD) pbEncoded[13], (DWORD) pbEncoded[14], (DWORD) pbEncoded[15])) { goto FormatMessageError; } break; } case 32: { // // "%1!02x!%2!02x!:%3!02x!%4!02x!:%5!02x!%6!02x!:%7!02x!%8!02x!:%9!02x!%10!02x!:%11!02x!%12!02x!:%13!02x!%14!02x!:%15!02x!%16!02x!%17!s!%18!s! // Mask=%19!02x!%20!02x!:%21!02x!%22!02x!:%23!02x!%24!02x!:%25!02x!%26!02x!:%27!02x!%28!02x!:%29!02x!%30!02x!:%31!02x!%32!02x!:%33!02x!%34!02x!" // if (!FormatMessageUnicode(&pwszFormat, IDS_IPADDRESS_V6_32, (DWORD) pbEncoded[0], (DWORD) pbEncoded[1], (DWORD) pbEncoded[2], (DWORD) pbEncoded[3], (DWORD) pbEncoded[4], (DWORD) pbEncoded[5], (DWORD) pbEncoded[6], (DWORD) pbEncoded[7], (DWORD) pbEncoded[8], (DWORD) pbEncoded[9], (DWORD) pbEncoded[10], (DWORD) pbEncoded[11], (DWORD) pbEncoded[12], (DWORD) pbEncoded[13], (DWORD) pbEncoded[14], (DWORD) pbEncoded[15], bMultiLines ? wszCRLF : wszEMPTY, bMultiLines ? wszPrefix : wszCOMMA, (DWORD) pbEncoded[16], (DWORD) pbEncoded[17], (DWORD) pbEncoded[18], (DWORD) pbEncoded[19], (DWORD) pbEncoded[20], (DWORD) pbEncoded[21], (DWORD) pbEncoded[22], (DWORD) pbEncoded[23], (DWORD) pbEncoded[24], (DWORD) pbEncoded[25], (DWORD) pbEncoded[26], (DWORD) pbEncoded[27], (DWORD) pbEncoded[28], (DWORD) pbEncoded[29], (DWORD) pbEncoded[30], (DWORD) pbEncoded[31])) { goto FormatMessageError; } break; } default: { if (!(fResult = FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pbEncoded, cbEncoded, pbFormat, pcbFormat))) { goto FormatBytesToHexError; } goto CommonReturn; } } // // Total length needed. // cbNeeded = sizeof(WCHAR) * (wcslen(pwszFormat) + 1); // // Length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbNeeded) { *pcbFormat = cbNeeded; goto MoreDataError; } // // Copy size and data. // memcpy(pbFormat, pwszFormat, cbNeeded); *pcbFormat = cbNeeded; SuccessReturn: fResult = TRUE; CommonReturn: if (pwszFormat) { LocalFree((HLOCAL) pwszFormat); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); TRACE_ERROR(LoadStringError); TRACE_ERROR(FormatMessageError); TRACE_ERROR(FormatBytesToHexError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //+------------------------------------------------------------------------- // format the specified data structure according to the certificate // encoding type. //-------------------------------------------------------------------------- BOOL WINAPI CryptFormatObject( IN DWORD dwCertEncodingType, IN DWORD dwFormatType, IN DWORD dwFormatStrType, IN void *pFormatStruct, IN LPCSTR lpszStructType, IN const BYTE *pbEncoded, IN DWORD cbEncoded, OUT void *pbFormat, IN OUT DWORD *pcbFormat ) { BOOL fResult=FALSE; void *pvFuncAddr; HCRYPTOIDFUNCADDR hFuncAddr; if (CryptGetOIDFunctionAddress( hFormatFuncSet, dwCertEncodingType, lpszStructType, 0, // dwFlags &pvFuncAddr, &hFuncAddr)) { fResult = ((PFN_FORMAT_FUNC) pvFuncAddr)( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pbEncoded, cbEncoded, pbFormat, pcbFormat ); CryptFreeOIDFunctionAddress(hFuncAddr, 0); } else { //do not call the default hex dump if CRYPT_FORMAT_STR_NO_HEX is set if(0==(dwFormatStrType & CRYPT_FORMAT_STR_NO_HEX)) { //call the default routine automatically if (CryptGetOIDFunctionAddress( hFormatFuncSet, dwCertEncodingType, CRYPT_DEFAULT_OID, 0, // dwFlags &pvFuncAddr, &hFuncAddr)) { fResult = ((PFN_FORMAT_FUNC) pvFuncAddr)( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pbEncoded, cbEncoded, pbFormat, pcbFormat); CryptFreeOIDFunctionAddress(hFuncAddr, 0); } else { *pcbFormat = 0; fResult = FALSE; } } else { *pcbFormat = 0; fResult = FALSE; } } return fResult; } //----------------------------------------------------------- // // This is the actual format routine for an particular RDN attribute. // // lpszStructType is any OID for CERT_RDN_ATTR. pbEncoded is // an encoded BLOB for CERT_NAME_INFO struct. When pBuffer==NULL, // *pcbBuffer return the size of memory to be allocated in bytes. // Please notice the string is not NULL terminated. // // For example, to ask for an unicode string of common name, // pass lpszStructType=szOID_COMMON_NAME, // pass dwFormatType==CRYPT_FORMAT_SIMPL, // pBuffer will be set the L"xiaohs@microsoft.com". // // //------------------------------------------------------------- static BOOL WINAPI CryptDllFormatAttr( DWORD dwEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pBuffer, DWORD *pcbBuffer) { BOOL fResult=FALSE; WCHAR *pwszSeperator=NULL; BOOL fHeader=FALSE; BOOL flengthOnly=FALSE; DWORD dwBufferCount=0; DWORD dwBufferLimit=0; DWORD dwBufferIncrement=0; DWORD dwSeperator=0; DWORD dwHeader=0; DWORD dwOIDSize=0; WCHAR *pwszBuffer=NULL; WCHAR *pwszHeader=NULL; BOOL fAddSeperator=FALSE; DWORD cbStructInfo=0; CERT_NAME_INFO *pStructInfo=NULL; DWORD dwRDNIndex=0; DWORD dwAttrIndex=0; DWORD dwAttrCount=0; CERT_RDN_ATTR *pCertRDNAttr=NULL; PCCRYPT_OID_INFO pOIDInfo=NULL; LPWSTR pwszTemp; //check input parameters if(lpszStructType==NULL || (pbEncoded==NULL && cbEncoded!=0) || pcbBuffer==NULL ) goto InvalidArg; if(cbEncoded==0) { *pcbBuffer=0; goto InvalidArg; } //get the seperator of the attributes //wszCOMMA is the default seperator if(dwFormatType & CRYPT_FORMAT_COMMA) pwszSeperator=wszCOMMA; else { if(dwFormatType & CRYPT_FORMAT_SEMICOLON) pwszSeperator=wszSEMICOLON; else { if(dwFormatType & CRYPT_FORMAT_CRLF) pwszSeperator=wszCRLF; else { pwszSeperator=wszPLUS; } } } //calculate the length of the seperator dwSeperator=wcslen(pwszSeperator)*sizeof(WCHAR); //check the requirement for the header if(dwFormatType & CRYPT_FORMAT_X509 || dwFormatType & CRYPT_FORMAT_OID) { fHeader=TRUE; } if(NULL==pBuffer) flengthOnly=TRUE; //decode the X509_UNICODE_NAME if(!CryptDecodeObject(dwEncodingType, X509_UNICODE_NAME, pbEncoded, cbEncoded, CRYPT_DECODE_NOCOPY_FLAG, NULL, &cbStructInfo)) goto DecodeError; //allocate memory pStructInfo=(CERT_NAME_INFO *)malloc(cbStructInfo); if(!pStructInfo) goto MemoryError; //decode the struct if(!CryptDecodeObject(dwEncodingType, X509_UNICODE_NAME, pbEncoded, cbEncoded, CRYPT_DECODE_NOCOPY_FLAG, pStructInfo, &cbStructInfo)) goto DecodeError; //allocate the buffer for formatting if(!flengthOnly) { pwszBuffer=(WCHAR *)malloc(g_AllocateSize); if(!pwszBuffer) goto MemoryError; dwBufferLimit=g_AllocateSize; } //search for the OID requested. If found one, put it //to the buffer. If no requested attribut is found, //return. for(dwRDNIndex=0; dwRDNIndex<pStructInfo->cRDN; dwRDNIndex++) { //the following line is for code optimization dwAttrCount=(pStructInfo->rgRDN)[dwRDNIndex].cRDNAttr; for(dwAttrIndex=0; dwAttrIndex<dwAttrCount; dwAttrIndex++) { //look for the specific OIDs in the function if(_stricmp(lpszStructType, (pStructInfo->rgRDN)[dwRDNIndex].rgRDNAttr[dwAttrIndex].pszObjId)==0) { pCertRDNAttr=&((pStructInfo->rgRDN)[dwRDNIndex].rgRDNAttr[dwAttrIndex]); //init the dwBufferIncrement dwBufferIncrement=0; //get the header of the tag if(fHeader) { if(dwFormatType & CRYPT_FORMAT_X509) { //get the OID's name pOIDInfo=CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, (void *)lpszStructType, CRYPT_RDN_ATTR_OID_GROUP_ID); if(pOIDInfo) { //allocate memory, including the NULL terminator pwszHeader=(WCHAR *)malloc((wcslen(pOIDInfo->pwszName)+wcslen(wszEQUAL)+1)* sizeof(WCHAR)); if(!pwszHeader) goto MemoryError; wcscpy(pwszHeader,pOIDInfo->pwszName); } } //use the OID is no mapping is found or //OID is requested in the header if(pwszHeader==NULL) { //get the wide character string to the OID if(!(dwOIDSize=MultiByteToWideChar(CP_ACP,0, lpszStructType,strlen(lpszStructType),NULL,0))) goto szTOwszError; //allocate memory, including the NULL terminator pwszHeader=(WCHAR *)malloc((dwOIDSize+wcslen(wszEQUAL)+1)* sizeof(WCHAR)); if(!pwszHeader) goto MemoryError; if(!(dwHeader=MultiByteToWideChar(CP_ACP,0, lpszStructType,strlen(lpszStructType),pwszHeader,dwOIDSize))) goto szTOwszError; //NULL terminate the string *(pwszHeader+dwHeader)=L'\0'; } //add the euqal sign wcscat(pwszHeader, wszEQUAL); //get the header size, in bytes, excluding the NULL terminator dwHeader=wcslen(pwszHeader)*sizeof(WCHAR); dwBufferIncrement+=dwHeader; } //allocate enough memory. Including the NULL terminator dwBufferIncrement+=pCertRDNAttr->Value.cbData; dwBufferIncrement+=dwSeperator; dwBufferIncrement+=2; if(!flengthOnly && ((dwBufferCount+dwBufferIncrement)>dwBufferLimit)) { //reallocate the memory #if (0) // DSIE: Bug 27436 pwszBuffer=(WCHAR *)realloc(pwszBuffer, max(dwBufferLimit+g_AllocateSize, dwBufferLimit+dwBufferIncrement)); if(!pwszBuffer) goto MemoryError; #endif pwszTemp=(WCHAR *)realloc(pwszBuffer, max(dwBufferLimit+g_AllocateSize, dwBufferLimit+dwBufferIncrement)); if(!pwszTemp) goto MemoryError; pwszBuffer = pwszTemp; dwBufferLimit+=max(g_AllocateSize,dwBufferIncrement); } //add the header if necessary if(fHeader) { if(!flengthOnly) { memcpy((BYTE *)(pwszBuffer+dwBufferCount/sizeof(WCHAR)), pwszHeader,dwHeader); } dwBufferCount+=dwHeader; //do not need to do header anymore fHeader=FALSE; } //add the seperator after the 1st iteration if(fAddSeperator) { if(!flengthOnly) { memcpy((BYTE *)(pwszBuffer+dwBufferCount/sizeof(WCHAR)), pwszSeperator,dwSeperator); } dwBufferCount+=dwSeperator; } else fAddSeperator=TRUE; //add the attr content if(!flengthOnly) { memcpy((BYTE *)(pwszBuffer+dwBufferCount/sizeof(WCHAR)), (pCertRDNAttr->Value.pbData), pCertRDNAttr->Value.cbData); } //increment the buffercount dwBufferCount+=pCertRDNAttr->Value.cbData; } } } //return the result as requested //check if the requested OID is actually in the DN if(0==dwBufferCount) { *pcbBuffer=dwBufferCount; goto NotFoundError; } //we need to NULL terminate the string if(!flengthOnly) *(pwszBuffer+dwBufferCount/sizeof(WCHAR))=L'\0'; dwBufferCount+=2; if(pBuffer==NULL) { *pcbBuffer=dwBufferCount; fResult=TRUE; goto CommonReturn; } if((*pcbBuffer)<dwBufferCount) { *pcbBuffer=dwBufferCount; goto MoreDataError; } *pcbBuffer=dwBufferCount; memcpy(pBuffer, pwszBuffer,dwBufferCount); fResult=TRUE; CommonReturn: if(pwszHeader) free(pwszHeader); if(pwszBuffer) free(pwszBuffer); if(pStructInfo) free(pStructInfo); return fResult; ErrorReturn: fResult = FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(DecodeError); TRACE_ERROR(szTOwszError); SET_ERROR(NotFoundError, E_FAIL); SET_ERROR(MoreDataError, ERROR_MORE_DATA); } //----------------------------------------------------------- // // This is the actual format routine for an complete CERT_NAME // // // lpszStructType should be X509_NAME pbEncoded is // an encoded BLOB for CERT_NAME_INFO struct. When pBuffer==NULL, // *pcbBuffer return the size of memory to be allocated in bytes. // Please notice the string is NULL terminated. // //------------------------------------------------------------- static BOOL WINAPI CryptDllFormatName( DWORD dwEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbBuffer, DWORD *pcbBuffer) { //makesure lpszStructType is X509_NAME or X509_UNICODE_NAME if((X509_NAME != lpszStructType) && (X509_UNICODE_NAME != lpszStructType)) { SetLastError((DWORD) E_INVALIDARG); return FALSE; } //check input parameters if((pbEncoded==NULL && cbEncoded!=0) || pcbBuffer==NULL) { SetLastError((DWORD) E_INVALIDARG); return FALSE; } if(cbEncoded==0) { SetLastError((DWORD) E_INVALIDARG); return FALSE; } //call CryptDllFormatNameAll with no prefix return CryptDllFormatNameAll(dwEncodingType, dwFormatType, dwFormatStrType, pStruct, 0, FALSE, pbEncoded, cbEncoded, &pbBuffer, pcbBuffer); } //----------------------------------------------------------- // // This is the actual format routine for an complete CERT_NAME // // // lpszStructType should be X509_NAME pbEncoded is // an encoded BLOB for CERT_NAME_INFO struct. When pBuffer==NULL, // *pcbBuffer return the size of memory to be allocated in bytes. // Please notice the string is NULL terminated. // //------------------------------------------------------------- BOOL CryptDllFormatNameAll( DWORD dwEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pStruct, UINT idsPreFix, BOOL fToAllocate, const BYTE *pbEncoded, DWORD cbEncoded, void **ppbBuffer, DWORD *pcbBuffer) { BOOL fResult=FALSE; DWORD dwStrType=0; CERT_NAME_BLOB Cert_Name_Blob; DWORD dwSize=0; LPWSTR pwszName=NULL; LPWSTR pwszMulti=NULL; Cert_Name_Blob.cbData=cbEncoded; Cert_Name_Blob.pbData=(BYTE *)pbEncoded; //calculate the dwStryType to use for CertNameToStrW dwStrType=FormatToStr(dwFormatType); //overwrite dwStrType to default if we are doing MULTI line format //since the options will be ignored //We want to use + and , for the seperator if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) { dwStrType &=~(CERT_NAME_STR_CRLF_FLAG); dwStrType &=~(CERT_NAME_STR_COMMA_FLAG); dwStrType &=~(CERT_NAME_STR_SEMICOLON_FLAG); dwStrType &=~(CERT_NAME_STR_NO_QUOTING_FLAG); dwStrType &=~(CERT_NAME_STR_NO_PLUS_FLAG); } //if this function is not called from CryptDllFormatName, //make sure that we use the RESERSE Flag if(TRUE == fToAllocate) dwStrType |= CERT_NAME_STR_REVERSE_FLAG; //call the CertNameToStrW to convert dwSize=CertNameToStrW(dwEncodingType, &Cert_Name_Blob, dwStrType, NULL, 0); if(0==dwSize) goto CertNameToStrError; pwszName=(LPWSTR)malloc(sizeof(WCHAR)*(dwSize)); if(NULL==pwszName) goto MemoryError; dwSize=CertNameToStrW(dwEncodingType, &Cert_Name_Blob, dwStrType, pwszName, dwSize); if(0==dwSize) goto CertNameToStrError; //we do not need to parse the string for single line format if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) { //calculate the bytes needed dwSize=sizeof(WCHAR)*(wcslen(pwszName)+1); //if FALSE==fToAllocate, we do not allocate the memory on user's //behalf; otherwize, allocate memory to eliminate the need for //double call if(FALSE==fToAllocate) { if(NULL==(*ppbBuffer)) { *pcbBuffer=dwSize; fResult=TRUE; goto CommonReturn; } if(*pcbBuffer < dwSize) { *pcbBuffer=dwSize; goto MoreDataError; } memcpy(*ppbBuffer, pwszName, dwSize); *pcbBuffer=dwSize; } else { *ppbBuffer=malloc(dwSize); if(NULL==(*ppbBuffer)) goto MemoryError; memcpy(*ppbBuffer, pwszName, dwSize); //pcbBuffer can be NULL in this case } } else { //we need to parse the string to make the multiple format if(!GetCertNameMulti(pwszName, idsPreFix, &pwszMulti)) goto GetCertNameError; //calculate the bytes needee dwSize=sizeof(WCHAR)*(wcslen(pwszMulti)+1); //if FALSE==fToAllocate, we do not allocate the memory on user's //behalf; otherwize, allocate memory to eliminate the need for //double call if(FALSE==fToAllocate) { if(NULL==(*ppbBuffer)) { *pcbBuffer=dwSize; fResult=TRUE; goto CommonReturn; } if(*pcbBuffer < dwSize) { *pcbBuffer=dwSize; goto MoreDataError; } memcpy(*ppbBuffer, pwszMulti, dwSize); *pcbBuffer=dwSize; } else { *ppbBuffer=malloc(dwSize); if(NULL==(*ppbBuffer)) goto MemoryError; memcpy(*ppbBuffer, pwszMulti, dwSize); //pcbBuffer can be NULL in this case } } fResult=TRUE; CommonReturn: if(pwszName) free(pwszName); if(pwszMulti) free(pwszMulti); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(CertNameToStrError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(GetCertNameError); } //-------------------------------------------------------------------------- // // FormatBasicConstraints2: szOID_BASIC_CONSTRAINTS2 // X509_BASIC_CONSTRAINTS2 //-------------------------------------------------------------------------- static BOOL WINAPI FormatBasicConstraints2( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; WCHAR wszSubject[SUBJECT_SIZE]; WCHAR wszNone[NONE_SIZE]; PCERT_BASIC_CONSTRAINTS2_INFO pInfo=NULL; DWORD cbNeeded=0; BOOL fResult=FALSE; UINT idsSub=0; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_BASIC_CONSTRAINTS2, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //load the string for the subjectType if (pInfo->fCA) idsSub=IDS_SUB_CA; else idsSub=IDS_SUB_EE; if(!LoadStringU(hFrmtFuncInst,idsSub, wszSubject, sizeof(wszSubject)/sizeof(wszSubject[0]))) goto LoadStringError; if (pInfo->fPathLenConstraint) { //decide between signle line and multi line display if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsSub=IDS_BASIC_CONS2_PATH_MULTI; else idsSub=IDS_BASIC_CONS2_PATH; if(!FormatMessageUnicode(&pwszFormat,idsSub, wszSubject, pInfo->dwPathLenConstraint)) goto FormatMsgError; } else { if(!LoadStringU(hFrmtFuncInst,IDS_NONE, wszNone, sizeof(wszNone)/sizeof(wszNone[0]))) goto LoadStringError; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsSub=IDS_BASIC_CONS2_NONE_MULTI; else idsSub=IDS_BASIC_CONS2_NONE; if(!FormatMessageUnicode(&pwszFormat,idsSub, wszSubject, wszNone)) goto FormatMsgError; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszFormat) LocalFree((HLOCAL)pwszFormat); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // FormatSPCObject: // // idsPreFix is the pre fix for mulit-line display //-------------------------------------------------------------------------- BOOL FormatSPCObject( DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, UINT idsPreFix, PSPC_SERIALIZED_OBJECT pInfo, LPWSTR *ppwszFormat) { BOOL fResult=FALSE; LPWSTR pwszHex=NULL; LPWSTR pwszClassId=NULL; WCHAR wszPreFix[PRE_FIX_SIZE]; DWORD cbNeeded=0; LPWSTR pwszClassFormat=NULL; LPWSTR pwszDataFormat=NULL; LPWSTR pwszTemp; assert(pInfo); *ppwszFormat=NULL; //load the pre-dix if(0!=idsPreFix) { if(!LoadStringU(hFrmtFuncInst, idsPreFix, wszPreFix, sizeof(wszPreFix)/sizeof(wszPreFix[0]))) goto LoadStringError; } cbNeeded=0; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->ClassId, 16, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszClassId=(LPWSTR)malloc(cbNeeded); if(NULL==pwszClassId) goto MemoryError; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->ClassId, 16, pwszClassId, &cbNeeded)) goto FormatBytesToHexError; //format if(!FormatMessageUnicode(&pwszClassFormat, IDS_SPC_OBJECT_CLASS, pwszClassId)) goto FormatMsgError; //strcat *ppwszFormat=(LPWSTR)malloc(sizeof(WCHAR) * (wcslen(pwszClassFormat)+wcslen(wszPreFix)+wcslen(wszCOMMA)+1)); if(NULL==*ppwszFormat) goto MemoryError; **ppwszFormat=L'\0'; if(0!=idsPreFix) wcscat(*ppwszFormat, wszPreFix); wcscat(*ppwszFormat, pwszClassFormat); //format based on the availability of SerializedData if(0!=pInfo->SerializedData.cbData) { //cancatenate the ", " or \n" if(NULL != (*ppwszFormat)) { if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwszFormat, wszCRLF); else wcscat(*ppwszFormat, wszCOMMA); } cbNeeded=0; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->SerializedData.pbData, pInfo->SerializedData.cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszHex=(LPWSTR)malloc(cbNeeded); if(NULL==pwszHex) goto MemoryError; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->SerializedData.pbData, pInfo->SerializedData.cbData, pwszHex, &cbNeeded)) goto FormatBytesToHexError; if(!FormatMessageUnicode(&pwszDataFormat, IDS_SPC_OBJECT_DATA,pwszHex)) goto FormatMsgError; //strcat #if (0) // DSIE: Bug 27436 *ppwszFormat=(LPWSTR)realloc(*ppwszFormat, sizeof(WCHAR)* (wcslen(*ppwszFormat)+wcslen(pwszDataFormat)+wcslen(wszPreFix)+1)); if(NULL==*ppwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(*ppwszFormat, sizeof(WCHAR)* (wcslen(*ppwszFormat)+wcslen(pwszDataFormat)+wcslen(wszPreFix)+1)); if(NULL==pwszTemp) goto MemoryError; *ppwszFormat = pwszTemp; if(0!=idsPreFix) wcscat(*ppwszFormat, wszPreFix); wcscat(*ppwszFormat, pwszDataFormat); } fResult=TRUE; CommonReturn: if(pwszHex) free(pwszHex); if(pwszClassId) free(pwszClassId); if(pwszClassFormat) LocalFree((HLOCAL)pwszClassFormat); if(pwszDataFormat) LocalFree((HLOCAL)pwszDataFormat); return fResult; ErrorReturn: if(*ppwszFormat) { free(*ppwszFormat); *ppwszFormat=NULL; } fResult=FALSE; goto CommonReturn; TRACE_ERROR(FormatBytesToHexError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatMsgError); TRACE_ERROR(LoadStringError); } //-------------------------------------------------------------------------- // // FormatSPCLink: //-------------------------------------------------------------------------- BOOL FormatSPCLink( DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, UINT idsPreFix, PSPC_LINK pInfo, LPWSTR *ppwsz) { BOOL fResult=FALSE; LPWSTR pwszObj=NULL; UINT ids=0; LPWSTR pwszFormat=NULL; assert(pInfo); *ppwsz=NULL; switch(pInfo->dwLinkChoice) { case SPC_URL_LINK_CHOICE: if(!FormatMessageUnicode(&pwszFormat, IDS_SPC_URL_LINK,pInfo->pwszUrl)) goto FormatMsgError; break; case SPC_MONIKER_LINK_CHOICE: if(!FormatSPCObject( dwFormatType, dwFormatStrType, pFormatStruct, idsPreFix, &(pInfo->Moniker), &pwszObj)) goto FormatSPCObjectError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_SPC_MONIKER_LINK_MULTI; else ids=IDS_SPC_MONIKER_LINK; if(!FormatMessageUnicode(&pwszFormat,ids,pwszObj)) goto FormatMsgError; break; case SPC_FILE_LINK_CHOICE: if(!FormatMessageUnicode(&pwszFormat, IDS_SPC_FILE_LINK, pInfo->pwszFile)) goto FormatMsgError; break; default: if(!FormatMessageUnicode(&pwszFormat, IDS_SPC_LINK_UNKNOWN, pInfo->dwLinkChoice)) goto FormatMsgError; } *ppwsz=(LPWSTR)malloc(sizeof(WCHAR) * (wcslen(pwszFormat)+1)); if(NULL==(*ppwsz)) goto MemoryError; memcpy(*ppwsz, pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+1)); fResult=TRUE; CommonReturn: if(pwszObj) free(pwszObj); if(pwszFormat) LocalFree((HLOCAL)pwszFormat); return fResult; ErrorReturn: if(*ppwsz) { free(*ppwsz); *ppwsz=NULL; } fResult=FALSE; goto CommonReturn; TRACE_ERROR(FormatMsgError); TRACE_ERROR(FormatSPCObjectError); SET_ERROR(MemoryError, E_OUTOFMEMORY); } //-------------------------------------------------------------------------- // // FormatSPCImage: //-------------------------------------------------------------------------- BOOL FormatSPCImage( DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, UINT idsPreFix, PSPC_IMAGE pInfo, LPWSTR *ppwszImageFormat) { BOOL fResult=FALSE; LPWSTR pwszFormat=NULL; LPWSTR pwszLink=NULL; LPWSTR pwszLinkFormat=NULL; LPWSTR pwszHex=NULL; LPWSTR pwszHexFormat=NULL; UINT ids=0; DWORD cbNeeded=0; LPWSTR pwszTemp; assert(pInfo); //init *ppwszImageFormat=NULL; pwszFormat=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwszFormat) goto MemoryError; *pwszFormat=L'\0'; if(pInfo->pImageLink) { if(!FormatSPCLink(dwFormatType, dwFormatStrType, pFormatStruct, idsPreFix, pInfo->pImageLink, &pwszLink)) goto FormatSPCLinkError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_IMAGE_LINK_MULTI; else ids=IDS_IMAGE_LINK; if(!FormatMessageUnicode(&pwszLinkFormat, ids, &pwszLink)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszCOMMA)+wcslen(pwszLinkFormat)+1)); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszCOMMA)+wcslen(pwszLinkFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, pwszLinkFormat); } if(0!=pInfo->Bitmap.cbData) { //strcat ", " if(0!=wcslen(pwszFormat)) { if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwszFormat, wszCOMMA); } cbNeeded=0; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->Bitmap.pbData, pInfo->Bitmap.cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszHex=(LPWSTR)malloc(cbNeeded); if(NULL==pwszHex) goto MemoryError; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->Bitmap.pbData, pInfo->Bitmap.cbData, pwszHex, &cbNeeded)) goto FormatBytesToHexError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_IMAGE_BITMAP_MULTI; else ids=IDS_IMAGE_BITMAP; if(!FormatMessageUnicode(&pwszHexFormat, ids, pwszHex)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszCOMMA)+wcslen(pwszHexFormat)+1)); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszCOMMA)+wcslen(pwszHexFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, pwszHexFormat); //free memory free(pwszHex); pwszHex=NULL; LocalFree((HLOCAL)pwszHexFormat); pwszHexFormat=NULL; } if(0!=pInfo->Metafile.cbData) { //strcat ", " if(0!=wcslen(pwszFormat)) { if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwszFormat, wszCOMMA); } cbNeeded=0; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->Metafile.pbData, pInfo->Metafile.cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszHex=(LPWSTR)malloc(cbNeeded); if(NULL==pwszHex) goto MemoryError; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->Metafile.pbData, pInfo->Metafile.cbData, pwszHex, &cbNeeded)) goto FormatBytesToHexError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_IMAGE_METAFILE_MULTI; else ids=IDS_IMAGE_METAFILE; if(!FormatMessageUnicode(&pwszHexFormat, ids, pwszHex)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) *(wcslen(pwszFormat)+wcslen(wszCOMMA)+wcslen(pwszHexFormat)+1)); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) *(wcslen(pwszFormat)+wcslen(wszCOMMA)+wcslen(pwszHexFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, pwszHexFormat); //free memory free(pwszHex); pwszHex=NULL; LocalFree((HLOCAL)pwszHexFormat); pwszHexFormat=NULL; } if(0!=pInfo->EnhancedMetafile.cbData) { //strcat ", " if(0!=wcslen(pwszFormat)) { if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwszFormat, wszCOMMA); } cbNeeded=0; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->EnhancedMetafile.pbData, pInfo->EnhancedMetafile.cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszHex=(LPWSTR)malloc(cbNeeded); if(NULL==pwszHex) goto MemoryError; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->EnhancedMetafile.pbData, pInfo->EnhancedMetafile.cbData, pwszHex, &cbNeeded)) goto FormatBytesToHexError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_IMAGE_ENHANCED_METAFILE_MULTI; else ids=IDS_IMAGE_ENHANCED_METAFILE; if(!FormatMessageUnicode(&pwszHexFormat, ids, pwszHex)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) *(wcslen(pwszFormat)+wcslen(wszCOMMA)+wcslen(pwszHexFormat)+1)); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) *(wcslen(pwszFormat)+wcslen(wszCOMMA)+wcslen(pwszHexFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, pwszHexFormat); //free memory free(pwszHex); pwszHex=NULL; LocalFree((HLOCAL)pwszHexFormat); pwszHexFormat=NULL; } if(0!=pInfo->GifFile.cbData) { //strcat ", " if(0!=wcslen(pwszFormat)) { if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwszFormat, wszCOMMA); } cbNeeded=0; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->GifFile.pbData, pInfo->GifFile.cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszHex=(LPWSTR)malloc(cbNeeded); if(NULL==pwszHex) goto MemoryError; if(!FormatBytesToHex( 0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->GifFile.pbData, pInfo->GifFile.cbData, pwszHex, &cbNeeded)) goto FormatBytesToHexError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_IMAGE_GIFFILE_MULTI; else ids=IDS_IMAGE_GIFFILE; if(!FormatMessageUnicode(&pwszHexFormat, IDS_IMAGE_GIFFILE, pwszHex)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) *(wcslen(pwszFormat)+wcslen(wszCOMMA)+wcslen(pwszHexFormat)+1)); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) *(wcslen(pwszFormat)+wcslen(wszCOMMA)+wcslen(pwszHexFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, pwszHexFormat); //free memory free(pwszHex); pwszHex=NULL; LocalFree((HLOCAL)pwszHexFormat); pwszHexFormat=NULL; } if(0==wcslen(pwszFormat)) { //fine if nothing is formatted *ppwszImageFormat=NULL; } else { *ppwszImageFormat=(LPWSTR)malloc(sizeof(WCHAR)*(wcslen(pwszFormat)+1)); #if (0) // DSIE: Bug 27432 & 27434 if(NULL == ppwszImageFormat) #endif if(NULL == *ppwszImageFormat) goto MemoryError; memcpy(*ppwszImageFormat, pwszFormat, sizeof(WCHAR)*(wcslen(pwszFormat)+1)); } fResult=TRUE; CommonReturn: if(pwszHex) free(pwszHex); if(pwszHexFormat) LocalFree((HLOCAL)pwszHexFormat); if(pwszLink) free(pwszLink); if(pwszLinkFormat) LocalFree((HLOCAL)pwszLinkFormat); if(pwszFormat) free(pwszFormat); return fResult; ErrorReturn: if(*ppwszImageFormat) { free(*ppwszImageFormat); *ppwszImageFormat=NULL; } fResult=FALSE; goto CommonReturn; TRACE_ERROR(FormatSPCLinkError); TRACE_ERROR(FormatMsgError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatBytesToHexError); } //-------------------------------------------------------------------------- // // FormatSPAgencyInfo: SPC_SP_AGENCY_INFO_STRUCT // SPC_SP_AGENCY_INFO_OBJID //-------------------------------------------------------------------------- static BOOL WINAPI FormatSPAgencyInfo( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; PSPC_SP_AGENCY_INFO pInfo=NULL; LPWSTR pwszPolicyInfo=NULL; LPWSTR pwszPolicyInfoFormat=NULL; LPWSTR pwszLogoLink=NULL; LPWSTR pwszLogoLinkFormat=NULL; LPWSTR pwszPolicyDsplyFormat=NULL; LPWSTR pwszLogoImage=NULL; LPWSTR pwszLogoImageFormat=NULL; DWORD cbNeeded=0; BOOL fResult=FALSE; UINT ids=0; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,SPC_SP_AGENCY_INFO_STRUCT, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; //format pPolicyInformation if(pInfo->pPolicyInformation) { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_TWO_TABS; else ids=0; if(!FormatSPCLink(dwFormatType, dwFormatStrType, pFormatStruct, ids, pInfo->pPolicyInformation, &pwszPolicyInfo)) goto FormatSPCLinkError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_AGENCY_POLICY_INFO_MULTI; else ids=IDS_AGENCY_POLICY_INFO; if(!FormatMessageUnicode(&pwszPolicyInfoFormat, ids, pwszPolicyInfo)) goto FormatMsgError; //strcat #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) *(wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszPolicyInfoFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) *(wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszPolicyInfoFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszPolicyInfoFormat); } //format pwszPolicyDisplayText if(pInfo->pwszPolicyDisplayText) { //strcat ", " if(0!=wcslen(pwsz)) { if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_AGENCY_POLICY_DSPLY_MULTI; else ids=IDS_AGENCY_POLICY_DSPLY; if(!FormatMessageUnicode(&pwszPolicyDsplyFormat, ids, pInfo->pwszPolicyDisplayText)) goto FormatMsgError; //strcat #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) *(wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszPolicyDsplyFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) *(wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszPolicyDsplyFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszPolicyDsplyFormat); } //pLogoImage if(pInfo->pLogoImage) { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_THREE_TABS; else ids=0; if(!FormatSPCImage(dwFormatType, dwFormatStrType, pFormatStruct, ids, pInfo->pLogoImage, &pwszLogoImage)) goto FormatSPCImageError; //spcImage can include nothing if(NULL!=pwszLogoImage) { //strcat ", " if(0!=wcslen(pwsz)) { if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_AGENCY_LOGO_IMAGE_MULTI; else ids=IDS_AGENCY_LOGO_IMAGE; if(!FormatMessageUnicode(&pwszLogoImageFormat,ids,pwszLogoImage)) goto FormatMsgError; //strcat #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) *(wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszLogoImageFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) *(wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszLogoImageFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszLogoImageFormat); } } //format pLogoLink if(pInfo->pLogoLink) { //strcat ", " if(0!=wcslen(pwsz)) { if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_TWO_TABS; else ids=0; if(!FormatSPCLink(dwFormatType, dwFormatStrType, pFormatStruct, ids, pInfo->pLogoLink, &pwszLogoLink)) goto FormatSPCLinkError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_AGENCY_LOGO_LINK_MULTI; else ids=IDS_AGENCY_LOGO_LINK; if(!FormatMessageUnicode(&pwszLogoLinkFormat, ids, pwszLogoLink)) goto FormatMsgError; //strcat #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszLogoLinkFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszLogoLinkFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszLogoLinkFormat); } if(0==wcslen(pwsz)) { //no data pwszFormat=(LPWSTR)malloc((NO_INFO_SIZE+1)*sizeof(WCHAR)); if(NULL==pwszFormat) goto MemoryError; if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, pwszFormat, NO_INFO_SIZE)) goto LoadStringError; } else { pwszFormat=pwsz; pwsz=NULL; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszPolicyInfo) free(pwszPolicyInfo); if(pwszPolicyInfoFormat) LocalFree((HLOCAL)pwszPolicyInfoFormat); if(pwszLogoLink) free(pwszLogoLink); if(pwszLogoLinkFormat) LocalFree((HLOCAL)pwszLogoLinkFormat); if(pwszPolicyDsplyFormat) LocalFree((HLOCAL)pwszPolicyDsplyFormat); if(pwszLogoImage) free(pwszLogoImage); if(pwszLogoImageFormat) LocalFree((HLOCAL)pwszLogoImageFormat); if(pwszFormat) free(pwszFormat); if(pwsz) free(pwsz); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatSPCLinkError); TRACE_ERROR(FormatSPCImageError); } //-------------------------------------------------------------------------- // // GetNoticeNumberString: // // The memory should be allocated via malloc //-------------------------------------------------------------------------- BOOL WINAPI GetNoticeNumberString( DWORD cNoticeNumbers, int *rgNoticeNumbers, LPWSTR *ppwszNumber) { BOOL fResult=FALSE; WCHAR wszNumber[INT_SIZE]; DWORD dwIndex=0; LPWSTR pwszTemp; *ppwszNumber=NULL; if(NULL==rgNoticeNumbers || 0==cNoticeNumbers) goto InvalidArg; *ppwszNumber=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==*ppwszNumber) goto MemoryError; **ppwszNumber=L'\0'; for(dwIndex=0; dwIndex<cNoticeNumbers; dwIndex++) { wszNumber[0]='\0'; _itow(rgNoticeNumbers[dwIndex], wszNumber, 10); if(wcslen(wszNumber) > 0) { #if (0) // DSIE: Bug 27436 *ppwszNumber=(LPWSTR)realloc(*ppwszNumber, sizeof(WCHAR)*(wcslen(*ppwszNumber)+wcslen(wszNumber)+wcslen(wszCOMMA)+1)); if(NULL==*ppwszNumber) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(*ppwszNumber, sizeof(WCHAR)*(wcslen(*ppwszNumber)+wcslen(wszNumber)+wcslen(wszCOMMA)+1)); if(NULL==pwszTemp) goto MemoryError; *ppwszNumber = pwszTemp; wcscat(*ppwszNumber, wszNumber); if(dwIndex != (cNoticeNumbers-1)) wcscat(*ppwszNumber, wszCOMMA); } } if(0==wcslen(*ppwszNumber)) goto InvalidArg; fResult=TRUE; CommonReturn: return fResult; ErrorReturn: if(*ppwszNumber) { free(*ppwszNumber); *ppwszNumber=NULL; } fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); SET_ERROR(MemoryError, E_OUTOFMEMORY); } //-------------------------------------------------------------------------- // // FormatCertQualifier: // // The memory should be allocated via malloc //-------------------------------------------------------------------------- BOOL FormatPolicyUserNotice( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, UINT idsPreFix, BYTE *pbEncoded, DWORD cbEncoded, LPWSTR *ppwsz) { BOOL fResult=FALSE; WCHAR wszNoInfo[NO_INFO_SIZE]; WCHAR wszPreFix[PREFIX_SIZE]; WCHAR wszNextPre[PREFIX_SIZE]; WCHAR wszText[SUBJECT_SIZE]; BOOL fComma=FALSE; CERT_POLICY_QUALIFIER_USER_NOTICE *pInfo=NULL; LPWSTR pwszOrg=NULL; LPWSTR pwszNumber=NULL; LPWSTR pwszTemp; *ppwsz=NULL; if (!DecodeGenericBLOB(dwCertEncodingType, szOID_PKIX_POLICY_QUALIFIER_USERNOTICE, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; if(!LoadStringU(hFrmtFuncInst,idsPreFix, wszPreFix, sizeof(wszPreFix)/sizeof(wszPreFix[0]))) goto LoadStringError; if(!LoadStringU(hFrmtFuncInst,idsPreFix+1, wszNextPre, sizeof(wszNextPre)/sizeof(wszNextPre[0]))) goto LoadStringError; if(NULL == pInfo->pNoticeReference && NULL == pInfo->pszDisplayText) { //load the string "Info Not Available" if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, wszNoInfo, sizeof(wszNoInfo)/sizeof(wszNoInfo[0]))) goto LoadStringError; *ppwsz=(LPWSTR)malloc(sizeof(WCHAR) * (wcslen(wszNoInfo) + wcslen(wszPreFix) + POSTFIX_SIZE + 1)); if(NULL==*ppwsz) goto MemoryError; **ppwsz=L'\0'; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwsz, wszPreFix); wcscat(*ppwsz, wszNoInfo); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwsz, wszCRLF); } else { *ppwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==*ppwsz) goto MemoryError; **ppwsz=L'\0'; if(pInfo->pNoticeReference) { if(!LoadStringU(hFrmtFuncInst,IDS_USER_NOTICE_REF, wszText, sizeof(wszText)/sizeof(wszText[0]))) goto LoadStringError; #if (0) // DSIE: Bug 27436 *ppwsz=(LPWSTR)realloc(*ppwsz, sizeof(WCHAR) * (wcslen(*ppwsz)+wcslen(wszText)+wcslen(wszPreFix)+POSTFIX_SIZE+1)); if(NULL==*ppwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(*ppwsz, sizeof(WCHAR) * (wcslen(*ppwsz)+wcslen(wszText)+wcslen(wszPreFix)+POSTFIX_SIZE+1)); if(NULL==pwszTemp) goto MemoryError; *ppwsz = pwszTemp; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwsz, wszPreFix); wcscat(*ppwsz, wszText); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwsz, wszCRLF); if(pInfo->pNoticeReference->pszOrganization) { if(S_OK!=SZtoWSZ(pInfo->pNoticeReference->pszOrganization, &pwszOrg)) goto SZtoWSZError; if(!LoadStringU(hFrmtFuncInst,IDS_USER_NOTICE_REF_ORG, wszText, sizeof(wszText)/sizeof(wszText[0]))) goto LoadStringError; #if (0) // DSIE: Bug 27436 *ppwsz=(LPWSTR)realloc(*ppwsz, sizeof(WCHAR) * (wcslen(*ppwsz)+wcslen(wszText)+wcslen(pwszOrg)+wcslen(wszNextPre)+POSTFIX_SIZE+1)); if(NULL==*ppwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(*ppwsz, sizeof(WCHAR) * (wcslen(*ppwsz)+wcslen(wszText)+wcslen(pwszOrg)+wcslen(wszNextPre)+POSTFIX_SIZE+1)); if(NULL==pwszTemp) goto MemoryError; *ppwsz = pwszTemp; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwsz, wszNextPre); wcscat(*ppwsz, wszText); wcscat(*ppwsz, pwszOrg); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwsz, wszCRLF); else { wcscat(*ppwsz, wszCOMMA); fComma=TRUE; } } if(pInfo->pNoticeReference->cNoticeNumbers) { if(NULL == pInfo->pNoticeReference->rgNoticeNumbers) goto InvalidArg; if(!GetNoticeNumberString(pInfo->pNoticeReference->cNoticeNumbers, pInfo->pNoticeReference->rgNoticeNumbers, &pwszNumber)) goto GetNumberError; if(!LoadStringU(hFrmtFuncInst,IDS_USER_NOTICE_REF_NUMBER, wszText, sizeof(wszText)/sizeof(wszText[0]))) goto LoadStringError; #if (0) // DSIE: Bug 27436 *ppwsz=(LPWSTR)realloc(*ppwsz, sizeof(WCHAR) * (wcslen(*ppwsz)+wcslen(wszText)+wcslen(pwszNumber)+wcslen(wszNextPre)+POSTFIX_SIZE+1)); if(NULL==*ppwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(*ppwsz, sizeof(WCHAR) * (wcslen(*ppwsz)+wcslen(wszText)+wcslen(pwszNumber)+wcslen(wszNextPre)+POSTFIX_SIZE+1)); if(NULL==pwszTemp) goto MemoryError; *ppwsz = pwszTemp; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwsz, wszNextPre); wcscat(*ppwsz, wszText); wcscat(*ppwsz, pwszNumber); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwsz, wszCRLF); else { wcscat(*ppwsz, wszCOMMA); fComma=TRUE; } } } if(pInfo->pszDisplayText) { if(!LoadStringU(hFrmtFuncInst,IDS_USER_NOTICE_TEXT, wszText, sizeof(wszText)/sizeof(wszText[0]))) goto LoadStringError; #if (0) // DSIE: Bug 27436 *ppwsz=(LPWSTR)realloc(*ppwsz, sizeof(WCHAR) * (wcslen(*ppwsz)+wcslen(wszText)+wcslen(pInfo->pszDisplayText)+wcslen(wszPreFix)+POSTFIX_SIZE+1)); if(NULL==*ppwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(*ppwsz, sizeof(WCHAR) * (wcslen(*ppwsz)+wcslen(wszText)+wcslen(pInfo->pszDisplayText)+wcslen(wszPreFix)+POSTFIX_SIZE+1)); if(NULL==pwszTemp) goto MemoryError; *ppwsz = pwszTemp; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwsz, wszPreFix); wcscat(*ppwsz, wszText); wcscat(*ppwsz, pInfo->pszDisplayText); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwsz, wszCRLF); else { wcscat(*ppwsz, wszCOMMA); fComma=TRUE; } } //get rid of the last comma if(fComma) *(*ppwsz+wcslen(*ppwsz)-wcslen(wszCOMMA))=L'\0'; } fResult=TRUE; CommonReturn: if(pInfo) free(pInfo); if(pwszOrg) free(pwszOrg); if(pwszNumber) free(pwszNumber); return fResult; ErrorReturn: if(*ppwsz) { free(*ppwsz); *ppwsz=NULL; } fResult=FALSE; goto CommonReturn; TRACE_ERROR(LoadStringError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(SZtoWSZError); TRACE_ERROR(GetNumberError); SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); } //-------------------------------------------------------------------------- // // FormatCertQualifier: //-------------------------------------------------------------------------- BOOL FormatCertQualifier( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, PCERT_POLICY_QUALIFIER_INFO pInfo, LPWSTR *ppwszFormat) { BOOL fResult=FALSE; DWORD cbNeeded=0; UINT ids=0; PCCRYPT_OID_INFO pOIDInfo=NULL; LPWSTR pwszName=NULL; LPWSTR pwszElement=NULL; LPWSTR pwszOID=NULL; *ppwszFormat=NULL; //get the oid name pOIDInfo=CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, pInfo->pszPolicyQualifierId, 0); if(NULL == pOIDInfo) { if(S_OK!=SZtoWSZ(pInfo->pszPolicyQualifierId, &pwszOID)) goto SZtoWSZError; } if(pInfo->Qualifier.cbData) { if(0==strcmp(szOID_PKIX_POLICY_QUALIFIER_CPS, pInfo->pszPolicyQualifierId)) { //this is just a unicode format //turn off the multi line here cbNeeded=0; if(!FormatAnyUnicodeStringExtension( dwCertEncodingType, dwFormatType, dwFormatStrType & (~CRYPT_FORMAT_STR_MULTI_LINE), pFormatStruct, pInfo->pszPolicyQualifierId, pInfo->Qualifier.pbData, pInfo->Qualifier.cbData, NULL, &cbNeeded)) goto FormatUnicodeError; pwszName=(LPWSTR)malloc(cbNeeded); if(NULL==pwszName) goto MemoryError; if(!FormatAnyUnicodeStringExtension( dwCertEncodingType, dwFormatType, dwFormatStrType & (~CRYPT_FORMAT_STR_MULTI_LINE), pFormatStruct, pInfo->pszPolicyQualifierId, pInfo->Qualifier.pbData, pInfo->Qualifier.cbData, pwszName, &cbNeeded)) goto FormatUnicodeError; } else { if(0==strcmp(szOID_PKIX_POLICY_QUALIFIER_USERNOTICE,pInfo->pszPolicyQualifierId)) { //this is yet another struct to format. We remember to have //a 3 tab prefix if(!FormatPolicyUserNotice( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, IDS_THREE_TABS, pInfo->Qualifier.pbData, pInfo->Qualifier.cbData, &pwszName)) goto FormatUserNoticdeError; } else { //get the Hex dump of the Key Usage cbNeeded=0; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->Qualifier.pbData, pInfo->Qualifier.cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszName=(LPWSTR)malloc(cbNeeded); if(NULL==pwszName) goto MemoryError; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->Qualifier.pbData, pInfo->Qualifier.cbData, pwszName, &cbNeeded)) goto FormatBytesToHexError; } } //add the desired 3 tab prefix and new line for CSP and the new line //for the multi line case if((dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) && (0!=strcmp(szOID_PKIX_POLICY_QUALIFIER_USERNOTICE,pInfo->pszPolicyQualifierId))) { if(!FormatMessageUnicode(&pwszElement, IDS_POLICY_QUALIFIER_ELEMENT, pwszName)) goto FormatMsgError; } //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_POLICY_QUALIFIER_MULTI; else ids=IDS_POLICY_QUALIFIER; if(!FormatMessageUnicode(ppwszFormat, ids, pOIDInfo? pOIDInfo->pwszName : pwszOID, pwszElement? pwszElement : pwszName)) goto FormatMsgError; } else { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_POLICY_QUALIFIER_NO_BLOB_MULTI; else ids=IDS_POLICY_QUALIFIER_NO_BLOB; if(!FormatMessageUnicode(ppwszFormat, ids, pOIDInfo? pOIDInfo->pwszName : pwszOID)) goto FormatMsgError; } fResult=TRUE; CommonReturn: if(pwszName) free(pwszName); if(pwszElement) LocalFree((HLOCAL)pwszElement); if(pwszOID) free(pwszOID); return fResult; ErrorReturn: if(*ppwszFormat) { LocalFree((HLOCAL)(*ppwszFormat)); *ppwszFormat=NULL; } fResult=FALSE; goto CommonReturn; TRACE_ERROR(FormatBytesToHexError); TRACE_ERROR(FormatMsgError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatUnicodeError); TRACE_ERROR(FormatUserNoticdeError); TRACE_ERROR(SZtoWSZError); } //-------------------------------------------------------------------------- // // FormatCertPolicies: X509_CERT_POLICIES // szOID_CERT_POLICIES // szOID_APPLICATION_CERT_POLICIES // //-------------------------------------------------------------------------- static BOOL WINAPI FormatCertPolicies( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; LPWSTR pwszPolicyFormat=NULL; LPWSTR pwszQualifiers=NULL; LPWSTR pwszQualifierFormat=NULL; LPWSTR pwszOneQualifier=NULL; LPWSTR pwszOID=NULL; PCERT_POLICIES_INFO pInfo=NULL; PCERT_POLICY_INFO pPolicyInfo=NULL; DWORD dwIndex=0; DWORD dwQualifierIndex=0; DWORD cbNeeded=0; BOOL fResult=FALSE; UINT ids=0; PCCRYPT_OID_INFO pOIDInfo=NULL; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_CERT_POLICIES, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; for(dwIndex=0; dwIndex < pInfo->cPolicyInfo; dwIndex++) { //strcat ", " if(0!=wcslen(pwsz)) { if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } pPolicyInfo=&(pInfo->rgPolicyInfo[dwIndex]); pwszQualifiers=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwszQualifiers) goto MemoryError; *pwszQualifiers=L'\0'; //format the qualifiers for(dwQualifierIndex=0; dwQualifierIndex < pPolicyInfo->cPolicyQualifier; dwQualifierIndex++) { //strcat ", " if(0!=wcslen(pwszQualifiers)) { if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwszQualifiers, wszCOMMA); } if(!FormatCertQualifier(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, &(pPolicyInfo->rgPolicyQualifier[dwQualifierIndex]), &pwszOneQualifier)) goto FormatCertQualifierError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_POLICY_QUALIFIER_INFO_MULTI; else ids=IDS_POLICY_QUALIFIER_INFO; //format if(!FormatMessageUnicode(&pwszQualifierFormat,ids, dwIndex+1, dwQualifierIndex+1, pwszOneQualifier)) goto FormatMsgError; //strcat #if (0) // DSIE: Bug 27436 pwszQualifiers=(LPWSTR)realloc(pwszQualifiers, sizeof(WCHAR) * (wcslen(pwszQualifiers)+wcslen(wszCOMMA)+wcslen(pwszQualifierFormat)+1)); if(NULL==pwszQualifiers) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszQualifiers, sizeof(WCHAR) * (wcslen(pwszQualifiers)+wcslen(wszCOMMA)+wcslen(pwszQualifierFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwszQualifiers = pwszTemp; wcscat(pwszQualifiers, pwszQualifierFormat); LocalFree((HLOCAL)pwszOneQualifier); pwszOneQualifier=NULL; LocalFree((HLOCAL)pwszQualifierFormat); pwszQualifierFormat=NULL; } //now, format the certPolicyInfo pOIDInfo=CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, pPolicyInfo->pszPolicyIdentifier, 0); if(NULL == pOIDInfo) { if(S_OK!=SZtoWSZ(pPolicyInfo->pszPolicyIdentifier, &pwszOID)) goto SZtoWSZError; } if(0!=pPolicyInfo->cPolicyQualifier) { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) if (0 == strcmp(lpszStructType, szOID_CERT_POLICIES)) ids=IDS_CERT_POLICY_MULTI; else ids=IDS_APPLICATION_CERT_POLICY_MULTI; else if (0 == strcmp(lpszStructType, szOID_CERT_POLICIES)) ids=IDS_CERT_POLICY; else ids=IDS_APPLICATION_CERT_POLICY; if(!FormatMessageUnicode(&pwszPolicyFormat,ids, dwIndex+1, pOIDInfo? pOIDInfo->pwszName : pwszOID, pwszQualifiers)) goto FormatMsgError; } else { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) if (0 == strcmp(lpszStructType, szOID_CERT_POLICIES)) ids=IDS_CERT_POLICY_NO_QUA_MULTI; else ids=IDS_APPLICATION_CERT_POLICY_NO_QUA_MULTI; else if (0 == strcmp(lpszStructType, szOID_CERT_POLICIES)) ids=IDS_CERT_POLICY_NO_QUA; else ids=IDS_APPLICATION_CERT_POLICY_NO_QUA; if(!FormatMessageUnicode(&pwszPolicyFormat, ids, dwIndex+1, pOIDInfo? pOIDInfo->pwszName : pwszOID)) goto FormatMsgError; } //strcat #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszPolicyFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszPolicyFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszPolicyFormat); free(pwszQualifiers); pwszQualifiers=NULL; LocalFree((HLOCAL)pwszPolicyFormat); pwszPolicyFormat=NULL; if(pwszOID) free(pwszOID); pwszOID=NULL; } if(0==wcslen(pwsz)) { //no data pwszFormat=(LPWSTR)malloc(sizeof(WCHAR)*(NO_INFO_SIZE+1)); if(NULL==pwszFormat) goto MemoryError; if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, pwszFormat, NO_INFO_SIZE)) goto LoadStringError; } else { pwszFormat=pwsz; pwsz=NULL; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszOID) free(pwszOID); if(pwszOneQualifier) LocalFree((HLOCAL)pwszOneQualifier); if(pwszQualifierFormat) LocalFree((HLOCAL)pwszQualifierFormat); if(pwszQualifiers) free(pwszQualifiers); if(pwszPolicyFormat) LocalFree((HLOCAL)pwszPolicyFormat); if(pwsz) free(pwsz); if(pwszFormat) free(pwszFormat); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); SET_ERROR(MemoryError,E_OUTOFMEMORY); TRACE_ERROR(FormatCertQualifierError); TRACE_ERROR(SZtoWSZError); } //-------------------------------------------------------------------------- // // FormatCAVersion: szOID_CERTSRV_CA_VERSION // Decode as X509_INTEGER // //-------------------------------------------------------------------------- static BOOL WINAPI FormatCAVersion( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult=FALSE; DWORD cbNeeded=0; UINT ids=0; DWORD dwCAVersion=0; DWORD cbCAVersion=sizeof(dwCAVersion); LPWSTR pwszFormat=NULL; //check for input parameters if((NULL==pbEncoded && 0!=cbEncoded) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if(!CryptDecodeObject(dwCertEncodingType,X509_INTEGER,pbEncoded, cbEncoded, 0,&dwCAVersion,&cbCAVersion)) goto DecodeGenericError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_CA_VERSION_MULTI; else ids=IDS_CA_VERSION; if(!FormatMessageUnicode(&pwszFormat, ids, CANAMEIDTOICERT(dwCAVersion), CANAMEIDTOIKEY(dwCAVersion))) goto FormatMsgError; cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszFormat) LocalFree((HLOCAL)pwszFormat); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // FormatNetscapeCertType: // szOID_NETSCAPE_CERT_TYPE // Decode as X509_BITS // //-------------------------------------------------------------------------- static BOOL WINAPI FormatNetscapeCertType( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult=FALSE; DWORD cbNeeded=0; WCHAR wszCertType[CERT_TYPE_SIZE+1]; FORMAT_CERT_TYPE_INFO rgCertType[]={ NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE, IDS_NETSCAPE_SSL_CLIENT_AUTH, //0x80 NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE, IDS_NETSCAPE_SSL_SERVER_AUTH, //0x40 NETSCAPE_SMIME_CERT_TYPE, IDS_NETSCAPE_SMIME, //0x20 NETSCAPE_SIGN_CERT_TYPE, IDS_NETSCAPE_SIGN, //0x10 0x08, IDS_UNKNOWN_CERT_TYPE, //0x08 NETSCAPE_SSL_CA_CERT_TYPE, IDS_NETSCAPE_SSL_CA, //0x04 NETSCAPE_SMIME_CA_CERT_TYPE, IDS_NETSCAPE_SMIME_CA, //0x02 NETSCAPE_SIGN_CA_CERT_TYPE, IDS_NETSCAPE_SIGN_CA}; //0x01 DWORD dwCertType=0; DWORD dwIndex=0; CRYPT_BIT_BLOB *pInfo=NULL; LPWSTR pwsz=NULL; LPWSTR pwszByte=NULL; LPWSTR pwszFormat=NULL; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded && 0!=cbEncoded) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if(!DecodeGenericBLOB(dwCertEncodingType,X509_BITS, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; if(0==pInfo->cbData) goto InvalidArg; pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; //the count of bits to consider dwCertType=sizeof(rgCertType)/sizeof(rgCertType[0]); //we need to consider the unused bits in the last byte if((1 == pInfo->cbData) && (8 > pInfo->cUnusedBits)) { dwCertType=8-pInfo->cUnusedBits; } for(dwIndex=0; dwIndex<dwCertType; dwIndex++) { if(pInfo->pbData[0] & rgCertType[dwIndex].bCertType) { if(!LoadStringU(hFrmtFuncInst, rgCertType[dwIndex].idsCertType, wszCertType, CERT_TYPE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCertType)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCertType)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszCertType); wcscat(pwsz, wszCOMMA); } } //there is data that we can not interpret if the bit number is more than 8 if(8 < (8 * pInfo->cbData - pInfo->cUnusedBits)) { if(!LoadStringU(hFrmtFuncInst, IDS_UNKNOWN_CERT_TYPE, wszCertType, CERT_TYPE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCertType)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCertType)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszCertType); wcscat(pwsz, wszCOMMA); } if(0==wcslen(pwsz)) { #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (CERT_TYPE_SIZE+1)); if(NULL == pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (CERT_TYPE_SIZE+1)); if(NULL == pwszTemp) goto MemoryError; pwsz = pwszTemp; if(!LoadStringU(hFrmtFuncInst, IDS_UNKNOWN_CERT_TYPE, pwsz, CERT_TYPE_SIZE)) goto LoadStringError; } else { //get rid of the last comma *(pwsz+wcslen(pwsz)-wcslen(wszCOMMA))=L'\0'; } //get the Hex dump of the cert type cbNeeded=0; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pInfo->pbData, pInfo->cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszByte=(LPWSTR)malloc(cbNeeded); if(NULL==pwszByte) goto MemoryError; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pInfo->pbData, pInfo->cbData, pwszByte, &cbNeeded)) goto FormatBytesToHexError; //convert the WSZ if(!FormatMessageUnicode(&pwszFormat, IDS_BIT_BLOB, pwsz, pwszByte)) goto FormatMsgError; cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pInfo) free(pInfo); if(pwsz) free(pwsz); if(pwszByte) free(pwszByte); if(pwszFormat) LocalFree((HLOCAL)pwszFormat); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(FormatMsgError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatBytesToHexError); TRACE_ERROR(LoadStringError); } //-------------------------------------------------------------------------- // // FormatAnyUnicodeStringExtension: // szOID_ENROLLMENT_NAME_VALUE_PAIR // Decode as szOID_ENROLLMENT_NAME_VALUE_PAIR // //-------------------------------------------------------------------------- static BOOL WINAPI FormatAnyNameValueStringAttr( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult=FALSE; DWORD cbNeeded=0; UINT ids=0; CRYPT_ENROLLMENT_NAME_VALUE_PAIR *pInfo=NULL; LPWSTR pwszFormat=NULL; //check for input parameters if((NULL==pbEncoded && 0!=cbEncoded) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,szOID_ENROLLMENT_NAME_VALUE_PAIR, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; if(NULL == pInfo->pwszName || NULL == pInfo->pwszValue) goto InvalidArg; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_NAME_VALUE_MULTI; else ids=IDS_NAME_VALUE; if(!FormatMessageUnicode(&pwszFormat, ids, pInfo->pwszName, pInfo->pwszValue)) goto FormatMsgError; cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pInfo) free(pInfo); if(pwszFormat) LocalFree((HLOCAL)pwszFormat); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // FormatAnyUnicodeStringExtension: // szOID_ENROLL_CERTTYPE_EXTENSION // szOID_NETSCAPE_REVOCATION_URL // Decode as X509_ANY_UNICODE_STRING // //-------------------------------------------------------------------------- static BOOL WINAPI FormatAnyUnicodeStringExtension( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult=FALSE; DWORD cbNeeded=0; UINT ids=0; CERT_NAME_VALUE *pInfo=NULL; LPWSTR pwszFormat=NULL; //check for input parameters if((NULL==pbEncoded && 0!=cbEncoded) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_UNICODE_ANY_STRING, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //the data can not be the encoded blob or the octect string if(!IS_CERT_RDN_CHAR_STRING(pInfo->dwValueType)) goto DecodeGenericError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_UNICODE_STRING_MULTI; else ids=IDS_UNICODE_STRING; if(!FormatMessageUnicode(&pwszFormat, ids, (LPWSTR)(pInfo->Value.pbData))) goto FormatMsgError; cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pInfo) free(pInfo); if(pwszFormat) LocalFree((HLOCAL)pwszFormat); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // FormatDistPointName: Pre-condition: dwDistPointNameChoice!=0 //-------------------------------------------------------------------------- BOOL FormatDistPointName(DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, PCRL_DIST_POINT_NAME pInfo, LPWSTR *ppwszFormat) { BOOL fResult=FALSE; DWORD cbNeeded=0; LPWSTR pwszCRLIssuer=NULL; UINT ids=0; *ppwszFormat=NULL; if(CRL_DIST_POINT_FULL_NAME==pInfo->dwDistPointNameChoice) { if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_THREE_TABS; cbNeeded=0; if(!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, ids, FALSE, &(pInfo->FullName), NULL, &cbNeeded)) goto FormatAltNameError; pwszCRLIssuer=(LPWSTR)malloc(cbNeeded); if(NULL==pwszCRLIssuer) goto MemoryError; if(!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, ids, FALSE, &(pInfo->FullName), pwszCRLIssuer, &cbNeeded)) goto FormatAltNameError; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_CRL_DIST_FULL_NAME_MULTI; else ids=IDS_CRL_DIST_FULL_NAME; if(!FormatMessageUnicode(ppwszFormat, ids,pwszCRLIssuer)) goto FormatMsgError; } else if(CRL_DIST_POINT_ISSUER_RDN_NAME==pInfo->dwDistPointNameChoice) { *ppwszFormat=(LPWSTR)malloc(sizeof(WCHAR)*(CRL_DIST_NAME_SIZE+1)); if(NULL==*ppwszFormat) goto MemoryError; if(!LoadStringU(hFrmtFuncInst, IDS_CRL_DIST_ISSUER_RDN, *ppwszFormat,CRL_DIST_NAME_SIZE)) goto LoadStringError; } else { if(!FormatMessageUnicode(ppwszFormat, IDS_DWORD, pInfo->dwDistPointNameChoice)) goto FormatMsgError; } fResult=TRUE; CommonReturn: if(pwszCRLIssuer) free(pwszCRLIssuer); return fResult; ErrorReturn: if(*ppwszFormat) { LocalFree((HLOCAL)(*ppwszFormat)); *ppwszFormat=NULL; } fResult=FALSE; goto CommonReturn; TRACE_ERROR(FormatMsgError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(LoadStringError); TRACE_ERROR(FormatAltNameError); } //-------------------------------------------------------------------------- // // FormatCRLReason: Pre-condition: pReason.cbData != 0 //-------------------------------------------------------------------------- BOOL FormatCRLReason(DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, PCRYPT_BIT_BLOB pInfo, LPWSTR *ppwszFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwszByte=NULL; WCHAR wszReason[CRL_REASON_SIZE+1]; DWORD cbNeeded=0; BOOL fResult=FALSE; LPWSTR pwszTemp; *ppwszFormat=NULL; pwszFormat=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwszFormat) goto MemoryError; *pwszFormat=L'\0'; //format the 1st byte if(pInfo->pbData[0] & CRL_REASON_UNUSED_FLAG) { if(!LoadStringU(hFrmtFuncInst, IDS_UNSPECIFIED, wszReason, CRL_REASON_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, wszReason); wcscat(pwszFormat, wszCOMMA); } if(pInfo->pbData[0] & CRL_REASON_KEY_COMPROMISE_FLAG) { if(!LoadStringU(hFrmtFuncInst, IDS_KEY_COMPROMISE, wszReason,CRL_REASON_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, wszReason); wcscat(pwszFormat, wszCOMMA); } if(pInfo->pbData[0] & CRL_REASON_CA_COMPROMISE_FLAG ) { if(!LoadStringU(hFrmtFuncInst, IDS_CA_COMPROMISE,wszReason, CRL_REASON_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, wszReason); wcscat(pwszFormat, wszCOMMA); } if(pInfo->pbData[0] & CRL_REASON_AFFILIATION_CHANGED_FLAG ) { if(!LoadStringU(hFrmtFuncInst, IDS_AFFILIATION_CHANGED, wszReason, CRL_REASON_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, wszReason); wcscat(pwszFormat, wszCOMMA); } if(pInfo->pbData[0] & CRL_REASON_SUPERSEDED_FLAG ) { if(!LoadStringU(hFrmtFuncInst, IDS_SUPERSEDED, wszReason, CRL_REASON_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, wszReason); wcscat(pwszFormat, wszCOMMA); } if(pInfo->pbData[0] & CRL_REASON_CESSATION_OF_OPERATION_FLAG ) { if(!LoadStringU(hFrmtFuncInst, IDS_CESSATION_OF_OPERATION, wszReason, CRL_REASON_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, wszReason); wcscat(pwszFormat, wszCOMMA); } if(pInfo->pbData[0] & CRL_REASON_CERTIFICATE_HOLD_FLAG ) { if(!LoadStringU(hFrmtFuncInst, IDS_CERTIFICATE_HOLD, wszReason, CRL_REASON_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszFormat) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(wszReason)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, wszReason); wcscat(pwszFormat, wszCOMMA); } if(0==wcslen(pwszFormat)) { #if (0) // DSIE: Bug 27436 pwszFormat=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (UNKNOWN_CRL_REASON_SIZE+1)); #endif pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (UNKNOWN_CRL_REASON_SIZE+1)); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; if(!LoadStringU(hFrmtFuncInst, IDS_UNKNOWN_CRL_REASON, pwszFormat, UNKNOWN_CRL_REASON_SIZE)) goto LoadStringError; } else { //get rid of the last comma *(pwszFormat+wcslen(pwszFormat)-wcslen(wszCOMMA))=L'\0'; } //get the Hex dump of the Key Usage cbNeeded=0; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pInfo->pbData, pInfo->cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszByte=(LPWSTR)malloc(cbNeeded); if(NULL==pwszByte) goto MemoryError; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pInfo->pbData, pInfo->cbData, pwszByte, &cbNeeded)) goto FormatBytesToHexError; //convert the WSZ if(!FormatMessageUnicode(ppwszFormat, IDS_BIT_BLOB, pwszFormat, pwszByte)) goto FormatMsgError; fResult=TRUE; CommonReturn: if(pwszFormat) free(pwszFormat); if(pwszByte) free(pwszByte); return fResult; ErrorReturn: if(*ppwszFormat) { LocalFree((HLOCAL)(*ppwszFormat)); *ppwszFormat=NULL; } fResult=FALSE; goto CommonReturn; TRACE_ERROR(LoadStringError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatBytesToHexError); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // FormatCRLDistPoints: X509_CRL_DIST_POINTS // szOID_CRL_DIST_POINTS // szOID_FRESHEST_CRL // szOID_CRL_SELF_CDP //-------------------------------------------------------------------------- static BOOL WINAPI FormatCRLDistPoints( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; LPWSTR pwszEntryFormat=NULL; LPWSTR pwszEntryTagFormat=NULL; LPWSTR pwszPointName=NULL; LPWSTR pwszNameFormat=NULL; LPWSTR pwszCRLReason=NULL; LPWSTR pwszReasonFormat=NULL; LPWSTR pwszCRLIssuer=NULL; LPWSTR pwszIssuerFormat=NULL; PCRL_DIST_POINTS_INFO pInfo=NULL; DWORD cbNeeded=0; DWORD dwIndex=0; BOOL fResult=FALSE; UINT ids=0; LPWSTR pwszTemp; LPCSTR pszOID; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } //DSIE: Cert server encodes szOID_CRL_SEL_CDP using szOID_CRL_DIST_POINTS, // so we need to change the lpszStructType for decoding. if (0 == strcmp(lpszStructType, szOID_CRL_SELF_CDP)) { pszOID = szOID_CRL_DIST_POINTS; } else { pszOID = lpszStructType; } if (!DecodeGenericBLOB(dwCertEncodingType, pszOID, //lpszStructType, pbEncoded, cbEncoded, (void **)&pInfo)) goto DecodeGenericError; pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; for(dwIndex=0; dwIndex<pInfo->cDistPoint; dwIndex++) { //format distribution name if(0!=pInfo->rgDistPoint[dwIndex].DistPointName.dwDistPointNameChoice) { if(!FormatDistPointName( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, &(pInfo->rgDistPoint[dwIndex].DistPointName), &pwszPointName)) goto FormatDistPointNameError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_CRL_DIST_NAME_MULTI; else ids=IDS_CRL_DIST_NAME; if(!FormatMessageUnicode(&pwszNameFormat, ids,pwszPointName)) goto FormatMsgError; } //format the CRL reason if(0!=pInfo->rgDistPoint[dwIndex].ReasonFlags.cbData) { if(!FormatCRLReason(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, &(pInfo->rgDistPoint[dwIndex].ReasonFlags), &pwszCRLReason)) goto FormatCRLReasonError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_CRL_DIST_REASON_MULTI; else ids=IDS_CRL_DIST_REASON; if(!FormatMessageUnicode(&pwszReasonFormat, ids ,pwszCRLReason)) goto FormatMsgError; } //format the Issuer if(0!=pInfo->rgDistPoint[dwIndex].CRLIssuer.cAltEntry) { if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_TWO_TABS; else ids=0; cbNeeded=0; if(!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, ids, FALSE, &(pInfo->rgDistPoint[dwIndex].CRLIssuer), NULL, &cbNeeded)) goto FormatAltNameError; pwszCRLIssuer=(LPWSTR)malloc(cbNeeded); if(NULL==pwszCRLIssuer) goto MemoryError; if(!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, ids, FALSE, &(pInfo->rgDistPoint[dwIndex].CRLIssuer), pwszCRLIssuer, &cbNeeded)) goto FormatAltNameError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_CRL_DIST_ISSUER_MULTI; else ids=IDS_CRL_DIST_ISSUER; if(!FormatMessageUnicode(&pwszIssuerFormat,ids,pwszCRLIssuer)) goto FormatMsgError; } cbNeeded=0; if(pwszNameFormat) cbNeeded+=wcslen(pwszNameFormat); if(pwszReasonFormat) cbNeeded+=wcslen(pwszReasonFormat); if(pwszIssuerFormat) cbNeeded+=wcslen(pwszIssuerFormat); if(0!=cbNeeded) { //add ", " between each element for single line format if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) { if(0!=wcslen(pwsz)) wcscat(pwsz, wszCOMMA); } //strcat all the information, including the COMMA cbNeeded += wcslen(wszCOMMA)*2; pwszEntryFormat=(LPWSTR)malloc(sizeof(WCHAR) * (cbNeeded+1)); if(NULL==pwszEntryFormat) goto MemoryError; *pwszEntryFormat=L'\0'; //strcat all three fields one at a time if(pwszNameFormat) wcscat(pwszEntryFormat, pwszNameFormat); if(pwszReasonFormat) { if(0!=wcslen(pwszEntryFormat)) { if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwszEntryFormat, wszCOMMA); } wcscat(pwszEntryFormat, pwszReasonFormat); } if(pwszIssuerFormat) { if(0!=wcslen(pwszEntryFormat)) { if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwszEntryFormat, wszCOMMA); } wcscat(pwszEntryFormat, pwszIssuerFormat); } //format the entry //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) // // DSIE: Load appropriate format string. // if (0 == strcmp(lpszStructType, szOID_FRESHEST_CRL)) ids=IDS_FRESHEST_CRL_MULTI; else if (0 == strcmp(lpszStructType, szOID_CRL_SELF_CDP)) ids=IDS_CRL_SELF_CDP_MULTI; else ids=IDS_CRL_DIST_ENTRY_MULTI; else if (0 == strcmp(lpszStructType, szOID_FRESHEST_CRL)) ids=IDS_FRESHEST_CRL; else if (0 == strcmp(lpszStructType, szOID_CRL_SELF_CDP)) ids=IDS_CRL_SELF_CDP; else ids=IDS_CRL_DIST_ENTRY; if(!FormatMessageUnicode(&pwszEntryTagFormat, ids, dwIndex+1, pwszEntryFormat)) goto FormatMsgError; //strcat the entry #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszEntryTagFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszEntryTagFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszEntryTagFormat); //free memory free(pwszEntryFormat); pwszEntryFormat=NULL; LocalFree(pwszEntryTagFormat); pwszEntryTagFormat=NULL; } //free memory if(pwszPointName) { LocalFree((HLOCAL)pwszPointName); pwszPointName=NULL; } if(pwszCRLReason) { LocalFree((HLOCAL)(pwszCRLReason)); pwszCRLReason=NULL; } if(pwszCRLIssuer) { free(pwszCRLIssuer); pwszCRLIssuer=NULL; } if(pwszNameFormat) { LocalFree((HLOCAL)pwszNameFormat); pwszNameFormat=NULL; } if(pwszReasonFormat) { LocalFree((HLOCAL)pwszReasonFormat); pwszReasonFormat=NULL; } if(pwszIssuerFormat) { LocalFree((HLOCAL)pwszIssuerFormat); pwszIssuerFormat=NULL; } } if(0==wcslen(pwsz)) { //no data pwszFormat=(LPWSTR)malloc(sizeof(WCHAR)*(NO_INFO_SIZE+1)); if(NULL==pwszFormat) goto MemoryError; if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, pwszFormat, NO_INFO_SIZE)) goto LoadStringError; } else { pwszFormat=pwsz; pwsz=NULL; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszEntryFormat) free(pwszEntryFormat); if(pwszEntryTagFormat) LocalFree((HLOCAL)pwszEntryTagFormat); //free memory if(pwszPointName) LocalFree((HLOCAL)pwszPointName); if(pwszCRLReason) LocalFree((HLOCAL)(pwszCRLReason)); if(pwszCRLIssuer) free(pwszCRLIssuer); if(pwszNameFormat) LocalFree((HLOCAL)pwszNameFormat); if(pwszReasonFormat) LocalFree((HLOCAL)pwszReasonFormat); if(pwszIssuerFormat) LocalFree((HLOCAL)pwszIssuerFormat); if(pwsz) free(pwsz); if(pwszFormat) free(pwszFormat); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatDistPointNameError); TRACE_ERROR(FormatCRLReasonError); TRACE_ERROR(FormatAltNameError); } //-------------------------------------------------------------------------- // // FormatCertPolicyID: // // Pre-condition: pCertPolicyID has to include the valid information.that is, // cCertPolicyElementId can not be 0. //-------------------------------------------------------------------------- BOOL FormatCertPolicyID(PCERT_POLICY_ID pCertPolicyID, LPWSTR *ppwszFormat) { BOOL fResult=FALSE; LPSTR pszFormat=NULL; DWORD dwIndex=0; HRESULT hr=S_OK; LPSTR pwszTemp; *ppwszFormat=NULL; if(0==pCertPolicyID->cCertPolicyElementId) goto InvalidArg; pszFormat=(LPSTR)malloc(sizeof(CHAR)); if(NULL==pszFormat) goto MemoryError; *pszFormat='\0'; for(dwIndex=0; dwIndex<pCertPolicyID->cCertPolicyElementId; dwIndex++) { #if (0) // DSIE: Bug 27436 pszFormat=(LPSTR)realloc(pszFormat, strlen(pszFormat)+ strlen(pCertPolicyID->rgpszCertPolicyElementId[dwIndex])+strlen(strCOMMA)+1); if(NULL==pszFormat) goto MemoryError; #endif pwszTemp=(LPSTR)realloc(pszFormat, strlen(pszFormat)+ strlen(pCertPolicyID->rgpszCertPolicyElementId[dwIndex])+strlen(strCOMMA)+1); if(NULL==pwszTemp) goto MemoryError; pszFormat = pwszTemp; strcat(pszFormat,pCertPolicyID->rgpszCertPolicyElementId[dwIndex]); strcat(pszFormat, strCOMMA); } //get rid of the last COMMA *(pszFormat+strlen(pszFormat)-strlen(strCOMMA))='\0'; //convert to WCHAR if(S_OK!=(hr=SZtoWSZ(pszFormat, ppwszFormat))) goto SZtoWSZError; fResult=TRUE; CommonReturn: if(pszFormat) free(pszFormat); return fResult; ErrorReturn: if(*ppwszFormat) { free(*ppwszFormat); *ppwszFormat=NULL; } fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); SET_ERROR(MemoryError, E_OUTOFMEMORY); SET_ERROR_VAR(SZtoWSZError,hr); } //-------------------------------------------------------------------------- // // FormatKeyRestriction: X509_KEY_USAGE_RESTRICTION // szOID_KEY_USAGE_RESTRICTION // // //-------------------------------------------------------------------------- static BOOL WINAPI FormatKeyRestriction( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; PCERT_KEY_USAGE_RESTRICTION_INFO pInfo=NULL; LPWSTR pwszPolicy=NULL; LPWSTR pwszPolicyFormat=NULL; LPWSTR pwszKeyUsage=NULL; LPWSTR pwszKeyUsageFormat=NULL; DWORD cbNeeded=0; DWORD dwIndex=0; BOOL fResult=FALSE; UINT ids=0; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_KEY_USAGE_RESTRICTION, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; for(dwIndex=0; dwIndex<pInfo->cCertPolicyId; dwIndex++) { if(0!=((pInfo->rgCertPolicyId)[dwIndex].cCertPolicyElementId)) { //concatecate the comma if not the 1st item if(0!=wcslen(pwsz)) { if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } if(!FormatCertPolicyID(&((pInfo->rgCertPolicyId)[dwIndex]), &pwszPolicy)) goto FormatCertPolicyIDError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_KEY_RES_ID_MULTI; else ids=IDS_KEY_RES_ID; if(!FormatMessageUnicode(&pwszPolicyFormat, ids,dwIndex+1,pwszPolicy)) goto FormatMsgError; //allocate memory, including the ", " #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszPolicyFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszPolicyFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszPolicyFormat); free(pwszPolicy); pwszPolicy=NULL; LocalFree((HLOCAL)pwszPolicyFormat); pwszPolicyFormat=NULL; } } //format the RestrictedKeyUsage if(0!=pInfo->RestrictedKeyUsage.cbData) { //concatecate the comma if not the 1st item if(0!=wcslen(pwsz)) { if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } cbNeeded=0; if(!FormatKeyUsageBLOB( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, &(pInfo->RestrictedKeyUsage), NULL, &cbNeeded)) goto FormatKeyUsageBLOBError; pwszKeyUsage=(LPWSTR)malloc(cbNeeded); if(NULL==pwszKeyUsage) goto MemoryError; if(!FormatKeyUsageBLOB( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, &(pInfo->RestrictedKeyUsage), pwszKeyUsage, &cbNeeded)) goto FormatKeyUsageBLOBError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_KEY_RES_USAGE_MULTI; else ids=IDS_KEY_RES_USAGE; //format the element string if(!FormatMessageUnicode(&pwszKeyUsageFormat, ids, pwszKeyUsage)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(pwszKeyUsageFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(pwszKeyUsageFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszKeyUsageFormat); } if(0==wcslen(pwsz)) { //no data pwszFormat=(LPWSTR)malloc(sizeof(WCHAR)*(NO_INFO_SIZE+1)); if(NULL==pwszFormat) goto MemoryError; if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, pwszFormat, NO_INFO_SIZE)) goto LoadStringError; } else { pwszFormat=pwsz; pwsz=NULL; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszPolicy) free(pwszPolicy); if(pwszPolicyFormat) LocalFree((HLOCAL)pwszPolicyFormat); if(pwszKeyUsage) free(pwszKeyUsage); if(pwszKeyUsageFormat) LocalFree((HLOCAL)pwszKeyUsageFormat); if(pwszFormat) free(pwszFormat); if(pwsz) free(pwsz); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatCertPolicyIDError); TRACE_ERROR(FormatKeyUsageBLOBError); } //----------------------------------------------------------------------- // // FormatFileTime // // Pre-condition: pFileTime points to valid data // //------------------------------------------------------------------------ BOOL FormatFileTime(FILETIME *pFileTime,LPWSTR *ppwszFormat) { BOOL fResult; int cch; int cch2; LPWSTR psz; SYSTEMTIME st; FILETIME localTime; DWORD locale; BOOL bRTLLocale; DWORD dwFlags = DATE_LONGDATE; // See if the user locale id is RTL (Arabic, Urdu, Farsi or Hebrew). locale = GetUserDefaultLCID(); bRTLLocale = ((PRIMARYLANGID(LANGIDFROMLCID(locale)) == LANG_ARABIC) || (PRIMARYLANGID(LANGIDFROMLCID(locale)) == LANG_URDU) || (PRIMARYLANGID(LANGIDFROMLCID(locale)) == LANG_FARSI) || (PRIMARYLANGID(LANGIDFROMLCID(locale)) == LANG_HEBREW)); locale = MAKELCID( MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), SORT_DEFAULT) ; if (bRTLLocale) { DWORD dwLayout; if (GetProcessDefaultLayout(&dwLayout)) { if (dwLayout & LAYOUT_RTL) { dwFlags |= DATE_RTLREADING; } else { dwFlags |= DATE_LTRREADING; } } else { dwFlags |= DATE_LTRREADING; } } if (!FileTimeToLocalFileTime(pFileTime, &localTime)) { goto ToLocalTimeError; } if (!FileTimeToSystemTime(&localTime, &st)) { // // if the conversion to local time failed, then just use the original time // if (!FileTimeToSystemTime(pFileTime, &st)) { goto ToSystemTimeError; } } cch = (GetTimeFormatU(LOCALE_USER_DEFAULT, 0, &st, NULL, NULL, 0) + GetDateFormatU(locale, dwFlags, &st, NULL, NULL, 0) + 5); if (NULL == (psz = (LPWSTR) LocalAlloc(LPTR, (cch+5) * sizeof(WCHAR)))) { goto OutOfMemoryError; } cch2 = GetDateFormatU(locale, dwFlags, &st, NULL, psz, cch); psz[cch2-1] = ' '; GetTimeFormatU(LOCALE_USER_DEFAULT, 0, &st, NULL, &psz[cch2], cch-cch2); *ppwszFormat = psz; fResult = TRUE; CommonReturn: return fResult; ErrorReturn: if(*ppwszFormat) { LocalFree((HLOCAL)(*ppwszFormat)); *ppwszFormat=NULL; } fResult=FALSE; goto CommonReturn; TRACE_ERROR(ToLocalTimeError); TRACE_ERROR(ToSystemTimeError); TRACE_ERROR(OutOfMemoryError); } //-------------------------------------------------------------------------- // // FormatKeyAttributes: X509_KEY_ATTRIBUTES // szOID_KEY_ATTRIBUTES //-------------------------------------------------------------------------- static BOOL WINAPI FormatKeyAttributes( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; LPWSTR pwszKeyIDFormat=NULL; LPWSTR pwszKeyID=NULL; LPWSTR pwszKeyUsageFormat=NULL; LPWSTR pwszKeyUsage=NULL; LPWSTR pwszKeyBeforeFormat=NULL; LPWSTR pwszKeyBefore=NULL; LPWSTR pwszKeyAfterFormat=NULL; LPWSTR pwszKeyAfter=NULL; PCERT_KEY_ATTRIBUTES_INFO pInfo=NULL; DWORD cbNeeded=0; BOOL fResult=FALSE; UINT ids=0; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_KEY_ATTRIBUTES, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; if(0!=pInfo->KeyId.cbData) { cbNeeded=0; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pInfo->KeyId.pbData, pInfo->KeyId.cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszKeyID=(LPWSTR)malloc(cbNeeded); if(NULL==pwszKeyID) goto MemoryError; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pInfo->KeyId.pbData, pInfo->KeyId.cbData, pwszKeyID, &cbNeeded)) goto FormatBytesToHexError; //format the element string //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_KEY_ATTR_ID_MULTI; else ids=IDS_KEY_ATTR_ID; if(!FormatMessageUnicode(&pwszKeyIDFormat, ids, pwszKeyID)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyIDFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyIDFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszKeyIDFormat); } //check the no data situation if(0!=pInfo->IntendedKeyUsage.cbData) { //strcat a ", " symbol for signle line format if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) { if(0!=wcslen(pwsz)) wcscat(pwsz, wszCOMMA); } cbNeeded=0; if(!FormatKeyUsageBLOB( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, &(pInfo->IntendedKeyUsage), NULL, &cbNeeded)) goto FormatKeyUsageBLOBError; pwszKeyUsage=(LPWSTR)malloc(cbNeeded); if(NULL==pwszKeyUsage) goto MemoryError; if(!FormatKeyUsageBLOB( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, &(pInfo->IntendedKeyUsage), pwszKeyUsage, &cbNeeded)) goto FormatKeyUsageBLOBError; //format the element string //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_KEY_ATTR_USAGE_MULTI; else ids=IDS_KEY_ATTR_USAGE; if(!FormatMessageUnicode(&pwszKeyUsageFormat, ids, pwszKeyUsage)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyUsageFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyUsageFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszKeyUsageFormat); } if(NULL!=pInfo->pPrivateKeyUsagePeriod) { //format only if there is some information if(!((0==pInfo->pPrivateKeyUsagePeriod->NotBefore.dwHighDateTime) &&(0==pInfo->pPrivateKeyUsagePeriod->NotBefore.dwLowDateTime))) { //strcat a ", " symbol for signle line format if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) { if(0!=wcslen(pwsz)) wcscat(pwsz, wszCOMMA); } if(!FormatFileTime(&(pInfo->pPrivateKeyUsagePeriod->NotBefore), &pwszKeyBefore)) goto FormatFileTimeError; //format the element string //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_KEY_ATTR_BEFORE_MULTI; else ids=IDS_KEY_ATTR_BEFORE; if(!FormatMessageUnicode(&pwszKeyBeforeFormat, ids, pwszKeyBefore)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR)*(wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyBeforeFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR)*(wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyBeforeFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszKeyBeforeFormat); } if(!((0==pInfo->pPrivateKeyUsagePeriod->NotAfter.dwHighDateTime) &&(0==pInfo->pPrivateKeyUsagePeriod->NotAfter.dwLowDateTime))) { //strcat a ", " symbol for signle line format if(0== (dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) { if(0!=wcslen(pwsz)) wcscat(pwsz, wszCOMMA); } if(!FormatFileTime(&(pInfo->pPrivateKeyUsagePeriod->NotAfter), &pwszKeyAfter)) goto FormatFileTimeError; //format the element string //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_KEY_ATTR_AFTER_MULTI; else ids=IDS_KEY_ATTR_AFTER; if(!FormatMessageUnicode(&pwszKeyAfterFormat, ids, pwszKeyAfter)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyAfterFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyAfterFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszKeyAfterFormat); } } if(0==wcslen(pwsz)) { pwszFormat=(LPWSTR)malloc(sizeof(WCHAR)*(NO_INFO_SIZE+1)); if(NULL==pwszFormat) goto MemoryError; if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, pwszFormat,NO_INFO_SIZE)) goto LoadStringError; } else { pwszFormat=pwsz; pwsz=NULL; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszKeyIDFormat) LocalFree((HLOCAL)pwszKeyIDFormat); if(pwszKeyID) free(pwszKeyID); if(pwszKeyUsageFormat) LocalFree((HLOCAL)pwszKeyUsageFormat); if(pwszKeyUsage) free(pwszKeyUsage); if(pwszKeyBeforeFormat) LocalFree((HLOCAL)pwszKeyBeforeFormat); if(pwszKeyBefore) LocalFree((HLOCAL)pwszKeyBefore); if(pwszKeyAfterFormat) LocalFree((HLOCAL)pwszKeyAfterFormat); if(pwszKeyAfter) LocalFree((HLOCAL)pwszKeyAfter); if(pwszFormat) free(pwszFormat); if(pwsz) free(pwsz); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatKeyUsageBLOBError); TRACE_ERROR(FormatFileTimeError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatBytesToHexError); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // FormatAuthortiyInfoAccess: X509_AUTHORITY_INFO_ACCESS // szOID_AUTHORITY_INFO_ACCESS //-------------------------------------------------------------------------- static BOOL WINAPI FormatAuthortiyInfoAccess( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fMethodAllocated=FALSE; WCHAR wszNoInfo[NO_INFO_SIZE]; WCHAR wszUnknownAccess[UNKNOWN_ACCESS_METHOD_SIZE]; PCCRYPT_OID_INFO pOIDInfo=NULL; CERT_ALT_NAME_INFO CertAltNameInfo; LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; LPWSTR pwszMethod=NULL; LPWSTR pwszAltName=NULL; LPWSTR pwszEntryFormat=NULL; PCERT_AUTHORITY_INFO_ACCESS pInfo=NULL; DWORD dwIndex=0; DWORD cbNeeded=0; BOOL fResult=FALSE; UINT ids=0; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_AUTHORITY_INFO_ACCESS, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; if(0==pInfo->cAccDescr) { //load the string "Info Not Available" if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, wszNoInfo, sizeof(wszNoInfo)/sizeof(wszNoInfo[0]))) goto LoadStringError; pwszFormat=wszNoInfo; } else { pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; //load the string "Unknown Access Method: if(!LoadStringU(hFrmtFuncInst,IDS_UNKNOWN_ACCESS_METHOD, wszUnknownAccess, sizeof(wszUnknownAccess)/sizeof(wszUnknownAccess[0]))) goto LoadStringError; for(dwIndex=0; dwIndex < pInfo->cAccDescr; dwIndex++) { fMethodAllocated=FALSE; //need a ", " between each element for single line format if(0!=wcslen(pwsz)) { if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ) wcscat(pwsz, wszCOMMA); } //get the name of the access method if(pInfo->rgAccDescr[dwIndex].pszAccessMethod) { pOIDInfo=CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, (void *)(pInfo->rgAccDescr[dwIndex].pszAccessMethod), CRYPT_EXT_OR_ATTR_OID_GROUP_ID); //get the access method OID if(pOIDInfo) { //allocate memory, including the NULL terminator pwszMethod=(LPWSTR)malloc((wcslen(pOIDInfo->pwszName)+1)* sizeof(WCHAR)); if(NULL==pwszMethod) goto MemoryError; fMethodAllocated=TRUE; wcscpy(pwszMethod,pOIDInfo->pwszName); }else pwszMethod=wszUnknownAccess; } memset(&CertAltNameInfo, 0, sizeof(CERT_ALT_NAME_INFO)); CertAltNameInfo.cAltEntry=1; CertAltNameInfo.rgAltEntry=&(pInfo->rgAccDescr[dwIndex].AccessLocation); //need to tell if it is for multi line format. We need two \t\t //in front of each alt name entry if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_TWO_TABS; else ids=0; //get the alternative name entry cbNeeded=0; if(!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, ids, FALSE, &CertAltNameInfo, NULL, &cbNeeded)) goto FormatAltNameError; pwszAltName=(LPWSTR)malloc(cbNeeded); if(NULL==pwszAltName) goto MemoryError; if(!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, ids, FALSE, &CertAltNameInfo, pwszAltName, &cbNeeded)) goto FormatAltNameError; //format the entry if(pInfo->rgAccDescr[dwIndex].pszAccessMethod) { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_AUTHORITY_ACCESS_INFO_MULTI; else ids=IDS_AUTHORITY_ACCESS_INFO; if(!FormatMessageUnicode(&pwszEntryFormat, ids, dwIndex+1, pwszMethod, pInfo->rgAccDescr[dwIndex].pszAccessMethod, pwszAltName)) goto FormatMsgError; } else { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_AUTHORITY_ACCESS_NO_METHOD_MULTI; else ids=IDS_AUTHORITY_ACCESS_NO_METHOD; if(!FormatMessageUnicode(&pwszEntryFormat, ids, dwIndex+1, pwszAltName)) goto FormatMsgError; } //reallocat the memory. Leave space for szComma #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(pwszEntryFormat)+ wcslen(wszCOMMA)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(pwszEntryFormat)+ wcslen(wszCOMMA)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, pwszEntryFormat); //free memory LocalFree((HLOCAL)pwszEntryFormat); pwszEntryFormat=NULL; free(pwszAltName); pwszAltName=NULL; if(TRUE==fMethodAllocated) free(pwszMethod); pwszMethod=NULL; } //convert to WCHAR pwszFormat=pwsz; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwsz) free(pwsz); if(pwszEntryFormat) LocalFree((HLOCAL)pwszEntryFormat); if(pwszAltName) free(pwszAltName); if(fMethodAllocated) { if(pwszMethod) free(pwszMethod); } if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); TRACE_ERROR(FormatAltNameError); SET_ERROR(MemoryError, E_OUTOFMEMORY); } //-------------------------------------------------------------------------- // // FormatKeyUsageBLOB //-------------------------------------------------------------------------- static BOOL WINAPI FormatKeyUsageBLOB( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, PCRYPT_BIT_BLOB pInfo, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFinal=NULL; LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; LPWSTR pwszByte=NULL; WCHAR wszKeyUsage[KEY_USAGE_SIZE+1]; DWORD cbNeeded=0; BOOL fResult=FALSE; LPWSTR pwszTemp; pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; //format the 1st byte if(pInfo->pbData[0] & CERT_DIGITAL_SIGNATURE_KEY_USAGE) { if(!LoadStringU(hFrmtFuncInst, IDS_DIG_SIG, wszKeyUsage, KEY_USAGE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszKeyUsage); wcscat(pwsz, wszCOMMA); } if(pInfo->pbData[0] & CERT_NON_REPUDIATION_KEY_USAGE) { if(!LoadStringU(hFrmtFuncInst, IDS_NON_REPUDIATION, wszKeyUsage, KEY_USAGE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszKeyUsage); wcscat(pwsz, wszCOMMA); } if(pInfo->pbData[0] & CERT_KEY_ENCIPHERMENT_KEY_USAGE ) { if(!LoadStringU(hFrmtFuncInst, IDS_KEY_ENCIPHERMENT, wszKeyUsage, KEY_USAGE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszKeyUsage); wcscat(pwsz, wszCOMMA); } if(pInfo->pbData[0] & CERT_DATA_ENCIPHERMENT_KEY_USAGE ) { if(!LoadStringU(hFrmtFuncInst, IDS_DATA_ENCIPHERMENT, wszKeyUsage, KEY_USAGE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszKeyUsage); wcscat(pwsz, wszCOMMA); } if(pInfo->pbData[0] & CERT_KEY_AGREEMENT_KEY_USAGE ) { if(!LoadStringU(hFrmtFuncInst, IDS_KEY_AGREEMENT, wszKeyUsage, KEY_USAGE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszKeyUsage); wcscat(pwsz, wszCOMMA); } if(pInfo->pbData[0] & CERT_KEY_CERT_SIGN_KEY_USAGE ) { if(!LoadStringU(hFrmtFuncInst, IDS_CERT_SIGN, wszKeyUsage, KEY_USAGE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszKeyUsage); wcscat(pwsz, wszCOMMA); } if(pInfo->pbData[0] & CERT_OFFLINE_CRL_SIGN_KEY_USAGE ) { if(!LoadStringU(hFrmtFuncInst, IDS_OFFLINE_CRL_SIGN, wszKeyUsage, KEY_USAGE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszKeyUsage); wcscat(pwsz, wszCOMMA); } if(pInfo->pbData[0] & CERT_CRL_SIGN_KEY_USAGE ) { if(!LoadStringU(hFrmtFuncInst, IDS_CRL_SIGN, wszKeyUsage, KEY_USAGE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszKeyUsage); wcscat(pwsz, wszCOMMA); } if(pInfo->pbData[0] & CERT_ENCIPHER_ONLY_KEY_USAGE ) { if(!LoadStringU(hFrmtFuncInst, IDS_ENCIPHER_ONLY, wszKeyUsage, KEY_USAGE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszKeyUsage); wcscat(pwsz, wszCOMMA); } //deal with the second byte if(pInfo->cbData>=2) { if(pInfo->pbData[1] & CERT_DECIPHER_ONLY_KEY_USAGE ) { if(!LoadStringU(hFrmtFuncInst, IDS_DECIPHER_ONLY, wszKeyUsage, KEY_USAGE_SIZE)) goto LoadStringError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszKeyUsage)+1+wcslen(wszCOMMA))); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz, wszKeyUsage); wcscat(pwsz, wszCOMMA); } } if(0==wcslen(pwsz)) { #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (UNKNOWN_KEY_USAGE_SIZE+1)); // if(NULL==pwszFormat) DSIE: Bug 27348 if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (UNKNOWN_KEY_USAGE_SIZE+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; if(!LoadStringU(hFrmtFuncInst, IDS_UNKNOWN_KEY_USAGE, pwsz, UNKNOWN_KEY_USAGE_SIZE)) goto LoadStringError; } else { //get rid of the last comma *(pwsz+wcslen(pwsz)-wcslen(wszCOMMA))=L'\0'; } //get the Hex dump of the Key Usage cbNeeded=0; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pInfo->pbData, pInfo->cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszByte=(LPWSTR)malloc(cbNeeded); if(NULL==pwszByte) goto MemoryError; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pInfo->pbData, pInfo->cbData, pwszByte, &cbNeeded)) goto FormatBytesToHexError; //convert the WSZ if(!FormatMessageUnicode(&pwszFormat, IDS_BIT_BLOB, pwsz, pwszByte)) goto FormatMsgError; // // DSIE: Fix bug 91502, 256396. // pwszFinal=(LPWSTR)malloc(sizeof(WCHAR) * (wcslen(pwszFormat)+1+wcslen(wszCRLF))); if(NULL==pwszFinal) goto MemoryError; wcscpy(pwszFinal, pwszFormat); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(pwszFinal, wszCRLF); cbNeeded=sizeof(WCHAR)*(wcslen(pwszFinal)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFinal, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if (pwszFinal) free(pwszFinal); if(pwszFormat) LocalFree((HLOCAL)pwszFormat); if(pwsz) free(pwsz); if(pwszByte) free(pwszByte); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatBytesToHexError); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // FormatKeyUsage: X509_KEY_USAGE // szOID_KEY_USAGE //-------------------------------------------------------------------------- static BOOL WINAPI FormatKeyUsage( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; WCHAR wszNoInfo[NO_INFO_SIZE]; PCRYPT_BIT_BLOB pInfo=NULL; DWORD cbNeeded=0; BOOL fResult=FALSE; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_KEY_USAGE, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //load the string "Info Not Available" if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, wszNoInfo, sizeof(wszNoInfo)/sizeof(wszNoInfo[0]))) goto LoadStringError; //check the no data situation if(0==pInfo->cbData) pwszFormat=wszNoInfo; else { if(1==pInfo->cbData) { if(0==pInfo->pbData[0]) pwszFormat=wszNoInfo; } else { if(2==pInfo->cbData) { if((0==pInfo->pbData[0])&&(0==pInfo->pbData[1])) pwszFormat=wszNoInfo; } } } if(NULL==pwszFormat) { fResult=FormatKeyUsageBLOB(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, pInfo, pbFormat, pcbFormat); if(FALSE==fResult) goto FormatKeyUsageBLOBError; } else { cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; } CommonReturn: if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatKeyUsageBLOBError); } //-------------------------------------------------------------------------- // // FormatSMIMECapabilities: PKCS_SMIME_CAPABILITIES // szOID_RSA_SMIMECapabilities //-------------------------------------------------------------------------- static BOOL WINAPI FormatSMIMECapabilities( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; LPWSTR pwszElementFormat=NULL; LPWSTR pwszParam=NULL; WCHAR wszNoInfo[NO_INFO_SIZE]; BOOL fParamAllocated=FALSE; PCRYPT_SMIME_CAPABILITIES pInfo=NULL; DWORD cbNeeded=0; BOOL fResult=FALSE; DWORD dwIndex =0; UINT idsSub=0; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,PKCS_SMIME_CAPABILITIES, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //check to see if information if available if(0==pInfo->cCapability) { //load the string "Info Not Available" if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, wszNoInfo, sizeof(wszNoInfo)/sizeof(wszNoInfo[0]))) goto LoadStringError; pwszFormat=wszNoInfo; } else { pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; for(dwIndex=0; dwIndex < pInfo->cCapability; dwIndex++) { fParamAllocated=FALSE; //strcat ", " if single line. No need for multi-line if(0!=wcslen(pwsz)) { if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } if(0!=(pInfo->rgCapability)[dwIndex].Parameters.cbData) { cbNeeded=0; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, (pInfo->rgCapability)[dwIndex].Parameters.pbData, (pInfo->rgCapability)[dwIndex].Parameters.cbData, NULL, &cbNeeded)) goto FormatBytesToHexError; pwszParam=(LPWSTR)malloc(cbNeeded); if(NULL==pwszParam) goto MemoryError; fParamAllocated=TRUE; if(!FormatBytesToHex( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, (pInfo->rgCapability)[dwIndex].Parameters.pbData, (pInfo->rgCapability)[dwIndex].Parameters.cbData, pwszParam, &cbNeeded)) goto FormatBytesToHexError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsSub=IDS_MIME_CAPABILITY_MULTI; else idsSub=IDS_MIME_CAPABILITY; //format the element string if(!FormatMessageUnicode(&pwszElementFormat, idsSub, dwIndex+1, (pInfo->rgCapability)[dwIndex].pszObjId, pwszParam)) goto FormatMsgError; } else { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsSub=IDS_MIME_CAPABILITY_NO_PARAM_MULTI; else idsSub=IDS_MIME_CAPABILITY_NO_PARAM; //format the element string if(!FormatMessageUnicode(&pwszElementFormat, idsSub, dwIndex+1, (pInfo->rgCapability)[dwIndex].pszObjId)) goto FormatMsgError; } #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszElementFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszElementFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; //strcat the element wcscat(pwsz, pwszElementFormat); //free the memory LocalFree((HLOCAL)pwszElementFormat); pwszElementFormat=NULL; if(fParamAllocated) free(pwszParam); pwszParam=NULL; } pwszFormat=pwsz; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszElementFormat) LocalFree((HLOCAL)pwszElementFormat); if(fParamAllocated) { if(pwszParam) free(pwszParam); } if(pInfo) free(pInfo); if(pwsz) free(pwsz); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatBytesToHexError); } //-------------------------------------------------------------------------- // // FormatFinancialCriteria: SPC_FINANCIAL_CRITERIA_OBJID // SPC_FINANCIAL_CRITERIA_STRUCT //-------------------------------------------------------------------------- static BOOL WINAPI FormatFinancialCriteria( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; WCHAR wszYesNo[YES_NO_SIZE]; WCHAR wszAvailable[AVAIL_SIZE]; PSPC_FINANCIAL_CRITERIA pInfo=NULL; DWORD cbNeeded=0; BOOL fResult=FALSE; UINT idsInfo=0; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,SPC_FINANCIAL_CRITERIA_STRUCT, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //load the string for financial info if(TRUE==pInfo->fFinancialInfoAvailable) { if(TRUE==pInfo->fMeetsCriteria) idsInfo=IDS_YES; else idsInfo=IDS_NO; //load the string for "yes" or "no" if(!LoadStringU(hFrmtFuncInst,idsInfo, wszYesNo, sizeof(wszYesNo)/sizeof(wszYesNo[0]))) goto LoadStringError; //mark the avaiblility of the financial info idsInfo=IDS_AVAILABLE; } else idsInfo=IDS_NOT_AVAILABLE; if(!LoadStringU(hFrmtFuncInst,idsInfo, wszAvailable, sizeof(wszAvailable)/sizeof(wszAvailable[0]))) goto LoadStringError; //format the output string if(TRUE==pInfo->fFinancialInfoAvailable) { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsInfo=IDS_SPC_FINANCIAL_AVAIL_MULTI; else idsInfo=IDS_SPC_FINANCIAL_AVAIL; if(!FormatMessageUnicode(&pwszFormat, idsInfo, wszAvailable, wszYesNo)) goto FormatMsgError; } else { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsInfo=IDS_SPC_FINANCIAL_NOT_AVAIL_MULTI; else idsInfo=IDS_SPC_FINANCIAL_NOT_AVAIL; if(!FormatMessageUnicode(&pwszFormat, idsInfo, wszAvailable)) goto FormatMsgError; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszFormat) LocalFree((HLOCAL)pwszFormat); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // FormatNextUpdateLocation: szOID_NEXT_UPDATE_LOCATION //-------------------------------------------------------------------------- static BOOL WINAPI FormatNextUpdateLocation( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { PCERT_ALT_NAME_INFO pInfo=NULL; BOOL fResult=FALSE; //check for input parameters if((NULL==pbEncoded && cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,szOID_NEXT_UPDATE_LOCATION, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //format the alternative name fResult=FormatAltNameInfo(dwCertEncodingType, dwFormatType,dwFormatStrType, pFormatStruct, 0, //no prefix TRUE, pInfo, pbFormat, pcbFormat); if(FALSE==fResult) goto FormatAltNameError; CommonReturn: if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(FormatAltNameError); } //-------------------------------------------------------------------------- // // FormatSubjectKeyID: szOID_SUBJECT_KEY_IDENTIFIER //-------------------------------------------------------------------------- static BOOL WINAPI FormatSubjectKeyID( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { PCRYPT_DATA_BLOB pInfo=NULL; BOOL fResult=FALSE; WCHAR wszNoInfo[NO_INFO_SIZE]; DWORD cbNeeded=0; // DSIE: Fix bug 91502 LPWSTR pwsz=NULL; LPWSTR pwszFormat=NULL; LPWSTR pwszKeyID=NULL; LPWSTR pwszKeyIDFormat=NULL; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded && cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,szOID_SUBJECT_KEY_IDENTIFIER, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //format the key subject ID //handle NULL data case if(0==pInfo->cbData) { //load the string "Info Not Available" if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, wszNoInfo, sizeof(wszNoInfo)/sizeof(wszNoInfo[0]))) goto LoadStringError; pwszFormat = wszNoInfo; } else { pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; cbNeeded=0; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, NULL, NULL, pInfo->pbData, pInfo->cbData, NULL, &cbNeeded)) goto KeyIDBytesToHexError; pwszKeyID=(LPWSTR)malloc(cbNeeded); if(NULL==pwszKeyID) goto MemoryError; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, NULL, NULL, pInfo->pbData, pInfo->cbData, pwszKeyID, &cbNeeded)) goto KeyIDBytesToHexError; if(!FormatMessageUnicode(&pwszKeyIDFormat,IDS_UNICODE_STRING,pwszKeyID)) goto FormatMsgError; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(pwszKeyIDFormat)+wcslen(wszCRLF)+1)); else pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(pwszKeyIDFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; //strcat the KeyID wcscat(pwsz,pwszKeyIDFormat); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(pwsz, wszCRLF); pwszFormat=pwsz; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszKeyID) free(pwszKeyID); if(pwszKeyIDFormat) LocalFree((HLOCAL)pwszKeyIDFormat); if(pwsz) free(pwsz); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(FormatMsgError); TRACE_ERROR(KeyIDBytesToHexError); //TRACE_ERROR(FormatBytestToHexError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); SET_ERROR(MemoryError, E_OUTOFMEMORY); } //-------------------------------------------------------------------------- // // FormatAuthorityKeyID: szOID_AUTHORITY_KEY_IDENTIFIER // X509_AUTHORITY_KEY_ID //-------------------------------------------------------------------------- static BOOL WINAPI FormatAuthorityKeyID( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; LPWSTR pwszKeyID=NULL; LPWSTR pwszKeyIDFormat=NULL; LPWSTR pwszCertIssuer=NULL; LPWSTR pwszCertIssuerFormat=NULL; LPWSTR pwszCertNumber=NULL; LPWSTR pwszCertNumberFormat=NULL; BYTE *pByte=NULL; DWORD dwByteIndex=0; WCHAR wszNoInfo[NO_INFO_SIZE]; PCERT_AUTHORITY_KEY_ID_INFO pInfo=NULL; DWORD cbNeeded=0; BOOL fResult=FALSE; UINT ids=0; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded && cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_AUTHORITY_KEY_ID, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //load the string "Info Not Available" if((0==pInfo->KeyId.cbData)&&(0==pInfo->CertIssuer.cbData) &&(0==pInfo->CertSerialNumber.cbData)) { if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, wszNoInfo, sizeof(wszNoInfo)/sizeof(wszNoInfo[0]))) goto LoadStringError; pwszFormat=wszNoInfo; } else { pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; //format the three fields in the struct: KeyID; CertIssuer; CertSerialNumber if(0!=pInfo->KeyId.cbData) { cbNeeded=0; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, NULL, NULL, pInfo->KeyId.pbData, pInfo->KeyId.cbData, NULL, &cbNeeded)) goto KeyIDBytesToHexError; pwszKeyID=(LPWSTR)malloc(cbNeeded); if(NULL==pwszKeyID) goto MemoryError; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, NULL, NULL, pInfo->KeyId.pbData, pInfo->KeyId.cbData, pwszKeyID, &cbNeeded)) goto KeyIDBytesToHexError; if(!FormatMessageUnicode(&pwszKeyIDFormat, IDS_AUTH_KEY_ID,pwszKeyID)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyIDFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif #if (0) //DSIE: Potential AV. Need two more chars, \r\n, for multi-lines. pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyIDFormat)+1)); #else if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyIDFormat)+wcslen(wszCRLF)+1)); else pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszKeyIDFormat)+1)); #endif if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; //strcat the KeyID wcscat(pwsz,pwszKeyIDFormat); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(pwsz, wszCRLF); } //format certIssuer if(0!=pInfo->CertIssuer.cbData) { //strcat ", " if there is data before if(0!=wcslen(pwsz)) { if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } if(!CryptDllFormatNameAll( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, IDS_ONE_TAB, TRUE, //memory allocation pInfo->CertIssuer.pbData, pInfo->CertIssuer.cbData, (void **)&pwszCertIssuer, NULL)) goto GetCertNameError; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_AUTH_CERT_ISSUER_MULTI; else ids=IDS_AUTH_CERT_ISSUER; if(!FormatMessageUnicode(&pwszCertIssuerFormat, ids,pwszCertIssuer)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszCertIssuerFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszCertIssuerFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz,pwszCertIssuerFormat); //no need for \n for CERT_NAME } //format CertSerialNumber if(0!=pInfo->CertSerialNumber.cbData) { //strcat ", " if there is data before if(0!=wcslen(pwsz)) { if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } //copy the serial number into the correct order pByte=(BYTE *)malloc(pInfo->CertSerialNumber.cbData); if(NULL==pByte) goto MemoryError; for(dwByteIndex=0; dwByteIndex <pInfo->CertSerialNumber.cbData; dwByteIndex++) { pByte[dwByteIndex]=*(pInfo->CertSerialNumber.pbData+ pInfo->CertSerialNumber.cbData-1-dwByteIndex); } cbNeeded=0; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, NULL, NULL, pByte, pInfo->CertSerialNumber.cbData, NULL, &cbNeeded)) goto CertNumberBytesToHexError; pwszCertNumber=(LPWSTR)malloc(cbNeeded); if(NULL==pwszCertNumber) goto MemoryError; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, NULL, NULL, pByte, pInfo->CertSerialNumber.cbData, pwszCertNumber, &cbNeeded)) goto CertNumberBytesToHexError; if(!FormatMessageUnicode(&pwszCertNumberFormat, IDS_AUTH_CERT_NUMBER,pwszCertNumber)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszCertNumberFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszCertNumberFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz,pwszCertNumberFormat); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(pwsz, wszCRLF); } pwszFormat=pwsz; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pByte) free(pByte); if(pwszKeyID) free(pwszKeyID); if(pwszKeyIDFormat) LocalFree((HLOCAL)pwszKeyIDFormat); if(pwszCertIssuer) free(pwszCertIssuer); if(pwszCertIssuerFormat) LocalFree((HLOCAL)pwszCertIssuerFormat); if(pwszCertNumber) free(pwszCertNumber); if(pwszCertNumberFormat) LocalFree((HLOCAL)pwszCertNumberFormat); if(pwsz) free(pwsz); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); TRACE_ERROR(KeyIDBytesToHexError); TRACE_ERROR(GetCertNameError); TRACE_ERROR(CertNumberBytesToHexError); SET_ERROR(MemoryError, E_OUTOFMEMORY); } //-------------------------------------------------------------------------- // // FormatAuthorityKeyID2: szOID_AUTHORITY_KEY_IDENTIFIER2 // X509_AUTHORITY_KEY_ID2 //-------------------------------------------------------------------------- static BOOL WINAPI FormatAuthorityKeyID2( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; LPWSTR pwszKeyID=NULL; LPWSTR pwszKeyIDFormat=NULL; LPWSTR pwszCertIssuer=NULL; LPWSTR pwszCertIssuerFormat=NULL; LPWSTR pwszCertNumber=NULL; LPWSTR pwszCertNumberFormat=NULL; BYTE *pByte=NULL; DWORD dwByteIndex=0; WCHAR wszNoInfo[NO_INFO_SIZE]; PCERT_AUTHORITY_KEY_ID2_INFO pInfo=NULL; DWORD cbNeeded=0; BOOL fResult=FALSE; UINT ids=0; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded && cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_AUTHORITY_KEY_ID2, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //load the string "Info Not Available" if((0==pInfo->KeyId.cbData)&&(0==pInfo->AuthorityCertIssuer.cAltEntry) &&(0==pInfo->AuthorityCertSerialNumber.cbData)) { if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, wszNoInfo, sizeof(wszNoInfo)/sizeof(wszNoInfo[0]))) goto LoadStringError; pwszFormat=wszNoInfo; } else { pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; //format the three fields in the struct: KeyID; CertIssuer; CertSerialNumber if(0!=pInfo->KeyId.cbData) { cbNeeded=0; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, NULL, NULL, pInfo->KeyId.pbData, pInfo->KeyId.cbData, NULL, &cbNeeded)) goto KeyIDBytesToHexError; pwszKeyID=(LPWSTR)malloc(cbNeeded); if(NULL==pwszKeyID) goto MemoryError; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, NULL, NULL, pInfo->KeyId.pbData, pInfo->KeyId.cbData, pwszKeyID, &cbNeeded)) goto KeyIDBytesToHexError; if(!FormatMessageUnicode(&pwszKeyIDFormat, IDS_AUTH_KEY_ID,pwszKeyID)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+ wcslen(pwszKeyIDFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+ wcslen(pwszKeyIDFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz,pwszKeyIDFormat); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(pwsz, wszCRLF); } //format certIssuer if(0!=pInfo->AuthorityCertIssuer.cAltEntry) { //strcat ", " if there is data before if(0!=wcslen(pwsz)) { if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } cbNeeded=0; //need a \t before each entry of the alternative name if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) ids=IDS_ONE_TAB; else ids=0; //format the alternative name if(!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, ids, FALSE, &(pInfo->AuthorityCertIssuer), NULL, &cbNeeded)) goto FormatAltNameError; pwszCertIssuer=(LPWSTR)malloc(cbNeeded); if(NULL==pwszCertIssuer) goto MemoryError; if(!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, ids, FALSE, &(pInfo->AuthorityCertIssuer), pwszCertIssuer, &cbNeeded)) goto FormatAltNameError; //format the element. Has to distinguish between the multi line //and single line for alternative name: if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) { if(!FormatMessageUnicode(&pwszCertIssuerFormat, IDS_AUTH_CERT_ISSUER_MULTI,pwszCertIssuer)) goto FormatMsgError; } else { if(!FormatMessageUnicode(&pwszCertIssuerFormat, IDS_AUTH_CERT_ISSUER,pwszCertIssuer)) goto FormatMsgError; } #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA) +wcslen(pwszCertIssuerFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA) +wcslen(pwszCertIssuerFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz,pwszCertIssuerFormat); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(pwsz, wszCRLF); } //format CertSerialNumber if(0!=pInfo->AuthorityCertSerialNumber.cbData) { //strcat ", " if there is data before if(0!=wcslen(pwsz)) { if(0==(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) wcscat(pwsz, wszCOMMA); } //copy the serial number into the correct order pByte=(BYTE *)malloc(pInfo->AuthorityCertSerialNumber.cbData); if(NULL==pByte) goto MemoryError; for(dwByteIndex=0; dwByteIndex <pInfo->AuthorityCertSerialNumber.cbData; dwByteIndex++) { pByte[dwByteIndex]=*(pInfo->AuthorityCertSerialNumber.pbData+ pInfo->AuthorityCertSerialNumber.cbData-1-dwByteIndex); } cbNeeded=0; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, NULL, NULL, pByte, pInfo->AuthorityCertSerialNumber.cbData, NULL, &cbNeeded)) goto CertNumberBytesToHexError; pwszCertNumber=(LPWSTR)malloc(cbNeeded); if(NULL==pwszCertNumber) goto MemoryError; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, NULL, NULL, pByte, pInfo->AuthorityCertSerialNumber.cbData, pwszCertNumber, &cbNeeded)) goto CertNumberBytesToHexError; if(!FormatMessageUnicode(&pwszCertNumberFormat, IDS_AUTH_CERT_NUMBER,pwszCertNumber)) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA) +wcslen(pwszCertNumberFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA) +wcslen(pwszCertNumberFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; wcscat(pwsz,pwszCertNumberFormat); if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(pwsz, wszCRLF); } //convert the WCHAR version pwszFormat=pwsz; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pByte) free(pByte); if(pwszKeyID) free(pwszKeyID); if(pwszKeyIDFormat) LocalFree((HLOCAL)pwszKeyIDFormat); if(pwszCertIssuer) free(pwszCertIssuer); if(pwszCertIssuerFormat) LocalFree((HLOCAL)pwszCertIssuerFormat); if(pwszCertNumber) free(pwszCertNumber); if(pwszCertNumberFormat) LocalFree((HLOCAL)pwszCertNumberFormat); if(pwsz) free(pwsz); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); TRACE_ERROR(KeyIDBytesToHexError); TRACE_ERROR(FormatAltNameError); TRACE_ERROR(CertNumberBytesToHexError); SET_ERROR(MemoryError, E_OUTOFMEMORY); } //-------------------------------------------------------------------------- // // FormatBasicConstraints: szOID_BASIC_CONSTRAINTS // X509_BASIC_CONSTRAINTS //-------------------------------------------------------------------------- static BOOL WINAPI FormatBasicConstraints( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; WCHAR wszSubject[SUBJECT_SIZE * 2]; WCHAR wszNone[NONE_SIZE]; LPWSTR pwszFormatSub=NULL; LPWSTR pwszFormatWhole=NULL; LPWSTR pwszSubtreeName=NULL; LPWSTR pwszSubtreeFormat=NULL; DWORD dwIndex=0; PCERT_BASIC_CONSTRAINTS_INFO pInfo=NULL; DWORD cbNeeded=0; BOOL fResult=FALSE; UINT idsSub=0; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_BASIC_CONSTRAINTS, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //load the string for the subjectType //init to "\0" *wszSubject=L'\0'; if(0!=pInfo->SubjectType.cbData) { //get the subjectType info if ((pInfo->SubjectType.pbData[0]) & CERT_CA_SUBJECT_FLAG) { if(!LoadStringU(hFrmtFuncInst,IDS_SUB_CA, wszSubject, sizeof(wszSubject)/sizeof(wszSubject[0]))) goto LoadStringError; } if ((pInfo->SubjectType.pbData[0]) & CERT_END_ENTITY_SUBJECT_FLAG) { if(wcslen(wszSubject)!=0) { wcscat(wszSubject, wszCOMMA); } if(!LoadStringU(hFrmtFuncInst,IDS_SUB_EE, wszSubject+wcslen(wszSubject), SUBJECT_SIZE)) goto LoadStringError; } //load string "NONE" if(0==wcslen(wszSubject)) { if(!LoadStringU(hFrmtFuncInst,IDS_NONE, wszSubject, sizeof(wszSubject)/sizeof(wszSubject[0]))) goto LoadStringError; } } //path contraints if (pInfo->fPathLenConstraint) { //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsSub=IDS_BASIC_CONS2_PATH_MULTI; else idsSub=IDS_BASIC_CONS2_PATH; if(!FormatMessageUnicode(&pwszFormatSub,idsSub, wszSubject, pInfo->dwPathLenConstraint)) goto FormatMsgError; } else { if(!LoadStringU(hFrmtFuncInst,IDS_NONE, wszNone, sizeof(wszNone)/sizeof(wszNone[0]))) goto LoadStringError; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsSub=IDS_BASIC_CONS2_NONE_MULTI; else idsSub=IDS_BASIC_CONS2_NONE; if(!FormatMessageUnicode(&pwszFormatSub,idsSub, wszSubject, wszNone)) goto FormatMsgError; } pwszFormatWhole=(LPWSTR)malloc(sizeof(WCHAR) * (wcslen(pwszFormatSub)+1)); if(!pwszFormatWhole) goto MemoryError; wcscpy(pwszFormatWhole, pwszFormatSub); //now, format SubTreeContraints one at a time for(dwIndex=0; dwIndex<pInfo->cSubtreesConstraint; dwIndex++) { //get WCHAR version of the name if(!CryptDllFormatNameAll( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, IDS_ONE_TAB, TRUE, //memory allocation pInfo->rgSubtreesConstraint[dwIndex].pbData, pInfo->rgSubtreesConstraint[dwIndex].cbData, (void **)&pwszSubtreeName, NULL)) goto GetCertNameError; //decide between single line and mulitple line format if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsSub=IDS_SUBTREE_CONSTRAINT_MULTI; else idsSub=IDS_SUBTREE_CONSTRAINT; if(!FormatMessageUnicode(&pwszSubtreeFormat,idsSub, dwIndex+1, pwszSubtreeName)) goto FormatNameError; #if (0) // DSIE: Bug 27436 pwszFormatWhole=(LPWSTR)realloc(pwszFormatWhole, sizeof(WCHAR) * (wcslen(pwszFormatWhole)+1+wcslen(pwszSubtreeFormat))); if(NULL == pwszFormatWhole) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwszFormatWhole, sizeof(WCHAR) * (wcslen(pwszFormatWhole)+1+wcslen(pwszSubtreeFormat))); if(NULL == pwszTemp) goto MemoryError; pwszFormatWhole = pwszTemp; wcscat(pwszFormatWhole,pwszSubtreeFormat); LocalFree((HLOCAL)pwszSubtreeFormat); pwszSubtreeFormat=NULL; free(pwszSubtreeName); pwszSubtreeName=NULL; } //format to the wide char version pwszFormat=pwszFormatWhole; cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszFormatSub) LocalFree((HLOCAL)pwszFormatSub); if(pwszSubtreeFormat) LocalFree((HLOCAL)pwszSubtreeFormat); if(pwszFormatWhole) free(pwszFormatWhole); if(pwszSubtreeName) free(pwszSubtreeName); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); TRACE_ERROR(FormatNameError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(GetCertNameError); } //-------------------------------------------------------------------------- // // FormatCRLReasonCode:szOID_CRL_REASON_CODE // X509_CRL_REASON_CODE //-------------------------------------------------------------------------- static BOOL WINAPI FormatCRLReasonCode( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { WCHAR wszReason[CRL_REASON_SIZE]; LPWSTR pwszFormat=NULL; int *pInfo=NULL; DWORD cbNeeded=0; BOOL fResult=FALSE; UINT idsCRLReason=0; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_CRL_REASON_CODE, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //decide which ids to use switch(*pInfo) { case CRL_REASON_UNSPECIFIED: idsCRLReason=IDS_UNSPECIFIED; break; case CRL_REASON_KEY_COMPROMISE: idsCRLReason=IDS_KEY_COMPROMISE; break; case CRL_REASON_CA_COMPROMISE: idsCRLReason=IDS_CA_COMPROMISE; break; case CRL_REASON_AFFILIATION_CHANGED: idsCRLReason=IDS_AFFILIATION_CHANGED; break; case CRL_REASON_SUPERSEDED: idsCRLReason=IDS_SUPERSEDED; break; case CRL_REASON_CESSATION_OF_OPERATION: idsCRLReason=IDS_CESSATION_OF_OPERATION; break; case CRL_REASON_CERTIFICATE_HOLD: idsCRLReason=IDS_CERTIFICATE_HOLD; break; case CRL_REASON_REMOVE_FROM_CRL: idsCRLReason=IDS_REMOVE_FROM_CRL; break; default: idsCRLReason=IDS_UNKNOWN_CRL_REASON; break; } //load string if(!LoadStringU(hFrmtFuncInst,idsCRLReason, wszReason, sizeof(wszReason)/sizeof(wszReason[0]))) goto LoadStringError; //format if(!FormatMessageUnicode(&pwszFormat, IDS_CRL_REASON, wszReason, *pInfo)) goto FormatMsgError; cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszFormat) LocalFree((HLOCAL)pwszFormat); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // FormatEnhancedKeyUsage: szOID_ENHANCED_KEY_USAGE // X509_ENHANCED_KEY_USAGE //-------------------------------------------------------------------------- static BOOL WINAPI FormatEnhancedKeyUsage( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fOIDNameAllocated=FALSE; WCHAR wszNoInfo[NO_INFO_SIZE]; WCHAR wszUnknownOID[UNKNOWN_KEY_USAGE_SIZE]; PCCRYPT_OID_INFO pOIDInfo=NULL; LPWSTR pwszFormat=NULL; LPWSTR pwszOIDName=NULL; PCERT_ENHKEY_USAGE pInfo=NULL; LPWSTR pwsz=NULL; LPWSTR pwszOIDFormat=NULL; DWORD dwIndex=0; DWORD cbNeeded=0; BOOL fResult=FALSE; LPWSTR pwszTemp; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_ENHANCED_KEY_USAGE, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; //load string NONE if there is no value available if(0==pInfo->cUsageIdentifier) { if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, wszNoInfo, sizeof(wszNoInfo)/sizeof(wszNoInfo[0]))) goto LoadStringError; pwszFormat=wszNoInfo; } else { //load the string for "unknown key usage" if(!LoadStringU(hFrmtFuncInst,IDS_UNKNOWN_KEY_USAGE, wszUnknownOID, sizeof(wszUnknownOID)/sizeof(wszUnknownOID[0]))) goto LoadStringError; pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; *pwsz=L'\0'; //build the comma/\n seperated string for(dwIndex=0; dwIndex<pInfo->cUsageIdentifier; dwIndex++) { fOIDNameAllocated=FALSE; pOIDInfo=CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, (void *)(pInfo->rgpszUsageIdentifier[dwIndex]), CRYPT_ENHKEY_USAGE_OID_GROUP_ID); if(pOIDInfo) { //allocate memory, including the NULL terminator pwszOIDName=(LPWSTR)malloc((wcslen(pOIDInfo->pwszName)+1)* sizeof(WCHAR)); if(NULL==pwszOIDName) goto MemoryError; fOIDNameAllocated=TRUE; wcscpy(pwszOIDName,pOIDInfo->pwszName); }else pwszOIDName=wszUnknownOID; if(!FormatMessageUnicode(&pwszOIDFormat, IDS_ENHANCED_KEY_USAGE, pwszOIDName, (pInfo->rgpszUsageIdentifier)[dwIndex])) goto FormatMsgError; #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+ wcslen(wszCOMMA)+wcslen(pwszOIDFormat)+1)); if(NULL==pwsz) goto MemoryError; #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+ wcslen(wszCOMMA)+wcslen(pwszOIDFormat)+1)); if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; //strcat the OID wcscat(pwsz, pwszOIDFormat); //strcat the , or '\n' if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(pwsz, wszCRLF); else { if(dwIndex!=(pInfo->cUsageIdentifier-1)) wcscat(pwsz, wszCOMMA); } LocalFree((HLOCAL)pwszOIDFormat); pwszOIDFormat=NULL; if(fOIDNameAllocated) free(pwszOIDName); pwszOIDName=NULL; } pwszFormat=pwsz; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwsz) free(pwsz); if(pwszOIDFormat) LocalFree((HLOCAL)pwszOIDFormat); if(fOIDNameAllocated) { if(pwszOIDName) free(pwszOIDName); } if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // GetOtherName: // // The idsPreFix is for multi line formatting only. // It should never be 0. //-------------------------------------------------------------------------- BOOL GetOtherName( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, CERT_OTHER_NAME *pOtherName, UINT idsPreFix, LPWSTR *ppwszOtherName) { BOOL fResult=FALSE; PCCRYPT_OID_INFO pOIDInfo=NULL; DWORD cbSize=0; WCHAR wszPreFix[PREFIX_SIZE]; LPWSTR pwszObjId = NULL; LPWSTR pwszName=NULL; LPWSTR pwszFormat=NULL; if(NULL == pOtherName || NULL == ppwszOtherName) goto InvalidArg; *ppwszOtherName=NULL; //get the OID name pOIDInfo=CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, pOtherName->pszObjId, 0); //get the value. If OID is szOID_NT_PRINCIPAL_NAME, we format it //as the unicode string. Otherwise, we hex dump if(0 == strcmp(szOID_NT_PRINCIPAL_NAME, pOtherName->pszObjId)) { //turn off the multi line here if(!FormatAnyUnicodeStringExtension( dwCertEncodingType, dwFormatType, dwFormatStrType & (~CRYPT_FORMAT_STR_MULTI_LINE), pFormatStruct, pOtherName->pszObjId, pOtherName->Value.pbData, pOtherName->Value.cbData, NULL, &cbSize)) goto FormatUnicodeError; pwszName=(LPWSTR)malloc(cbSize); if(NULL==pwszName) goto MemoryError; if(!FormatAnyUnicodeStringExtension( dwCertEncodingType, dwFormatType, dwFormatStrType & (~CRYPT_FORMAT_STR_MULTI_LINE), pFormatStruct, pOtherName->pszObjId, pOtherName->Value.pbData, pOtherName->Value.cbData, pwszName, &cbSize)) goto FormatUnicodeError; } else { if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType & (~CRYPT_FORMAT_STR_MULTI_LINE), pFormatStruct, NULL, pOtherName->Value.pbData, pOtherName->Value.cbData, NULL, &cbSize)) goto FormatByesToHexError; pwszName=(LPWSTR)malloc(cbSize); if(NULL==pwszName) goto MemoryError; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType & (~CRYPT_FORMAT_STR_MULTI_LINE), pFormatStruct, NULL, pOtherName->Value.pbData, pOtherName->Value.cbData, pwszName, &cbSize)) goto FormatByesToHexError; } if(pOIDInfo) { if(!FormatMessageUnicode(&pwszFormat, IDS_OTHER_NAME_OIDNAME, pOIDInfo->pwszName, pwszName)) goto FormatMsgError; } else { // // Convert OID to Unicode. // if (!AllocateAnsiToUnicode(pOtherName->pszObjId, &pwszObjId)) goto AnsiToUnicodeError; if(!FormatMessageUnicode(&pwszFormat,IDS_OTHER_NAME_OID, pwszObjId, pwszName)) goto FormatMsgError; } //copy the prefix and content if(!LoadStringU(hFrmtFuncInst,idsPreFix, wszPreFix, sizeof(wszPreFix)/sizeof(wszPreFix[0]))) goto LoadStringError; *ppwszOtherName=(LPWSTR)malloc(sizeof(WCHAR) * (wcslen(wszPreFix) + wcslen(pwszFormat) + 1)); if(NULL == *ppwszOtherName) goto MemoryError; **ppwszOtherName=L'\0'; if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) wcscat(*ppwszOtherName, wszPreFix); wcscat(*ppwszOtherName, pwszFormat); fResult=TRUE; CommonReturn: if (pwszObjId) free(pwszObjId); if(pwszName) free(pwszName); if(pwszFormat) LocalFree((HLOCAL)pwszFormat); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(FormatByesToHexError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(AnsiToUnicodeError); TRACE_ERROR(FormatUnicodeError); TRACE_ERROR(LoadStringError); TRACE_ERROR(FormatMsgError); } //-------------------------------------------------------------------------- // // FormatAltNameInfo: // //-------------------------------------------------------------------------- BOOL FormatAltNameInfo( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, UINT idsPreFix, BOOL fNewLine, PCERT_ALT_NAME_INFO pInfo, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwsz=NULL; LPWSTR pwszAltEntryFormat=NULL; LPWSTR pwszAltEntry=NULL; WCHAR wszNoInfo[NO_INFO_SIZE]; WCHAR wszAltName[ALT_NAME_SIZE]; WCHAR wszPreFix[PRE_FIX_SIZE]; BOOL fEntryAllocated=FALSE; DWORD dwIndex=0; DWORD cbNeeded=0; BOOL fResult=FALSE; HRESULT hr=S_OK; UINT idsAltEntryName=0; LPWSTR pwszTemp; //load the string "info not available" if(!LoadStringU(hFrmtFuncInst,IDS_NO_ALT_NAME, wszNoInfo, sizeof(wszNoInfo)/sizeof(wszNoInfo[0]))) goto LoadStringError; //build the list of alternative name entries //1st, check if any information is available if(0==pInfo->cAltEntry) { pwszFormat=wszNoInfo; } else { //load the pre-dix if(0!=idsPreFix) { if(!LoadStringU(hFrmtFuncInst, idsPreFix, wszPreFix, sizeof(wszPreFix)/sizeof(wszPreFix[0]))) goto LoadStringError; } pwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==pwsz) goto MemoryError; //NULL terminate the string *pwsz=L'\0'; //build the list of alternative name entries for(dwIndex=0; dwIndex<pInfo->cAltEntry; dwIndex++) { // DSIE: Fix bug 128630. cbNeeded = 0; fEntryAllocated=FALSE; switch((pInfo->rgAltEntry)[dwIndex].dwAltNameChoice) { case CERT_ALT_NAME_OTHER_NAME: if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsAltEntryName=IDS_OTHER_NAME_MULTI; else idsAltEntryName=IDS_OTHER_NAME; if(!GetOtherName( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, (pInfo->rgAltEntry)[dwIndex].pOtherName, (0!=idsPreFix) ? idsPreFix+1 : IDS_ONE_TAB, &pwszAltEntry)) goto GetOtherNameError; fEntryAllocated=TRUE; break; case CERT_ALT_NAME_RFC822_NAME: idsAltEntryName=IDS_RFC822_NAME; pwszAltEntry=(pInfo->rgAltEntry)[dwIndex].pwszRfc822Name; break; case CERT_ALT_NAME_DNS_NAME: idsAltEntryName=IDS_DNS_NAME; pwszAltEntry=(pInfo->rgAltEntry)[dwIndex].pwszDNSName; break; case CERT_ALT_NAME_X400_ADDRESS: idsAltEntryName=IDS_X400_ADDRESS; pwszAltEntry=wszNoInfo; break; case CERT_ALT_NAME_DIRECTORY_NAME: if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) idsAltEntryName=IDS_DIRECTORY_NAME_MULTI; else idsAltEntryName=IDS_DIRECTORY_NAME; if(!CryptDllFormatNameAll( dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, (0!=idsPreFix) ? idsPreFix+1 : IDS_ONE_TAB, TRUE, //memory allocation (pInfo->rgAltEntry)[dwIndex].DirectoryName.pbData, (pInfo->rgAltEntry)[dwIndex].DirectoryName.cbData, (void **)&pwszAltEntry, NULL)) goto GetCertNameError; fEntryAllocated=TRUE; break; case CERT_ALT_NAME_EDI_PARTY_NAME: idsAltEntryName=IDS_EDI_PARTY_NAME; pwszAltEntry=wszNoInfo; break; case CERT_ALT_NAME_URL: idsAltEntryName=IDS_URL; pwszAltEntry=(pInfo->rgAltEntry)[dwIndex].pwszURL; break; case CERT_ALT_NAME_IP_ADDRESS: idsAltEntryName=IDS_IP_ADDRESS; #if (0) // DSIE: 7/25/2000 if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, NULL, (pInfo->rgAltEntry)[dwIndex].IPAddress.pbData, (pInfo->rgAltEntry)[dwIndex].IPAddress.cbData, NULL, &cbNeeded)) goto FormatByesToHexError; pwszAltEntry=(LPWSTR)malloc(cbNeeded); if(NULL==pwszAltEntry) goto MemoryError; if(!FormatBytesToHex(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, NULL, (pInfo->rgAltEntry)[dwIndex].IPAddress.pbData, (pInfo->rgAltEntry)[dwIndex].IPAddress.cbData, pwszAltEntry, &cbNeeded)) goto FormatByesToHexError; #else if (!FormatIPAddress(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, NULL, idsPreFix, (pInfo->rgAltEntry)[dwIndex].IPAddress.pbData, (pInfo->rgAltEntry)[dwIndex].IPAddress.cbData, pwszAltEntry, &cbNeeded)) goto FormatIPAddressError; pwszAltEntry=(LPWSTR)malloc(cbNeeded); if(NULL==pwszAltEntry) goto MemoryError; if (!FormatIPAddress(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, NULL, idsPreFix, (pInfo->rgAltEntry)[dwIndex].IPAddress.pbData, (pInfo->rgAltEntry)[dwIndex].IPAddress.cbData, pwszAltEntry, &cbNeeded)) goto FormatIPAddressError; #endif fEntryAllocated=TRUE; break; case CERT_ALT_NAME_REGISTERED_ID: idsAltEntryName=IDS_REGISTERED_ID; if(S_OK!=(hr=SZtoWSZ((pInfo->rgAltEntry)[dwIndex].pszRegisteredID, &pwszAltEntry))) goto SZtoWSZError; fEntryAllocated=TRUE; break; default: idsAltEntryName=IDS_UNKNOWN_VALUE; pwszAltEntry=wszNoInfo; break; } //load the alternative name string if(!LoadStringU(hFrmtFuncInst,idsAltEntryName, wszAltName, sizeof(wszAltName)/sizeof(wszAltName[0]))) goto LoadStringError; //format message if(idsAltEntryName!=IDS_UNKNOWN_VALUE) { if(!FormatMessageUnicode(&pwszAltEntryFormat,IDS_ALT_NAME_ENTRY, wszAltName, pwszAltEntry)) goto FormatMsgError; } else { if(!FormatMessageUnicode(&pwszAltEntryFormat,IDS_ALT_NAME_ENTRY_UNKNOWN, wszAltName, (pInfo->rgAltEntry)[dwIndex].dwAltNameChoice)) goto FormatMsgError; } //concatenate the string, including the postfix and prefix if necessary if(0!=idsPreFix) { #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(wszPreFix)+wcslen(pwszAltEntryFormat)+1)); #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(wszPreFix)+wcslen(pwszAltEntryFormat)+1)); } else { #if (0) // DSIE: Bug 27436 pwsz=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszAltEntryFormat)+1)); #endif pwszTemp=(LPWSTR)realloc(pwsz, sizeof(WCHAR) * (wcslen(pwsz)+wcslen(wszCOMMA)+wcslen(pwszAltEntryFormat)+1)); } #if (0) // DSIE: Bug 27436 if(NULL==pwsz) goto MemoryError; #endif if(NULL==pwszTemp) goto MemoryError; pwsz = pwszTemp; //strcat the preFix if(0!=idsPreFix) wcscat(pwsz, wszPreFix); //strcat the entry wcscat(pwsz, pwszAltEntryFormat); //strcat the postFix if(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) { if((TRUE==fNewLine) || (dwIndex != (pInfo->cAltEntry-1))) { //no need for \n if the name is directory name (CERT_NAME) //in multi line format if(idsAltEntryName !=IDS_DIRECTORY_NAME_MULTI) wcscat(pwsz, wszCRLF); } } else { if(dwIndex != (pInfo->cAltEntry-1)) wcscat(pwsz, wszCOMMA); } LocalFree((HLOCAL)pwszAltEntryFormat); pwszAltEntryFormat=NULL; if(fEntryAllocated) free(pwszAltEntry); pwszAltEntry=NULL; } //if the last entry in the alternative name is IDS_DIRECTORY_NAME_MULTI, //we need to get rid of the last \n if fNewLine is FALSE if(FALSE==fNewLine) { if(idsAltEntryName==IDS_DIRECTORY_NAME_MULTI) { *(pwsz+wcslen(pwsz)-wcslen(wszCRLF))=L'\0'; } } //conver to the WCHAR format pwszFormat=pwsz; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwsz) free(pwsz); if(pwszAltEntryFormat) LocalFree((HLOCAL)pwszAltEntryFormat); if(fEntryAllocated) { if(pwszAltEntry) free(pwszAltEntry); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; TRACE_ERROR(LoadStringError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(FormatMsgError); SET_ERROR_VAR(SZtoWSZError, hr); TRACE_ERROR(GetCertNameError); #if (0) //DSIE TRACE_ERROR(FormatByesToHexError); #else TRACE_ERROR(FormatIPAddressError); #endif SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(GetOtherNameError); } //-------------------------------------------------------------------------- // // FormatAltName: X509_ALTERNATE_NAME // szOID_SUBJECT_ALT_NAME // szOID_ISSUER_ALT_NAME // szOID_SUBJECT_ALT_NAME2 // szOID_ISSUER_ALT_NAME2 // //-------------------------------------------------------------------------- static BOOL WINAPI FormatAltName( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult=FALSE; PCERT_ALT_NAME_INFO pInfo=NULL; //check for input parameters if((NULL==pbEncoded&& cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if(cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType,X509_ALTERNATE_NAME, pbEncoded,cbEncoded, (void **)&pInfo)) goto DecodeGenericError; fResult=FormatAltNameInfo(dwCertEncodingType, dwFormatType,dwFormatStrType, pFormatStruct, 0, TRUE, pInfo, pbFormat, pcbFormat); if(FALSE==fResult) goto FormatAltNameError; CommonReturn: if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(FormatAltNameError); } //-------------------------------------------------------------------------- // // GetCertNameMulti // // Get the multi line display of the certificate name //-------------------------------------------------------------------------- BOOL GetCertNameMulti(LPWSTR pwszNameStr, UINT idsPreFix, LPWSTR *ppwsz) { BOOL fResult=FALSE; WCHAR wszPreFix[PRE_FIX_SIZE]; LPWSTR pwszStart=NULL; LPWSTR pwszEnd=NULL; DWORD dwCopy=0; LPWSTR pwszNameStart=NULL; BOOL fDone=FALSE; BOOL fInQuote=FALSE; LPWSTR pwszTemp; //init *ppwsz=NULL; //load string for the preFix if(0!=idsPreFix && 1!=idsPreFix) { if(!LoadStringU(hFrmtFuncInst, idsPreFix, wszPreFix, PRE_FIX_SIZE)) goto LoadStringError; } *ppwsz=(LPWSTR)malloc(sizeof(WCHAR)); if(NULL==*ppwsz) goto MemoryError; **ppwsz=L'\0'; //now, start the search for the symbol '+' or ',' pwszStart=pwszNameStr; pwszEnd=pwszNameStr; //parse the whole string for(;FALSE==fDone; pwszEnd++) { //mark fInQuote to TRUE if we are inside " " if(L'\"'==*pwszEnd) fInQuote=!fInQuote; if((L'+'==*pwszEnd) || (L','==*pwszEnd) ||(L'\0'==*pwszEnd)) { //make sure + and ; are not quoted if((L'+'==*pwszEnd) || (L','==*pwszEnd)) { if(TRUE==fInQuote) continue; } //skip the leading spaces for(;*pwszStart != L'\0'; pwszStart++) { if(*pwszStart != L' ') break; } //we are done if NULL is reached if(L'\0'==*pwszStart) break; //calculate the length to copy dwCopy=(DWORD)(pwszEnd-pwszStart); if(0!=idsPreFix && 1!=idsPreFix) { #if (0) // DSIE: Bug 27436 *ppwsz=(LPWSTR)realloc(*ppwsz, (wcslen(*ppwsz)+dwCopy+wcslen(wszPreFix)+wcslen(wszCRLF)+1)*sizeof(WCHAR)); #endif pwszTemp=(LPWSTR)realloc(*ppwsz, (wcslen(*ppwsz)+dwCopy+wcslen(wszPreFix)+wcslen(wszCRLF)+1)*sizeof(WCHAR)); } else { #if (0) // DSIE: Bug 27436 *ppwsz=(LPWSTR)realloc(*ppwsz, (wcslen(*ppwsz)+dwCopy+wcslen(wszCRLF)+1)*sizeof(WCHAR)); #endif pwszTemp=(LPWSTR)realloc(*ppwsz, (wcslen(*ppwsz)+dwCopy+wcslen(wszCRLF)+1)*sizeof(WCHAR)); } #if (0) // DSIE: Bug 27436 if(NULL == *ppwsz) goto MemoryError; #endif if(NULL == pwszTemp) goto MemoryError; *ppwsz = pwszTemp; //copy the prefix if(0!=idsPreFix && 1!=idsPreFix) wcscat(*ppwsz, wszPreFix); pwszNameStart=(*ppwsz)+wcslen(*ppwsz); //copy the string to *ppwsz memcpy(pwszNameStart, pwszStart, dwCopy*sizeof(WCHAR)); pwszNameStart += dwCopy; //NULL terminate the string *pwszNameStart=L'\0'; //copy the "\n" wcscat(*ppwsz, wszCRLF); //reset pwszStart and pwszEnd. pwszStart=pwszEnd+1; if(L'\0'==*pwszEnd) fDone=TRUE; } } fResult=TRUE; CommonReturn: return fResult; ErrorReturn: if(*ppwsz) { free(*ppwsz); *ppwsz=NULL; } fResult=FALSE; goto CommonReturn; SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(LoadStringError); } //-------------------------------------------------------------------------- // // FormatMessageUnicode // //-------------------------------------------------------------------------- BOOL FormatMessageUnicode(LPWSTR * ppwszFormat, UINT ids, ...) { // get format string from resources WCHAR wszFormat[1000]; va_list argList; DWORD cbMsg=0; BOOL fResult=FALSE; if(NULL == ppwszFormat) goto InvalidArgErr; #if (0) //DSIE: Bug 160605 if(!LoadStringU(hFrmtFuncInst, ids, wszFormat, sizeof(wszFormat))) #else if(!LoadStringU(hFrmtFuncInst, ids, wszFormat, sizeof(wszFormat) / sizeof(wszFormat[0]))) #endif goto LoadStringError; // format message into requested buffer va_start(argList, ids); cbMsg = FormatMessageU( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_STRING, wszFormat, 0, // dwMessageId 0, // dwLanguageId (LPWSTR) (ppwszFormat), 0, // minimum size to allocate &argList); va_end(argList); if(!cbMsg) #if (1) // DSIE: Fix bug #128630 // // FormatMessageU() will return 0 byte, if data to be // formatted is empty. CertSrv generates extensions // with empty data for name constraints, so we need to // make sure we return an empty string, "", instead of // an error and NULL pointer. // if (0 == GetLastError()) { if (NULL == (*ppwszFormat = (LPWSTR) LocalAlloc(LPTR, sizeof(WCHAR)))) goto MemoryError; } else #endif goto FormatMessageError; fResult=TRUE; CommonReturn: return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; TRACE_ERROR(LoadStringError); TRACE_ERROR(FormatMessageError); SET_ERROR(InvalidArgErr, E_INVALIDARG); SET_ERROR(MemoryError, E_OUTOFMEMORY); } //-------------------------------------------------------------------------- // // FormatMessageStr // //-------------------------------------------------------------------------- /*BOOL FormatMessageStr(LPSTR *ppszFormat,UINT ids,...) { // get format string from resources CHAR szFormat[1000]; va_list argList; BOOL fResult=FALSE; HRESULT hr=S_OK; if(!LoadStringA(hFrmtFuncInst, ids, szFormat, sizeof(szFormat))) goto LoadStringError; // format message into requested buffer va_start(argList, ids); if(0==FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_STRING, szFormat, 0, // dwMessageId 0, // dwLanguageId (LPSTR) ppszFormat, 0, // minimum size to allocate &argList)) goto FormatMessageError; va_end(argList); fResult=TRUE; CommonReturn: return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; TRACE_ERROR(LoadStringError); TRACE_ERROR(FormatMessageError); } */ //-------------------------------------------------------------------------- // // Decode a generic BLOB // //-------------------------------------------------------------------------- BOOL DecodeGenericBLOB(DWORD dwEncodingType, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded,void **ppStructInfo) { DWORD cbStructInfo=0; //decode the object. No copying if(!CryptDecodeObject(dwEncodingType,lpszStructType,pbEncoded, cbEncoded, 0,NULL, &cbStructInfo)) return FALSE; *ppStructInfo=malloc(cbStructInfo); if(!(*ppStructInfo)) { SetLastError((DWORD) E_OUTOFMEMORY); return FALSE; } return CryptDecodeObject(dwEncodingType,lpszStructType,pbEncoded, cbEncoded, 0,*ppStructInfo,&cbStructInfo); } //////////////////////////////////////////////////////// // // Convert STR to WSTR // HRESULT SZtoWSZ(LPSTR szStr,LPWSTR *pwsz) { DWORD dwSize=0; DWORD dwError=0; *pwsz=NULL; //return NULL if(!szStr) return S_OK; dwSize=MultiByteToWideChar(0, 0,szStr, -1,NULL,0); if(dwSize==0) { dwError=GetLastError(); return HRESULT_FROM_WIN32(dwError); } //allocate memory *pwsz=(LPWSTR)malloc(dwSize * sizeof(WCHAR)); if(*pwsz==NULL) return E_OUTOFMEMORY; if(MultiByteToWideChar(0, 0,szStr, -1, *pwsz,dwSize)) { return S_OK; } else { free(*pwsz); *pwsz=NULL; dwError=GetLastError(); return HRESULT_FROM_WIN32(dwError); } } //-------------------------------------------------------------------------- // // Convert dwFormatType to dwStrType // //-------------------------------------------------------------------------- DWORD FormatToStr(DWORD dwFormatType) { DWORD dwStrType=0; //we default to CERT_X500_NAME_STR if(0==dwFormatType) { return CERT_X500_NAME_STR; } if(dwFormatType & CRYPT_FORMAT_SIMPLE) dwStrType |= CERT_SIMPLE_NAME_STR; if(dwFormatType & CRYPT_FORMAT_X509) dwStrType |= CERT_X500_NAME_STR; if(dwFormatType & CRYPT_FORMAT_OID) dwStrType |= CERT_OID_NAME_STR; if(dwFormatType & CRYPT_FORMAT_RDN_SEMICOLON) dwStrType |= CERT_NAME_STR_SEMICOLON_FLAG; if(dwFormatType & CRYPT_FORMAT_RDN_CRLF) dwStrType |= CERT_NAME_STR_CRLF_FLAG; if(dwFormatType & CRYPT_FORMAT_RDN_UNQUOTE) dwStrType |= CERT_NAME_STR_NO_QUOTING_FLAG; if(dwFormatType & CRYPT_FORMAT_RDN_REVERSE) dwStrType |= CERT_NAME_STR_REVERSE_FLAG; return dwStrType; } //+----------------------------------------------------------------------------- // Post Win2k. //------------------------------------------------------------------------------ //+----------------------------------------------------------------------------- // // FormatInteger X509_INTEGER // //------------------------------------------------------------------------------ static BOOL WINAPI FormatInteger ( DWORD dwCertEncodingType, DWORD dwFormatStrType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat, DWORD ids) { BOOL fResult; DWORD cbNeeded; int *pInfo = NULL; LPWSTR pwszFormat = NULL; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; // // Check input parameters. // if ((NULL == pbEncoded && 0 != cbEncoded) || (NULL == pcbFormat) || (0 == cbEncoded)) { goto InvalidArg; } // // Decode extension. // if (!DecodeGenericBLOB(dwCertEncodingType, X509_INTEGER, pbEncoded, cbEncoded, (void **)&pInfo)) { goto DecodeGenericError; } // // Some extension name=%1!d!%2!s! // if (!FormatMessageUnicode(&pwszFormat, ids, *pInfo, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } // // Total length needed. // cbNeeded = sizeof(WCHAR) * (wcslen(pwszFormat) + 1); // // length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbNeeded) { *pcbFormat = cbNeeded; goto MoreDataError; } // // Copy size and data. // memcpy(pbFormat, pwszFormat, cbNeeded); *pcbFormat = cbNeeded; SuccessReturn: fResult = TRUE; CommonReturn: // // Free resources. // if (pInfo) { free(pInfo); } if (pwszFormat) { LocalFree((HLOCAL) pwszFormat); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(FormatMessageError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //+----------------------------------------------------------------------------- // // FormatCrlNumber szOID_CRL_NUMBER // szOID_DELTA_CRL_INDICATOR // szOID_CRL_VIRTUAL_BASE // //------------------------------------------------------------------------------ static BOOL WINAPI FormatCrlNumber ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult; DWORD cbNeeded = 0; DWORD ids = 0; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; // // Check input parameters. // if ((NULL == pbEncoded && 0 != cbEncoded) || (NULL == pcbFormat) || (0 == cbEncoded)) { goto InvalidArg; } // // Decide between single line and mulitple line format. // if (bMultiLines) { ids = 0 == strcmp(lpszStructType, szOID_CRL_NUMBER) ? IDS_CRL_NUMBER : 0 == strcmp(lpszStructType, szOID_DELTA_CRL_INDICATOR) ? IDS_DELTA_CRL_INDICATOR : IDS_CRL_VIRTUAL_BASE; } else { ids = IDS_INTEGER; } // // Decode extension to get length. // // %1!d!%2!s! // CRL Number=%1!d!%2!s! // Delta CRL Number=%1!d!%2!s! // Virtual Base CRL Number=%1!d!%2!s! // if (!FormatInteger(dwCertEncodingType, dwFormatStrType, pbEncoded, cbEncoded, NULL, &cbNeeded, ids)) { goto FormatIntegerError; } // // length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbNeeded) { *pcbFormat = cbNeeded; goto MoreDataError; } // // Decode again to get data. // if (!FormatInteger(dwCertEncodingType, dwFormatStrType, pbEncoded, cbEncoded, pbFormat, &cbNeeded, ids)) { goto FormatIntegerError; } // // Copy size . // *pcbFormat = cbNeeded; SuccessReturn: fResult = TRUE; CommonReturn: return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); TRACE_ERROR(FormatIntegerError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //+----------------------------------------------------------------------------- // // FormatCrlNextPublish szOID_CRL_NEXT_PUBLISH // //------------------------------------------------------------------------------ static BOOL WINAPI FormatCrlNextPublish ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult; DWORD cbNeeded = 0; FILETIME * pInfo = NULL; LPWSTR pwszFileTime = NULL; LPWSTR pwszFormat = NULL; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; // // Check input parameters. // if ((NULL == pbEncoded && 0 != cbEncoded) || (NULL == pcbFormat) || (0 == cbEncoded)) { goto InvalidArg; } // // Decode extension. // if (!DecodeGenericBLOB(dwCertEncodingType, X509_CHOICE_OF_TIME, pbEncoded, cbEncoded, (void **) &pInfo)) { goto DecodeGenericError; } // // Get formatted date/time. // if (!FormatFileTime(pInfo, &pwszFileTime)) { goto FormatFileTimeError; } if (!FormatMessageUnicode(&pwszFormat, IDS_STRING, pwszFileTime, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } // // Total length needed. // cbNeeded = sizeof(WCHAR) * (wcslen(pwszFormat) + 1); // // length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbNeeded) { *pcbFormat = cbNeeded; goto MoreDataError; } // // Copy size and data. // memcpy(pbFormat, pwszFormat, cbNeeded); *pcbFormat = cbNeeded; SuccessReturn: fResult = TRUE; CommonReturn: if (pInfo) { free(pInfo); } if (pwszFileTime) { LocalFree((HLOCAL) pwszFileTime); } if (pwszFormat) { LocalFree((HLOCAL) pwszFormat); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); TRACE_ERROR(DecodeGenericError); TRACE_ERROR(FormatFileTimeError); TRACE_ERROR(FormatMessageError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //+----------------------------------------------------------------------------- // // FormatIssuingDistPoint X509_ISSUING_DIST_POINT // szOID_ISSUING_DIST_POINT // // typedef struct _CRL_ISSUING_DIST_POINT { // CRL_DIST_POINT_NAME DistPointName; // OPTIONAL // BOOL fOnlyContainsUserCerts; // BOOL fOnlyContainsCACerts; // CRYPT_BIT_BLOB OnlySomeReasonFlags; // OPTIONAL // BOOL fIndirectCRL; // } CRL_ISSUING_DIST_POINT, *PCRL_ISSUING_DIST_POINT; // // typedef struct _CRL_DIST_POINT_NAME { // DWORD dwDistPointNameChoice; // union { // CERT_ALT_NAME_INFO FullName; // 1 // // Not implemented IssuerRDN; // 2 // }; // } CRL_DIST_POINT_NAME, *PCRL_DIST_POINT_NAME; // //------------------------------------------------------------------------------ static BOOL WINAPI FormatIssuingDistPoint ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult; DWORD cbNeeded = 0; DWORD ids = 0; WCHAR wszYes[YES_NO_SIZE]; WCHAR wszNo[YES_NO_SIZE]; LPWSTR pwszTemp = NULL; LPWSTR pwszFormat = NULL; LPWSTR pwszPointName = NULL; LPWSTR pwszNameFormat = NULL; LPWSTR pwszOnlyContainsUserCerts = NULL; LPWSTR pwszOnlyContainsCACerts = NULL; LPWSTR pwszIndirectCRL = NULL; LPWSTR pwszCRLReason=NULL; LPWSTR pwszReasonFormat=NULL; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; PCRL_ISSUING_DIST_POINT pInfo = NULL; // // Check input parameters. // if ((NULL == pbEncoded && 0 != cbEncoded) || (NULL == pcbFormat) || (0 == cbEncoded)) { goto InvalidArg; } // // Decode extension. // if (!DecodeGenericBLOB(dwCertEncodingType, lpszStructType, pbEncoded, cbEncoded, (void **)&pInfo)) { goto DecodeGenericError; } // // Allocate format buffer. // if (!(pwszFormat = (LPWSTR) malloc(sizeof(WCHAR)))) { goto MemoryError; } *pwszFormat = L'\0'; // // Format distribution name, if exists. // if (CRL_DIST_POINT_NO_NAME != pInfo->DistPointName.dwDistPointNameChoice) { if (!FormatDistPointName(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, &(pInfo->DistPointName), &pwszPointName)) { goto FormatDistPointNameError; } // // Decide between single line and mulitple line format. // ids = bMultiLines ? IDS_ONLY_SOME_CRL_DIST_NAME_MULTI: IDS_ONLY_SOME_CRL_DIST_NAME; if (!FormatMessageUnicode(&pwszNameFormat, ids, pwszPointName)) { goto FormatMessageError; } // // Reallocate and concate to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + wcslen(pwszNameFormat) + 1)); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszNameFormat); LocalFree((HLOCAL) pwszPointName); pwszPointName = NULL; LocalFree((HLOCAL) pwszNameFormat); pwszNameFormat = NULL; } // // Format onlyContainsXXX fields. // if (!LoadStringU(hFrmtFuncInst, IDS_YES, wszYes, sizeof(wszYes) / sizeof(wszYes[0]))) { goto LoadStringError; } if (!LoadStringU(hFrmtFuncInst, IDS_NO, wszNo, sizeof(wszNo) / sizeof(wszNo[0]))) { goto LoadStringError; } // // %1!s!Only Contains User Certs=%2!s!%3!s! // if (!FormatMessageUnicode(&pwszOnlyContainsUserCerts, IDS_ONLY_CONTAINS_USER_CERTS, bMultiLines ? wszEMPTY : wszCOMMA, pInfo->fOnlyContainsUserCerts ? wszYes : wszNo, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } // // %1!s!Only Contains CA Certs=%2!s!%3!s! // if (!FormatMessageUnicode(&pwszOnlyContainsCACerts, IDS_ONLY_CONTAINS_CA_CERTS, bMultiLines ? wszEMPTY : wszCOMMA, pInfo->fOnlyContainsCACerts ? wszYes : wszNo, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } // // %1!s!Indirect CRL=%2!s!%3!s! // if (!FormatMessageUnicode(&pwszIndirectCRL, IDS_INDIRECT_CRL, bMultiLines ? wszEMPTY : wszCOMMA, pInfo->fIndirectCRL ? wszYes : wszNo, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } // // Reallocate and concate to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + wcslen(pwszOnlyContainsUserCerts) + wcslen(pwszOnlyContainsCACerts) + wcslen(pwszIndirectCRL) + 1)); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszOnlyContainsUserCerts); wcscat(pwszFormat, pwszOnlyContainsCACerts); wcscat(pwszFormat, pwszIndirectCRL); // // Format the CRL reason. // if (0 != pInfo->OnlySomeReasonFlags.cbData) { if (!FormatCRLReason(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, lpszStructType, &(pInfo->OnlySomeReasonFlags), &pwszCRLReason)) { goto FormatCRLReasonError; } // // Format Decide between single line and mulitple line format. // if (!FormatMessageUnicode(&pwszReasonFormat, bMultiLines ? IDS_CRL_DIST_REASON_MULTI : IDS_CRL_DIST_REASON, pwszCRLReason)) { goto FormatMessageError; } // // Reallocate and concate to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + wcslen(pwszReasonFormat) + 1)); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszReasonFormat); LocalFree((HLOCAL) pwszCRLReason); pwszCRLReason = NULL; LocalFree((HLOCAL) pwszReasonFormat); pwszReasonFormat = NULL; } // // length needed. // cbNeeded = sizeof(WCHAR) * (wcslen(pwszFormat) + 1); // // length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbNeeded) { *pcbFormat = cbNeeded; goto MoreDataError; } // // Copy size and data. // memcpy(pbFormat, pwszFormat, cbNeeded); *pcbFormat = cbNeeded; SuccessReturn: fResult = TRUE; CommonReturn: // // Free resources. // if (pwszCRLReason) { LocalFree((HLOCAL) pwszCRLReason); } if (pwszReasonFormat) { LocalFree((HLOCAL) pwszReasonFormat); } if(pwszIndirectCRL) { LocalFree((HLOCAL) pwszIndirectCRL); } if(pwszOnlyContainsCACerts) { LocalFree((HLOCAL) pwszOnlyContainsCACerts); } if(pwszOnlyContainsUserCerts) { LocalFree((HLOCAL) pwszOnlyContainsUserCerts); } if(pwszPointName) { LocalFree((HLOCAL) pwszPointName); } if (pwszNameFormat) { LocalFree((HLOCAL) pwszNameFormat); } if (pwszFormat) { free(pwszFormat); } if (pInfo) { free(pInfo); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); TRACE_ERROR(DecodeGenericError); SET_ERROR(MemoryError,E_OUTOFMEMORY); TRACE_ERROR(FormatDistPointNameError); TRACE_ERROR(LoadStringError); TRACE_ERROR(FormatCRLReasonError); TRACE_ERROR(FormatMessageError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //+----------------------------------------------------------------------------- // // FormatNameConstraintsSubtree. // // typedef struct _CERT_GENERAL_SUBTREE { // CERT_ALT_NAME_ENTRY Base; // DWORD dwMinimum; // BOOL fMaximum; // DWORD dwMaximum; // } CERT_GENERAL_SUBTREE, *PCERT_GENERAL_SUBTREE; // // // Note: Intended to be called only by FormatNameConstrants. So no validity // checks are done on parameters. // //------------------------------------------------------------------------------ //static BOOL FormatNameConstraintsSubtree ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, void *pbFormat, DWORD *pcbFormat, DWORD idSubtree, DWORD cSubtree, PCERT_GENERAL_SUBTREE pSubtree) { BOOL fResult; DWORD dwIndex; DWORD cbNeeded; WCHAR wszOneTab[PRE_FIX_SIZE] = wszEMPTY; LPWSTR pwszType = NULL; LPWSTR pwszSubtree = NULL; LPWSTR pwszAltName = NULL; LPWSTR pwszFormat = NULL; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; // // Any subtree? // if (0 == cSubtree) { // // Permitted=None%1!s! // Excluded=None%1!s! // if (IDS_NAME_CONSTRAINTS_PERMITTED == idSubtree) { idSubtree = IDS_NAME_CONSTRAINTS_PERMITTED_NONE; } else // if (IDS_NAME_CONSTRAINTS_EXCLUDED == idSubtree) { idSubtree = IDS_NAME_CONSTRAINTS_EXCLUDED_NONE; } if (!FormatMessageUnicode(&pwszType, idSubtree, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } } else { // // "Permitted%1!s!" // "Excluded%1!s!" // if (!FormatMessageUnicode(&pwszType, idSubtree, bMultiLines ? wszCRLF : wszCOLON)) { goto FormatMessageError; } // // Load tab strings. // if (!LoadStringU(hFrmtFuncInst, IDS_ONE_TAB, wszOneTab, sizeof(wszOneTab) / sizeof(wszOneTab[0]))) { goto LoadStringError; } } // // Allocate format buffer. // if (!(pwszFormat = (LPWSTR) malloc(sizeof(WCHAR) * (wcslen(pwszType) + 1)))) { goto MemoryError; } // // Initialize formatted string. // wcscpy(pwszFormat, pwszType); // // Format each subtree parts. // for (dwIndex = 0; dwIndex < cSubtree; dwIndex++, pSubtree++) { LPWSTR pwszTemp; // // Maximum specified? // if (pSubtree->fMaximum) { // // "%1!s![%2!d!]Subtrees (%3!d!..%4!d!):%5!s!" // if (!FormatMessageUnicode(&pwszSubtree, IDS_NAME_CONSTRAINTS_SUBTREE, bMultiLines ? wszOneTab : dwIndex ? wszCOMMA : wszEMPTY, dwIndex + 1, pSubtree->dwMinimum, pSubtree->dwMaximum, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } } else { // // "%1!s![%2!d!]Subtrees (%3!d!...):%4!s" // if (!FormatMessageUnicode(&pwszSubtree, IDS_NAME_CONSTRAINTS_SUBTREE_NO_MAX, bMultiLines ? wszOneTab : dwIndex ? wszCOMMA : wszEMPTY, dwIndex + 1, pSubtree->dwMinimum, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } } // // Reallocate and concate to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + 1 + wcslen(pwszSubtree))); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszSubtree); LocalFree((HLOCAL) pwszSubtree); pwszSubtree = NULL; // // Format name. // CERT_ALT_NAME_INFO CertAltNameInfo; memset(&CertAltNameInfo, 0, sizeof(CERT_ALT_NAME_INFO)); CertAltNameInfo.cAltEntry = 1; CertAltNameInfo.rgAltEntry = &(pSubtree->Base); // Need to tell if it is for multi line format. We need two \t\t // in front of each alt name entry DWORD ids = bMultiLines ? IDS_TWO_TABS : 0; // Get the alternative name entry cbNeeded = 0; if (!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, ids, FALSE, &CertAltNameInfo, NULL, &cbNeeded)) { goto FormatAltNameError; } if (NULL == (pwszAltName = (LPWSTR) malloc(cbNeeded))) { goto MemoryError; } if (!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, ids, FALSE, &CertAltNameInfo, pwszAltName, &cbNeeded)) { goto FormatAltNameError; } // // Append "\r\n" if multi-line. // if (bMultiLines) { pwszTemp = (LPWSTR) realloc(pwszAltName, sizeof(WCHAR) * (wcslen(pwszAltName) + wcslen(wszCRLF) + 1)); if (NULL == pwszTemp) { goto MemoryError; } pwszAltName = pwszTemp; wcscat(pwszAltName, wszCRLF); } // // Reallocate and concate to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + 1 + wcslen(pwszAltName))); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszAltName); free(pwszAltName); pwszAltName = NULL; } // // Total length needed. // cbNeeded = sizeof(WCHAR) * (wcslen(pwszFormat) + 1); // // length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbNeeded) { *pcbFormat = cbNeeded; goto MoreDataError; } // // Copy size and data. // memcpy(pbFormat, pwszFormat, cbNeeded); *pcbFormat = cbNeeded; SuccessReturn: fResult = TRUE; CommonReturn: // // Free resources. // if (pwszType) { LocalFree((HLOCAL) pwszType); } if (pwszSubtree) { LocalFree((HLOCAL) pwszSubtree); } if (pwszAltName) { free((HLOCAL) pwszAltName); } if (pwszFormat) { free(pwszFormat); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; TRACE_ERROR(FormatMessageError); TRACE_ERROR(LoadStringError); SET_ERROR(MemoryError,E_OUTOFMEMORY); TRACE_ERROR(FormatAltNameError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //+----------------------------------------------------------------------------- // // FormatNameConstrains: szOID_NAME_CONSTRAINTS // X509_NAME_CONSTRAINTS // // typedef struct _CERT_NAME_CONSTRAINTS_INFO { // DWORD cPermittedSubtree; // PCERT_GENERAL_SUBTREE rgPermittedSubtree; // DWORD cExcludedSubtree; // PCERT_GENERAL_SUBTREE rgExcludedSubtree; // } CERT_NAME_CONSTRAINTS_INFO, *PCERT_NAME_CONSTRAINTS_INFO; // //------------------------------------------------------------------------------ //static BOOL WINAPI FormatNameConstraints ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult = FALSE; DWORD cbPermitNeeded = 0; DWORD cbExcludeNeeded = 0; DWORD cbTotalNeeded = 0; PCERT_NAME_CONSTRAINTS_INFO pInfo = NULL; // // Check input parameters. // if ((NULL == pbEncoded && 0 != cbEncoded) || (NULL == pcbFormat) || (0 == cbEncoded)) { goto InvalidArg; } // // Decode extension. // if (!DecodeGenericBLOB(dwCertEncodingType, lpszStructType, pbEncoded, cbEncoded, (void **)&pInfo)) { goto DecodeGenericError; } // // Find out memory size needed. // if ((!FormatNameConstraintsSubtree(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, NULL, &cbPermitNeeded, IDS_NAME_CONSTRAINTS_PERMITTED, pInfo->cPermittedSubtree, pInfo->rgPermittedSubtree)) || (!FormatNameConstraintsSubtree(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, NULL, &cbExcludeNeeded, IDS_NAME_CONSTRAINTS_EXCLUDED, pInfo->cExcludedSubtree, pInfo->rgExcludedSubtree))) { goto ErrorReturn; } // // Total length needed. // cbTotalNeeded = cbPermitNeeded + cbExcludeNeeded; if (0 == cbTotalNeeded) { *pcbFormat = cbTotalNeeded; goto SuccessReturn; } // // One char less after we concate both strings. // if (cbPermitNeeded > 0 && cbExcludeNeeded > 0) { cbTotalNeeded -= sizeof(WCHAR); // // If not multi-lines and both strings are present, allow 2 more // chars for ", " to separate the strings. // if (!(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE)) { cbTotalNeeded += sizeof(WCHAR) * wcslen(wszCOMMA); } } // // length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbTotalNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbTotalNeeded) { *pcbFormat = cbTotalNeeded; goto MoreDataError; } // // Now format both subtrees. // if (!FormatNameConstraintsSubtree(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, pbFormat, &cbPermitNeeded, IDS_NAME_CONSTRAINTS_PERMITTED, pInfo->cPermittedSubtree, pInfo->rgPermittedSubtree)) { goto ErrorReturn; } // // If not multi-lines and both strings are present, then add ", " // to separate them. // if (!(dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE) && (cbPermitNeeded > 0) && (cbExcludeNeeded > 0)) { wcscat((LPWSTR) pbFormat, wszCOMMA); } pbFormat = (void *) ((BYTE *) pbFormat + wcslen((LPWSTR) pbFormat) * sizeof(WCHAR)); if (!FormatNameConstraintsSubtree(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, pbFormat, &cbExcludeNeeded, IDS_NAME_CONSTRAINTS_EXCLUDED, pInfo->cExcludedSubtree, pInfo->rgExcludedSubtree)) { goto ErrorReturn; } // // Copy the size needed. // *pcbFormat = cbTotalNeeded; SuccessReturn: fResult = TRUE; CommonReturn: // // Free resources. // if (pInfo) { free(pInfo); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); TRACE_ERROR(DecodeGenericError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //+----------------------------------------------------------------------------- // // FormatCertSrvPreviousCertHash szOID_CERTSRV_PREVIOUS_CERT_HASH // //------------------------------------------------------------------------------ static BOOL WINAPI FormatCertSrvPreviousCertHash ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult; DWORD cbNeeded = 0; CRYPT_DATA_BLOB * pInfo = NULL; WCHAR * pwszHex = NULL; WCHAR * pwszFormat = NULL; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; // // Check input parameters. // if ((NULL == pbEncoded && 0 != cbEncoded) || (NULL == pcbFormat) || (0 == cbEncoded)) { goto InvalidArg; } // // Decode extension. // if (!DecodeGenericBLOB(dwCertEncodingType, X509_OCTET_STRING, pbEncoded, cbEncoded, (void **) &pInfo)) { goto DecodeGenericError; } // // Get formatted hex string. // if(!FormatBytesToHex(0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->pbData, pInfo->cbData, NULL, &cbNeeded)) { goto FormatBytesToHexError; } if (!(pwszHex = (LPWSTR) malloc(cbNeeded))) { goto MemoryError; } if(!FormatBytesToHex(0, dwFormatType, dwFormatStrType, pFormatStruct, NULL, pInfo->pbData, pInfo->cbData, pwszHex, &cbNeeded)) { goto FormatBytesToHexError; } if (!FormatMessageUnicode(&pwszFormat, IDS_STRING, pwszHex, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } // // Total length needed. // cbNeeded = sizeof(WCHAR) * (wcslen(pwszFormat) + 1); // // Length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbNeeded) { *pcbFormat = cbNeeded; goto MoreDataError; } // // Copy size and data. // memcpy(pbFormat, pwszFormat, cbNeeded); *pcbFormat = cbNeeded; SuccessReturn: fResult = TRUE; CommonReturn: if (pInfo) { free(pInfo); } if (pwszHex) { free(pwszHex); } if (pwszFormat) { LocalFree((HLOCAL) pwszFormat); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); TRACE_ERROR(DecodeGenericError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatBytesToHexError); TRACE_ERROR(FormatMessageError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //+----------------------------------------------------------------------------- // // FormatPolicyMappings X509_POLICY_MAPPINGS // szOID_POLICY_MAPPINGS // szOID_APPLICATION_POLICY_MAPPINGS // //------------------------------------------------------------------------------ static BOOL WINAPI FormatPolicyMappings ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult; DWORD dwIndex = 0; DWORD cbNeeded = 0; char szEmpty[1] = {'\0'}; LPSTR pszObjectId = NULL; LPWSTR pwszFormat = NULL; LPWSTR pwszTemp = NULL; LPWSTR pwszLine = NULL; LPWSTR pwszPolicy = NULL; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; CERT_POLICY_MAPPINGS_INFO * pInfo = NULL; // // Check input parameters. // if ((NULL == pbEncoded && 0 != cbEncoded) || (NULL == pcbFormat) || (0 == cbEncoded)) { goto InvalidArg; } // // Decode extension. // if (!DecodeGenericBLOB(dwCertEncodingType, X509_POLICY_MAPPINGS, pbEncoded, cbEncoded, (void **) &pInfo)) { goto DecodeGenericError; } // // Make sure data is valid. // if (pInfo->cPolicyMapping && !pInfo->rgPolicyMapping) { goto BadDataError; } // // Initialize formatted string. // if (!(pwszFormat = (LPWSTR) malloc(sizeof(WCHAR)))) { goto MemoryError; } *pwszFormat = NULL; // // Loop thru each mapping. // for (dwIndex = 0; dwIndex < pInfo->cPolicyMapping; dwIndex++) { // // Format Issuer Domain Policy, if available. // if (pInfo->rgPolicyMapping[dwIndex].pszIssuerDomainPolicy) { pszObjectId = pInfo->rgPolicyMapping[dwIndex].pszIssuerDomainPolicy; } else { pszObjectId = szEmpty; } if (!FormatObjectId(pszObjectId, CRYPT_POLICY_OID_GROUP_ID, FALSE, &pwszPolicy)) { goto FormatObjectIdError; } // // "[%1!d!]Issuer Domain=%2!s!%3!s!" // if (!FormatMessageUnicode(&pwszLine, IDS_ISSUER_DOMAIN_POLICY, dwIndex + 1, pwszPolicy, bMultiLines ? wszCRLF : wszCOMMA)) { goto FormatMessageError; } // // Reallocate and concate line to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + wcslen(pwszLine) + 1)); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszLine); LocalFree((HLOCAL) pwszPolicy); pwszPolicy = NULL; LocalFree((HLOCAL) pwszLine); pwszLine = NULL; // // Format Subject Domain Policy, if available. // if (pInfo->rgPolicyMapping[dwIndex].pszSubjectDomainPolicy) { pszObjectId = pInfo->rgPolicyMapping[dwIndex].pszSubjectDomainPolicy; } else { pszObjectId = szEmpty; } if (!FormatObjectId(pszObjectId, CRYPT_POLICY_OID_GROUP_ID, FALSE, &pwszPolicy)) { goto FormatObjectIdError; } // // "%1!s!Subject Domain=%2!s!%3!s!" // if (!FormatMessageUnicode(&pwszLine, IDS_SUBJECT_DOMAIN_POLICY, bMultiLines ? wszTAB : wszEMPTY, pwszPolicy, bMultiLines ? wszCRLF : (dwIndex + 1) < pInfo->cPolicyMapping ? wszCOMMA : wszEMPTY)) { goto FormatMessageError; } // // Reallocate and concate line to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + wcslen(pwszLine) + 1)); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszLine); LocalFree((HLOCAL) pwszPolicy); pwszPolicy = NULL; LocalFree((HLOCAL) pwszLine); pwszLine = NULL; } // // Total length needed. // cbNeeded = sizeof(WCHAR) * (wcslen(pwszFormat) + 1); // // Length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbNeeded) { *pcbFormat = cbNeeded; goto MoreDataError; } // // Copy size and data. // memcpy(pbFormat, pwszFormat, cbNeeded); *pcbFormat = cbNeeded; SuccessReturn: fResult = TRUE; CommonReturn: if (pwszLine) { LocalFree((HLOCAL) pwszLine); } if (pwszPolicy) { LocalFree((HLOCAL) pwszPolicy); } if (pwszFormat) { free(pwszFormat); } if (pInfo) { free(pInfo); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); TRACE_ERROR(DecodeGenericError); SET_ERROR(BadDataError, E_POINTER); TRACE_ERROR(FormatObjectIdError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatMessageError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //+----------------------------------------------------------------------------- // // FormatPolicyConstraints X509_POLICY_CONSTRAINTS // szOID_POLICY_CONSTRAINTS // szOID_APPLICATION_POLICY_CONSTRAINTS // //------------------------------------------------------------------------------ static BOOL WINAPI FormatPolicyConstraints ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult; DWORD cbNeeded = 0; LPWSTR pwszFormat = NULL; LPWSTR pwszTemp = NULL; LPWSTR pwszLine = NULL; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; CERT_POLICY_CONSTRAINTS_INFO * pInfo = NULL; // // Check input parameters. // if ((NULL == pbEncoded && 0 != cbEncoded) || (NULL == pcbFormat) || (0 == cbEncoded)) { goto InvalidArg; } // // Decode extension. // if (!DecodeGenericBLOB(dwCertEncodingType, X509_POLICY_CONSTRAINTS, pbEncoded, cbEncoded, (void **) &pInfo)) { goto DecodeGenericError; } // // Initialize formatted string. // if (!(pwszFormat = (LPWSTR) malloc(sizeof(WCHAR)))) { goto MemoryError; } *pwszFormat = NULL; // // Format Required Explicit Policy Skip Certs, if available. // if (pInfo->fRequireExplicitPolicy) { // // "Required Explicit Policy Skip Certs=%1!d!%2!s!" // if (!FormatMessageUnicode(&pwszLine, IDS_REQUIRED_EXPLICIT_POLICY_SKIP_CERTS, pInfo->dwRequireExplicitPolicySkipCerts, bMultiLines ? wszCRLF : wszCOMMA)) { goto FormatMessageError; } // // Reallocate and concate line to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + wcslen(pwszLine) + 1)); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszLine); LocalFree((HLOCAL) pwszLine); pwszLine = NULL; } // // Format Inhibit Policy Mapping Skip Certs, if available. // if (pInfo->fInhibitPolicyMapping) { // // "Inhibit Policy Mapping Skip Certs=%1!d!%2!s!" // if (!FormatMessageUnicode(&pwszLine, IDS_INHIBIT_POLICY_MAPPING_SKIP_CERTS, pInfo->dwInhibitPolicyMappingSkipCerts, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } // // Reallocate and concate line to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + wcslen(pwszLine) + 1)); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszLine); LocalFree((HLOCAL) pwszLine); pwszLine = NULL; } // // Total length needed. // cbNeeded = sizeof(WCHAR) * (wcslen(pwszFormat) + 1); // // Length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbNeeded) { *pcbFormat = cbNeeded; goto MoreDataError; } // // Copy size and data. // memcpy(pbFormat, pwszFormat, cbNeeded); *pcbFormat = cbNeeded; SuccessReturn: fResult = TRUE; CommonReturn: if (pwszLine) { LocalFree((HLOCAL) pwszLine); } if (pwszFormat) { free(pwszFormat); } if (pInfo) { free(pInfo); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); TRACE_ERROR(DecodeGenericError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatMessageError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //+----------------------------------------------------------------------------- // // FormatCertificateTemplate X509_CERTIFICATE_TEMPLATE // szOID_CERTIFICATE_TEMPLATE // //------------------------------------------------------------------------------ static BOOL WINAPI FormatCertificateTemplate ( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { BOOL fResult; DWORD cbNeeded = 0; LPWSTR pwszFormat = NULL; LPWSTR pwszObjId = NULL; LPWSTR pwszTemp = NULL; LPWSTR pwszLine = NULL; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; CERT_TEMPLATE_EXT * pInfo = NULL; // // Check input parameters. // if ((NULL == pbEncoded && 0 != cbEncoded) || (NULL == pcbFormat) || (0 == cbEncoded)) { goto InvalidArg; } // // Decode extension. // if (!DecodeGenericBLOB(dwCertEncodingType, X509_CERTIFICATE_TEMPLATE, pbEncoded, cbEncoded, (void **) &pInfo)) { goto DecodeGenericError; } // // Initialize formatted string. // if (!(pwszFormat = (LPWSTR) malloc(sizeof(WCHAR)))) { goto MemoryError; } *pwszFormat = NULL; #if (0) //DSIE: Bug 157853 // // Convert OID to Unicode. // if (!AllocateAnsiToUnicode(pInfo->pszObjId, &pwszObjId)) { goto AnsiToUnicodeError; } #else if (!FormatObjectId(pInfo->pszObjId, CRYPT_TEMPLATE_OID_GROUP_ID, FALSE, &pwszObjId)) { goto FormatObjectIdError; } #endif // // "Template=%1!s!%2!s!Major Version Number=%3!d!%4!s!" // if (!FormatMessageUnicode(&pwszLine, IDS_CERTIFICATE_TEMPLATE_MAJOR_VERSION, pwszObjId, bMultiLines ? wszCRLF : wszCOMMA, pInfo->dwMajorVersion, bMultiLines ? wszCRLF : wszCOMMA)) { goto FormatMessageError; } // // Reallocate and concate line to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + wcslen(pwszLine) + 1)); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszLine); LocalFree((HLOCAL) pwszLine); pwszLine = NULL; // // Format Minor Version, if available. // if (pInfo->fMinorVersion) { // // "Minor Version Number=%1!d!%2!s!" // if (!FormatMessageUnicode(&pwszLine, IDS_CERTIFICATE_TEMPLATE_MINOR_VERSION, pInfo->dwMinorVersion, bMultiLines ? wszCRLF : wszEMPTY)) { goto FormatMessageError; } // // Reallocate and concate line to format buffer. // pwszTemp = (LPWSTR) realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat) + wcslen(pwszLine) + 1)); if (NULL == pwszTemp) { goto MemoryError; } pwszFormat = pwszTemp; wcscat(pwszFormat, pwszLine); LocalFree((HLOCAL) pwszLine); pwszLine = NULL; } // // Total length needed. // cbNeeded = sizeof(WCHAR) * (wcslen(pwszFormat) + 1); // // Length only calculation? // if (NULL == pbFormat) { *pcbFormat = cbNeeded; goto SuccessReturn; } // // Caller provided us with enough memory? // if (*pcbFormat < cbNeeded) { *pcbFormat = cbNeeded; goto MoreDataError; } // // Copy size and data. // memcpy(pbFormat, pwszFormat, cbNeeded); *pcbFormat = cbNeeded; SuccessReturn: fResult = TRUE; CommonReturn: if (pwszObjId) { #if (0) //DSIE: Bug 157853 free(pwszObjId); #else LocalFree((HLOCAL) pwszObjId); #endif } if (pwszLine) { LocalFree((HLOCAL) pwszLine); } if (pwszFormat) { free(pwszFormat); } if (pInfo) { free(pInfo); } return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg,E_INVALIDARG); TRACE_ERROR(DecodeGenericError); SET_ERROR(MemoryError, E_OUTOFMEMORY); #if (0) //DSIE: Bug 157853 TRACE_ERROR(AnsiToUnicodeError); #else TRACE_ERROR(FormatObjectIdError); #endif TRACE_ERROR(FormatMessageError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); } //-------------------------------------------------------------------------- // // FormatXCertDistPoints: X509_CROSS_CERT_DIST_POINTS // szOID_CROSS_CERT_DIST_POINTS //-------------------------------------------------------------------------- static BOOL WINAPI FormatXCertDistPoints( DWORD dwCertEncodingType, DWORD dwFormatType, DWORD dwFormatStrType, void *pFormatStruct, LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, void *pbFormat, DWORD *pcbFormat) { LPWSTR pwszFormat=NULL; LPWSTR pwszDeltaTime=NULL; LPWSTR pwszEntryLine=NULL; LPWSTR pwszDistPoint=NULL; PCROSS_CERT_DIST_POINTS_INFO pInfo=NULL; DWORD cbNeeded=0; DWORD dwIndex=0; BOOL fResult=FALSE; BOOL bMultiLines = dwFormatStrType & CRYPT_FORMAT_STR_MULTI_LINE; LPWSTR pwszTemp; //check for input parameters if ((NULL==pbEncoded && cbEncoded!=0) || (NULL==pcbFormat)) goto InvalidArg; if (cbEncoded==0) { *pcbFormat=0; goto InvalidArg; } if (!DecodeGenericBLOB(dwCertEncodingType, lpszStructType, pbEncoded, cbEncoded, (void **)&pInfo)) goto DecodeGenericError; // // "Delta Sync Time=%1!d! seconds%2!s!" // if (!FormatMessageUnicode(&pwszDeltaTime, IDS_XCERT_DELTA_SYNC_TIME, pInfo->dwSyncDeltaTime, bMultiLines ? wszCRLF : wszCOMMA)) { goto FormatMessageError; } pwszFormat=(LPWSTR)malloc(sizeof(WCHAR) * (wcslen(pwszDeltaTime)+1)); if(NULL==pwszFormat) goto MemoryError; wcscpy(pwszFormat, pwszDeltaTime); //format the xcert dist point entries. for (dwIndex=0; dwIndex<pInfo->cDistPoint; dwIndex++) { cbNeeded=0; if (!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, bMultiLines ? IDS_ONE_TAB : 0, FALSE, &pInfo->rgDistPoint[dwIndex], NULL, &cbNeeded)) goto FormatAltNameError; pwszEntryLine=(LPWSTR)malloc(cbNeeded); if (NULL==pwszEntryLine) goto MemoryError; if (!FormatAltNameInfo(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, bMultiLines ? IDS_ONE_TAB : 0, FALSE, &pInfo->rgDistPoint[dwIndex], pwszEntryLine, &cbNeeded)) goto FormatAltNameError; //"[%1!d!]Cross-Certificate Distribution Point: %2!s!%3!s!%4!s!" if(!FormatMessageUnicode(&pwszDistPoint, IDS_XCERT_DIST_POINT, dwIndex + 1, bMultiLines ? wszCRLF : wszEMPTY, pwszEntryLine, bMultiLines || (dwIndex == pInfo->cDistPoint - 1) ? wszCRLF : wszCOMMA)) goto FormatMessageError; pwszTemp=(LPWSTR)realloc(pwszFormat, sizeof(WCHAR) * (wcslen(pwszFormat)+wcslen(pwszDistPoint)+1)); if(NULL==pwszTemp) goto MemoryError; pwszFormat = pwszTemp; wcscat(pwszFormat, pwszDistPoint); //free memory free(pwszEntryLine); pwszEntryLine=NULL; LocalFree((HLOCAL) pwszDistPoint); pwszDistPoint=NULL; } if(0==wcslen(pwszFormat)) { //no data pwszFormat=(LPWSTR)malloc(sizeof(WCHAR)*(NO_INFO_SIZE+1)); if(NULL==pwszFormat) goto MemoryError; if(!LoadStringU(hFrmtFuncInst,IDS_NO_INFO, pwszFormat, NO_INFO_SIZE)) goto LoadStringError; } cbNeeded=sizeof(WCHAR)*(wcslen(pwszFormat)+1); //length only calculation if(NULL==pbFormat) { *pcbFormat=cbNeeded; fResult=TRUE; goto CommonReturn; } if((*pcbFormat)<cbNeeded) { *pcbFormat=cbNeeded; goto MoreDataError; } //copy the data memcpy(pbFormat, pwszFormat, cbNeeded); //copy the size *pcbFormat=cbNeeded; fResult=TRUE; CommonReturn: if(pwszDeltaTime) LocalFree((HLOCAL) pwszDeltaTime); if(pwszDistPoint) LocalFree((HLOCAL) pwszDistPoint); if(pwszEntryLine) free(pwszEntryLine); if (pwszFormat) free(pwszFormat); if(pInfo) free(pInfo); return fResult; ErrorReturn: fResult=FALSE; goto CommonReturn; SET_ERROR(InvalidArg, E_INVALIDARG); TRACE_ERROR(DecodeGenericError); SET_ERROR(MoreDataError,ERROR_MORE_DATA); TRACE_ERROR(LoadStringError); TRACE_ERROR(FormatMessageError); SET_ERROR(MemoryError, E_OUTOFMEMORY); TRACE_ERROR(FormatAltNameError); }
27.44796
158
0.528697
[ "object" ]
031a9f07d7049751eac5bfc23fa62702941e9299
407
cpp
C++
input/ex1-dag/Professor.cpp
d3rail0/dependency-resolver
dbfa106b097d18973b8b085a29852f573476a85f
[ "MIT" ]
1
2022-01-26T16:58:20.000Z
2022-01-26T16:58:20.000Z
input/ex2-dcg/Professor.cpp
d3rail0/dependency-resolver
dbfa106b097d18973b8b085a29852f573476a85f
[ "MIT" ]
null
null
null
input/ex2-dcg/Professor.cpp
d3rail0/dependency-resolver
dbfa106b097d18973b8b085a29852f573476a85f
[ "MIT" ]
null
null
null
#include "Professor.h" std::ostream& operator<<(std::ostream& os, const Professor& professor) { os << professor.getName() << " " << professor.getAge() << " " << "Teaching subjecs = ["; std::vector<Subject> teSubs = professor.getTeachingSubjects(); for (size_t i = 0; i < teSubs.size(); i++) { os << teSubs[i].name; if (i == teSubs.size() - 1) break; os << ", "; } return os << "]"; }
22.611111
72
0.572482
[ "vector" ]
031aaacbb29d5c2e0b9ac5a2599332f5984f5ec6
479
cpp
C++
examples/ejemplo3.cpp
so77id/Programing-examples
051b706318703a4126af0595b21f7b4aceecbc4a
[ "MIT" ]
null
null
null
examples/ejemplo3.cpp
so77id/Programing-examples
051b706318703a4126af0595b21f7b4aceecbc4a
[ "MIT" ]
null
null
null
examples/ejemplo3.cpp
so77id/Programing-examples
051b706318703a4126af0595b21f7b4aceecbc4a
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <stdio.h> using namespace std; int main() { int base, ex, resultado, limite,r2; cin>>limite; cin>>ex; base=limite; resultado=0; r2=resultado; while (ex>0){ limite = base; while(limite>0){ resultado=resultado+base; limite--; } ex--; } cout<<resultado << endl;; return 0; }
14.96875
38
0.544885
[ "vector" ]
032393c6544e74588e03d8c756223798dcf014cd
97,522
cpp
C++
test/core/integration/MultipleLanguage_2_Test.cpp
SRCH2/srch2-ngn
925f36971aa6a8b31cdc59f7992790169e97ee00
[ "BSD-3-Clause" ]
14
2016-01-15T20:26:54.000Z
2018-11-26T20:47:43.000Z
test/core/integration/MultipleLanguage_2_Test.cpp
SRCH2/srch2-ngn
925f36971aa6a8b31cdc59f7992790169e97ee00
[ "BSD-3-Clause" ]
2
2016-04-26T05:29:01.000Z
2016-05-07T00:13:38.000Z
test/core/integration/MultipleLanguage_2_Test.cpp
SRCH2/srch2-ngn
925f36971aa6a8b31cdc59f7992790169e97ee00
[ "BSD-3-Clause" ]
7
2016-02-27T11:35:59.000Z
2018-11-26T20:47:59.000Z
/* * Copyright (c) 2016, SRCH2 * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the SRCH2 nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SRCH2 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. */ /* * MultipleLanguage_2_Test.cpp * * Created on: Oct 3, 2013 */ #include <instantsearch/Analyzer.h> #include "operation/IndexerInternal.h" #include <instantsearch/QueryEvaluator.h> #include <instantsearch/Query.h> #include <instantsearch/Term.h> #include <instantsearch/Schema.h> #include <instantsearch/Record.h> #include <instantsearch/QueryResults.h> #include "util/Assert.h" #include "IntegrationTestHelper.h" #include <stdlib.h> #include <time.h> #include <iostream> #include <cstdlib> #include <sstream> #include <fstream> #include <string> #include <vector> #include <cstring> using namespace std; namespace srch2is = srch2::instantsearch; using namespace srch2is; string DBLP_INDEX_DIR = getenv("dblp_index_dir"); string INDEX_DIR = getenv("small_index_dir"); //from http://novel.tingroom.com/ translated by google void addPolishRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "dyskursów"); record->setSearchableAttributeValue("article_sentence", "Ze wszystkich kierunków, znajdziesz nie jeden, który jest w stanie kontemplacji się"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "Przemówienie zachodniej Sadzenie"); record->setSearchableAttributeValue(2, "on po dyskurs, jeden z najciekawszych i składek cenne dla historii wczesnego wykrywan"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Diana z Crossways"); record->setSearchableAttributeValue(2, "George Meredith, OM (1828-1909), angielski pisarz i poeta. Studiował prawo i został Artykularny jako radca prawny"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Obrona GUENEVERE"); record->setSearchableAttributeValue("article_sentence", "To jest powielanie książki wydanej przed 1923. Ta dyskursów książka może być sporadyczne niedoskonałości, takich jak brakujące lub niewyraźne strony "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Polish void testPolish() { addPolishRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "dyskursów"; vector<unsigned> recordIds; recordIds.push_back(1101); recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "takich"; vector<unsigned> recordIds; recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addPortugueseRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "As Aventuras de Roderick Aleatório"); record->setSearchableAttributeValue("article_sentence", "aqui não é tão divertido e melhorando universalmente, tal como a que é introduzida, como se fosse, ocasionalmente,"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "As Aventuras de Peregrine Pickle"); record->setSearchableAttributeValue(2, "Em um certo condado da Inglaterra, delimitada de um lado pelo mar"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Terças com Morrie"); record->setSearchableAttributeValue(2, "A história foi adaptada mais tarde por Thomas Rickman em um filme de TV de mesmo nome, dirigido"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Ir Tell It On The Mountain"); record->setSearchableAttributeValue("article_sentence", "O livro analisa o papel da Igreja cristã na vida dos Africano-Americanos"); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Portuguese void testPortuguese() { addPortugueseRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "Aventuras"; vector<unsigned> recordIds; recordIds.push_back(1101); recordIds.push_back(1102); ASSERT( pingExactPrefix(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyPrefix(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "cristã"; vector<unsigned> recordIds; recordIds.push_back(1201); ASSERT( pingExactPrefix(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyPrefix(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addRomanianRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "Cei trei muschetari"); record->setSearchableAttributeValue("article_sentence", "ecounts aventurile unui tânăr pe nume d'Artagnan după ce pleacă"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "Bogat Tata tata sarac"); record->setSearchableAttributeValue(2, "Acesta susține independența financiară prin investiții, imobiliare,"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Sea Wolf imobiliare"); record->setSearchableAttributeValue(2, "care intra sub dominația Wolf Larsen, puternic și amoral căpitan care de salvare"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Povestea vieții mele"); record->setSearchableAttributeValue("article_sentence", "ȚII de ea au fost adaptate de William Gibson pentru un 1957 căpitan"); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Romanian void testRomanian() { addRomanianRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "imobiliare"; vector<unsigned> recordIds; recordIds.push_back(1102); recordIds.push_back(1103); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "căpitan"; vector<unsigned> recordIds; recordIds.push_back(1103); recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addRussianRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "Побег из Шоушенка"); record->setSearchableAttributeValue("article_sentence", "это адаптация повести Стивена Кинга Рита Хейворт"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "На дороге"); record->setSearchableAttributeValue(2, "Это в значительной степени автобиографическая работа, которая была основана на спонтанной"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Как закалялась сталь Steel"); record->setSearchableAttributeValue(2, "Дверь балкона была открыта, а под занавес Tomorrow перемешивают на ветру, заполнив。"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "И восходит солнце sun“"); record->setSearchableAttributeValue("article_sentence", "Он восходит солнце стоит как,talk пожалуй, самым впечатляющим первый роман novel "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Russian void testRussian() { addRussianRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "Tomorrow "; vector<unsigned> recordIds; recordIds.push_back(1003); recordIds.push_back(1103); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "спонтанной "; vector<unsigned> recordIds; recordIds.push_back(1101); recordIds.push_back(1102); recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 3, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addSerbianRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "Фрозен Дееп"); record->setSearchableAttributeValue("article_sentence", "Време је ноћ. А посао тренутка плеше"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "Од мора до мора"); record->setSearchableAttributeValue(2, "Мотив и шема која ће доћи у ништа"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Фрамлеи Two Парсонаге first"); record->setSearchableAttributeValue(2, "Када је млади Марк Робартс напуштања Tomorrow колеџа, његов отац можда и изјављујем да су сви људи。"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Цветање Вилдернес"); record->setSearchableAttributeValue("article_sentence", " Први су су се упознали More на венчању Флеур Little и Мајкл Монт је и искра "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Serbian void testSerbian() { addSerbianRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "Tomorrow"; vector<unsigned> recordIds; recordIds.push_back(1003); recordIds.push_back(1103); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "Вилдернес"; vector<unsigned> recordIds; recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addSlovakRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "Záhradná slávnosť a iné príbehy"); record->setSearchableAttributeValue("article_sentence", "Lawrence a niečo ako súper Virginie Woolfovej. Mansfield tvorivé rokov"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "Záhradná prežitie"); record->setSearchableAttributeValue(2, "IT prekvapí a zároveň možno pobaví, aby ste vedeli,"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Zo Zeme na earth Mesiac moon"); record->setSearchableAttributeValue(2, "Počas vojny povstania, bol nový poor a vplyvný Yesterday klub založený v meste Baltimore v štáte Maryland"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Franchise Affair“"); record->setSearchableAttributeValue("article_sentence", "Robert Blair chystal ukradnúť z pomalej deň v jeho advokátskej kancelárii, keď zazvonil telefó "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Slovak void testSlovak() { addSlovakRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "Záhradná"; vector<unsigned> recordIds; recordIds.push_back(1101); recordIds.push_back(1102); //recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "Yesterday "; vector<unsigned> recordIds; recordIds.push_back(1001); recordIds.push_back(1103); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addSlovenianRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two življenja More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "Lisica ženska"); record->setSearchableAttributeValue("article_sentence", "Nekateri dušo tišine, starodavno in potrpežljiv kot korake, brooded nad njimi."); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "Flappersu in Filozofi"); record->setSearchableAttributeValue(2, "To verjetno zgodba se začne na morju, ki je bil modro sanje, kot barvita kot modro-svilene nogavice"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Mož, ki se je man bal"); record->setSearchableAttributeValue(2, "out od najtemnejših globin življenja, kjer je podpredsednik in kriminal in bedo bahajo"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Določenem obdobju“"); record->setSearchableAttributeValue("article_sentence", "Je del utopija, del distopija, del temno satira, s pridihom sodobnega steampunk "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Slovenian void testSlovenian() { addSlovenianRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "življenja "; vector<unsigned> recordIds; recordIds.push_back(1003); recordIds.push_back(1103); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "Določenem"; vector<unsigned> recordIds; recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addSpanishRecords() { ///Create Schema Spanish Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); // pure Spanish characters record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "Lucas"); record->setSearchableAttributeValue("article_sentence", "Teófilo, que, para muchas personas tomar una pluma para el libro que cuenta la historia entre nosotros lo han hecho"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "Mateo"); record->setSearchableAttributeValue(2, "Los descendientes de Abraham, hijo de David, la genealogía de Jesucristo"); record->setRecordBoost(90); index->addRecord(record, analyzer); //simple Spanish and english record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Malaquías "); record->setSearchableAttributeValue(2, "SEÑOR a Israel por medio Tomorrow de Malaquías miss implicaba 。"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Zechariah Zacarías“"); record->setSearchableAttributeValue("article_sentence", "El segundo año del rey Little Darío agosto Jehová á wing ddo Berequías, hijo del profeta Zacarías "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Spanish void testSpanish() { addSpanishRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "genealogía "; vector<unsigned> recordIds; recordIds.push_back(1102); ASSERT( pingExactPrefix(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyPrefix(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "Little "; vector<unsigned> recordIds; recordIds.push_back(1002); recordIds.push_back(1201); ASSERT( pingExactPrefix(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyPrefix(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addSwedishRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "Första och sista saker"); record->setSearchableAttributeValue("article_sentence", "Efter att jag hade studerat naturvetenskap och särskilt biologisk vetenskap för några år"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "finansiären"); record->setSearchableAttributeValue(2, "På grund av sin ålder, kan den innehålla brister såsom Markeringar, noteringar, marginaliaen"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Felix Holt Radical"); record->setSearchableAttributeValue(2, "Felix Holt, när han kom in, var inte i en observant humör, och när,"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "En dröm av såsom John Ball“"); record->setSearchableAttributeValue("article_sentence", "Engelska författaren William Morris om engelska böndernas revolt av 1381 och rebellen John Ball. "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Swedish void testSwedish() { addSwedishRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "såsom "; vector<unsigned> recordIds; recordIds.push_back(1102); recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "böndernas "; vector<unsigned> recordIds; recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addThaiRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "ลงและออกในกรุงปารีสและลอนดอน"); record->setSearchableAttributeValue("article_sentence", "นี้ละครที่ผิดปกติในอัตชีวประวัติส่วนดี narrates โดยไม่ต้องสงสารตัวเอง"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "ฟอสเตอร์โดโรธี"); record->setSearchableAttributeValue(2, "ดำเนินแรงโน้มถ่วงไม่มีที่ติดังนั้นภูมิปัญญาเอกพจน์โดดเด่นเพื่อ"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "มารยาทในประ manners เทศของชาวอเมริกัน"); record->setSearchableAttributeValue(2, "นี่คือการทำสำเนาห Tomorrow นังสือที่ตีพิมพ์ก่อนที่ 1923"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Thorne แพทย์"); record->setSearchableAttributeValue("article_sentence", "แฟรงค์ Gresham เป็นความตั้งใจที่จะแต่งงานกับสุดที่รักของเขาแมรี่ Thorne "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Thai void testThai() { addThaiRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "Tomorrow "; vector<unsigned> recordIds; recordIds.push_back(1003); recordIds.push_back(1103); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "บสุดที่ "; vector<unsigned> recordIds; recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addTurkishRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "Yaratıklar bir Çeşitlilik"); record->setSearchableAttributeValue("article_sentence", "sloganımız çalışır. Teorik olarak biz ne biz savunma"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "Söylemler"); record->setSearchableAttributeValue(2, "Ne kadar gramatik sanat tefekkür gücüne sahip mi?"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Batı Dikim Bir Söylemler"); record->setSearchableAttributeValue(2, "Yeni Dünya erken keşif home Tarihi için en lost meraklı ve değerli katkılarından biri,"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Crossways Diana“"); record->setSearchableAttributeValue("article_sentence", ". O hukuk okumak ve bir avukat olarak sözleşmeli edildi "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Turkish void testTurkish() { addTurkishRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "Söylemler"; vector<unsigned> recordIds; recordIds.push_back(1102); recordIds.push_back(1103); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "sözleşmeli "; vector<unsigned> recordIds; recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addUkrainianRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "Синя книга Фея"); record->setSearchableAttributeValue("article_sentence", "З людьми, що посієш, те й пожнеш,"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "сліпа любов"); record->setSearchableAttributeValue(2, "нарочним порушених упокій Денніс Howmore"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "холодний будинок"); record->setSearchableAttributeValue(2, "Місцевих найстаріших сімей, які year опинилися him в that незручне становище"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Чорна him мантія “"); record->setSearchableAttributeValue("article_sentence", "Цілком можливо, що жінки не мають позитивні оцінки того, що "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Ukrainian void testUkrainian() { addUkrainianRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "him"; vector<unsigned> recordIds; recordIds.push_back(1103); recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "любов"; vector<unsigned> recordIds; recordIds.push_back(1102); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addVietnameseRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "Quốc phòng của Guenevere"); record->setSearchableAttributeValue("article_sentence", "Đây là một bản sao của một cuốn sách xuất bản trước năm 1923"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "các Deerslayer"); record->setSearchableAttributeValue(2, "Crack chết người của một súng trường và tiếng kêu xuyên của Ấn Độ trên các warpat"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "Ghi nợ và Tín"); record->setSearchableAttributeValue(2, "Thẻ ghi nợ và tín dụng là hai khía cạnh cơ bản của tất cả các giao dịch tài chính"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "Deerslayer bình minh"); record->setSearchableAttributeValue("article_sentence", "Bản chất của chúng ta suy yếu không đầy đủ; Một cái gì đó trong tù này ngôi sao của chúng tôi "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Vietnamese void testVietnamese() { addVietnameseRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "Deerslayer"; vector<unsigned> recordIds; recordIds.push_back(1102); recordIds.push_back(1201); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } { string query = "trường "; vector<unsigned> recordIds; recordIds.push_back(1102); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addFarsiRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_tittle", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_tittle", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); // pure Tra_Chinese characters record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_tittle", "Barnaby چین Rudge"); record->setSearchableAttributeValue("article_sentence", "اظهار نظر او که کلاغ به تدریج منقرض شدن"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "واحد ضد چین"); record->setSearchableAttributeValue(2, "مواد منفجره، وکیل مدافع جوزف آنتونلی مورد از دست دادن هرگز - و یا پشت سر هم از وجدان"); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Farsi void testFarsi() { addFarsiRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "چین "; vector<unsigned> recordIds; recordIds.push_back(1101); recordIds.push_back(1103); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } //Test a record that includes both French and English { string query = "اظهار"; vector<unsigned> recordIds; recordIds.push_back(1101); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addArabicRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_title", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_title", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More"); record->setRecordBoost(10); index->addRecord(record, analyzer); // pure Arabic characters record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_title", "الرجل مانيرينغ"); record->setSearchableAttributeValue("article_sentence", "جعلت رواية أو الرومانسية من يفرلي طريقها إلى الجمهور ببطء، وبطبيعة الحال"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "حزب حديقة وقصص أخرى"); record->setSearchableAttributeValue(2, "مانسفيلد هو الكاتب الأكثر شهرة في نيوزيلندا."); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "والفراء الدولة"); record->setSearchableAttributeValue(2, "يجب أن القراء ليس دفعة واحدة تخيل الترفيه الكبرى، مثل الكرة المحكمة، أو بسهرة موسيقية"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1104); record->setSearchableAttributeValue(1, "ومجمدة"); record->setSearchableAttributeValue(2, "رئيس بلدية ومؤسسة من المدينة وإعطاء الكرة الكبرى"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1105); record->setSearchableAttributeValue(1, "من الأرض إلى القمر"); record->setSearchableAttributeValue(2, "خلال الحرب من تمرد، تم إنشاء ناد جديد ومؤثر في مدينة بالتيمور في ولاية ميريلاند"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1106); record->setSearchableAttributeValue(1, "من البحر إلى البحر"); record->setSearchableAttributeValue(2, "الحرية وضرورة استخدام لها. الحافز وخطة من شأنها أن تأتي إلى"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1107); record->setSearchableAttributeValue(1, "فرانكشتاين فرانكشتاين"); record->setSearchableAttributeValue(2, "العلماء فرانكشتاين استبدال دور الخالق في محاولة لخلق الحياة في أيديهم"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1108); record->setSearchableAttributeValue(1, "الحياة قضية الفرنشايز هو"); record->setSearchableAttributeValue(2, "وكان روبرت بلير على وشك ضرب قبالة من يوم بطيئة في مكتب محاماة له عندما رن جرس "); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1109); record->setSearchableAttributeValue(1, "المرأة الثعلب"); record->setSearchableAttributeValue(2, "الجرح الخطوات القديمة حتى من جانب الجبل من خلال أشجار الصنوبر طويل القامة، والصبر في عمق مداس عليها من قبل أقدام من عشرين قرنا"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1110); record->setSearchableAttributeValue(1, "الزعانف والفلاسفة"); record->setSearchableAttributeValue(2, "تبدأ هذه القصة من غير المرجح على البحر الذي كان حلما الأزرق، ملونة مثل جوارب زرقاء الحرير،"); record->setRecordBoost(90); index->addRecord(record, analyzer); //simple Arabic and english record->clear(); record->setPrimaryKey(1201); record->setSearchableAttributeValue("article_title", "bookالحياة بيت القسيس"); record->setSearchableAttributeValue("article_sentence", "عند الشباب Robarts مارك كان يغادر collegeالكلية،أيضاwas والدهleaving قد أعلن "); record->setRecordBoost(90); index->addRecord(record, analyzer); //Test a record that includes both Arabic and English record->clear(); record->setPrimaryKey(1202); record->setSearchableAttributeValue(1, "Miss الرجل الذي كان يخاف"); record->setSearchableAttributeValue(2, "من أحلك أعماق الحياة، viceحيث الرذيلة والجريمة centuryوالبؤس وتكثر، ويأتي بايرون من lifeالقرن "); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1203); record->setSearchableAttributeValue(1, ""); record->setSearchableAttributeValue(2, "Missمن أحلك أعماق الحياة يخاف، viceحيث الرذيلة والجريمة centuryوالبؤس وتكثر، ويأتي بايرون من lifeالقرن "); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Arabic void testArabic() { addArabicRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); //We use popular English novel and translate into Arabic,using the content and their titles to test if the engine can support Chinese characters. The data was obtained from www.baidu.com search "中国 诗词名句" //Query: "مثل", hits -> 1103, 1110 { string query = "مثل"; vector<unsigned> recordIds; recordIds.push_back(1102); recordIds.push_back(1103); recordIds.push_back(1105); recordIds.push_back(1109); recordIds.push_back(1110); recordIds.push_back(1202); recordIds.push_back(1203); ASSERT( pingExactPrefix(analyzer, queryEvaluator, query, 7, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyPrefix(analyzer, queryEvaluator, query, 7, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 7, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyComplete(analyzer, queryEvaluator, query, 7, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } //search English text //Query: "book", hits -> 1001, 1201 { vector<unsigned> recordIds; recordIds.push_back(1001); recordIds.push_back(1201); ASSERT( pingExactPrefix(analyzer, queryEvaluator, "book", 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyPrefix(analyzer, queryEvaluator, "book", 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingExactComplete(analyzer, queryEvaluator, "book", 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyComplete(analyzer, queryEvaluator, "book", 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } //Test a record that includes both Arabic and English //Query: "Missيخاف", hits -> 1003, 1201 { string query = "Missيخاف"; vector<unsigned> recordIds; recordIds.push_back(1202); recordIds.push_back(1203); ASSERT( pingExactPrefix(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyPrefix(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } //search long English and Arabic text //Query: "viceحيث الرذيلة والجريمة century", hits -> 1003, 1201 { string query = "viceحيث الرذيلة والجريمة century"; vector<unsigned> recordIds; recordIds.push_back(1202); recordIds.push_back(1203); ASSERT( pingExactPrefix(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyPrefix(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); ASSERT( pingFuzzyComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addHebrewRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_tittle", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_tittle", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); // pure Tra_Chinese characters record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_tittle", "הספר של סנובים"); record->setSearchableAttributeValue("article_sentence", "יום זה כ יצירות פילוסופיות חשובות, בשמו שלו שנים מאוחר יותר פילוסופיה בוגרת יותר"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "חרקים ארבה בסיס"); record->setSearchableAttributeValue(2, "ספר זה עוקב אחרי בחור צעיר בשם טוד האקט רואה את עצמו כצייר ואמן"); record->setRecordBoost(90); index->addRecord(record, analyzer); //simple Tra_Chinese and english record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "יחידת סין הוכחה"); record->setSearchableAttributeValue(2, " חומרי נפץ,test הסנגור ג'וזף אנטונלי מעולם לא Tomorrow מאבדים את מקרה - או פרץ של מצפון צורב בוא"); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Hebrew void testHebrew() { addHebrewRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "Tomorrow"; vector<unsigned> recordIds; recordIds.push_back(1003); recordIds.push_back(1103); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } //Test a record that includes both French and English { string query = "סנובים"; vector<unsigned> recordIds; recordIds.push_back(1101); recordIds.push_back(1103); ASSERT( pingExactComplete(analyzer, queryEvaluator, query, 2, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //from http://novel.tingroom.com/ translated by google void addKazakhRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_tittle", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_tittle", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); // pure Tra_Chinese characters record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_tittle", "тазалап тастапты "); record->setSearchableAttributeValue("article_sentence", "тастағанға ұқсайды"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "Жеп home отырмын"); record->setSearchableAttributeValue(2, "тастапты ұқсайды тастағанға"); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } // test Kazakh void testKazakh() { addKazakhRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "тастағанға "; vector<unsigned> recordIds; recordIds.push_back(1101); recordIds.push_back(1102); ASSERT(pingExactComplete(analyzer, queryEvaluator, query, 2,recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } // from http://my.wikipedia.org/wiki/Wikipedia:Font void addBurmeseRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_sentence", 2); // searchable text schema->setSearchableAttribute("article_translate", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_sentence", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_translate", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); // pure Tra_Chinese characters record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_sentence", "ပြည်ထောင်စု သမ္မတ မြန်မာနိုင်ငံတော်"); record->setSearchableAttributeValue("article_translate", "Republic of the Union of Myanmar"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "ဤစာမျက်နှာသည် ရည်ရွယ်ချက်ရှိလို့ အင်္ဂလိပ်စာနှင့်ရေးထားသည်။ ဘာသာမပြန်ပါနှင့်။"); record->setSearchableAttributeValue(2, "This article is written in English for a specific purpose. Please do not translate it."); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } //test Burmese void testBurmese() { addBurmeseRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "ဘာသာမပြန်ပါ"; vector<unsigned> recordIds; recordIds.push_back(1102); ASSERT(pingExactComplete(analyzer, queryEvaluator, query, 1,recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //Portuguese - Brazil The main differece from Portuguese is the voice and some write, the character is same. From http://en.wikipedia.org/wiki/Brazilian_Portuguese void addPortugueseBrazilRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_sentence", 2); // searchable text schema->setSearchableAttribute("article_translate", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_sentence", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_translate", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); // pure Tra_Chinese characters record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_sentence", "carteira de habilitação, carteira de motorista, carta"); record->setSearchableAttributeValue("article_translate", "driver's license (US), driving licence (UK)"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "trem, composição ferroviária"); record->setSearchableAttributeValue(2, "train"); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } //test Portuguese - Brazil void testPortugueseBrazil() { addPortugueseBrazilRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "habilitação"; vector<unsigned> recordIds; recordIds.push_back(1101); ASSERT(pingExactComplete(analyzer, queryEvaluator, query, 1,recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } //Spanish - Latin America The main differece from Spanish is the voice and some write, the character is same. From http://novel.tingroom.com/ translated by http://www.spanishdict.com/translate/Latin%20America void addSpanishLatinRecords() { ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_sentence", 2); // searchable text schema->setSearchableAttribute("article_translate", 7); // searchable text Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_sentence", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_translate", "Come Yesterday Once More"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRecordBoost(10); index->addRecord(record, analyzer); // pure Tra_Chinese characters record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_sentence", "La novela o el Romance de Waverley hizo su manera al público"); record->setSearchableAttributeValue("article_translate", "The Novel or Romance of Waverley made its way to the public slowly"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1102); record->setSearchableAttributeValue(1, "pero luego con tal popularidad acumulando que fomenten al autor a un segundo intento"); record->setSearchableAttributeValue(2, "but afterwards with such accumulating popularity as to encourage the Author to a second attempt"); record->setRecordBoost(90); index->addRecord(record, analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } //test Spanish-Latin void testSpanishLatin() { addSpanishLatinRecords(); // create an index searcher unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::load(indexMetaData1); QueryEvaluatorRuntimeParametersContainer runtimeParameters; QueryEvaluator * queryEvaluator = new QueryEvaluator(index, &runtimeParameters); Analyzer *analyzer = getAnalyzer(); { string query = "público"; vector<unsigned> recordIds; recordIds.push_back(1101); ASSERT(pingExactComplete(analyzer, queryEvaluator, query, 1, recordIds, vector<unsigned>(), ATTRIBUTES_OP_AND) == true); } delete analyzer; delete queryEvaluator; delete index; } void addFarsiRecordsWithNonSearchableAttribute(){ ///Create Schema Schema *schema = Schema::create(srch2::instantsearch::DefaultIndex); schema->setPrimaryKey("article_id"); // integer, not searchable schema->setSearchableAttribute("article_id"); // convert id to searchable text schema->setSearchableAttribute("article_tittle", 2); // searchable text schema->setSearchableAttribute("article_sentence", 7); // searchable text schema->setRefiningAttribute("price" , ATTRIBUTE_TYPE_INT , "0" ); schema->setRefiningAttribute("class" , ATTRIBUTE_TYPE_TEXT , "الف" ); Record *record = new Record(schema); Analyzer *analyzer = new Analyzer(NULL, NULL, NULL, NULL, ""); unsigned mergeEveryNSeconds = 3; unsigned mergeEveryMWrites = 5; unsigned updateHistogramEveryPMerges = 1; unsigned updateHistogramEveryQWrites = 5; IndexMetaData *indexMetaData1 = new IndexMetaData(new CacheManager(), mergeEveryNSeconds, mergeEveryMWrites, updateHistogramEveryPMerges, updateHistogramEveryQWrites, INDEX_DIR); Indexer *index = Indexer::create(indexMetaData1, analyzer, schema); //pure english record->setPrimaryKey(1001); record->setSearchableAttributeValue("article_tittle", "book Tom Smith and Jack Lennon"); record->setSearchableAttributeValue("article_sentence", "Come Yesterday Once More"); record->setRefiningAttributeValue("price" , "1001"); record->setRefiningAttributeValue("class" , "الف"); record->setRecordBoost(90); index->addRecord(record, analyzer); record->clear(); record->setPrimaryKey(1002); record->setSearchableAttributeValue(1, "Jimi Hendrix"); record->setSearchableAttributeValue(2, "Little wing"); record->setRefiningAttributeValue("price" , "1002"); record->setRefiningAttributeValue("class" , "ب"); record->setRecordBoost(90); index->addRecord(record,analyzer); record->clear(); record->setPrimaryKey(1003); record->setSearchableAttributeValue(1, "Mr Smith and Miss Smith"); record->setSearchableAttributeValue(2, "Come Tomorrow Two More first"); record->setRefiningAttributeValue("price" , "1003"); record->setRefiningAttributeValue("class" , "C"); record->setRecordBoost(10); index->addRecord(record,analyzer); // pure Tra_Chinese characters record->clear(); record->setPrimaryKey(1101); record->setSearchableAttributeValue("article_tittle", "Barnaby چین Rudge"); record->setSearchableAttributeValue("article_sentence", "اظهار نظر او که کلاغ به تدریج منقرض شدن"); record->setRefiningAttributeValue("price" , "1101"); record->setRefiningAttributeValue("class" , "ج"); record->setRecordBoost(90); index->addRecord(record,analyzer); record->clear(); record->setPrimaryKey(1103); record->setSearchableAttributeValue(1, "واحد ضد چین"); record->setSearchableAttributeValue(2, "مواد منفجره، وکیل مدافع جوزف آنتونلی مورد از دست دادن هرگز - و یا پشت سر هم از وجدان"); record->setRefiningAttributeValue("price" , "1103"); record->setRefiningAttributeValue("class" , "د"); record->setRecordBoost(90); index->addRecord(record,analyzer); index->commit(); index->save(); delete schema; delete record; delete analyzer; delete index; } int main(){ testPolish(); cout << "test Polish passed" << endl; testPortuguese(); cout << "test Portuguese passed" << endl; testRomanian(); cout << "test Romanian passed" << endl; testRussian(); cout << "test Russian passed" << endl; testSlovak(); cout << "test Slovak passed" << endl; testSlovenian(); cout << "test Slovenian passed" << endl; testSerbian(); cout << "test Serbian passed" << endl; testSwedish(); cout << "test Swedish passed" << endl; testThai(); cout << "test Thai passed" << endl; testTurkish(); cout << "test Turkish passed" << endl; testVietnamese(); cout << "test Vietnamese passed" << endl; testHebrew(); cout << "reading from right to left test Hebrew passed" << endl; testUkrainian(); cout << "test Ukrainian passed" << endl; testFarsi(); cout << "reading from right to left test Farsi passed" << endl; testKazakh(); cout << "test Kazakh passed" << endl; // test Burmese testBurmese(); cout << "test Chinese passed" << endl; // test PortugueseBrazil testPortugueseBrazil(); cout << "test Portuguese-Brazil passed" << endl; // test Spanish-Latin testSpanishLatin(); cout << "test Spanish-Latin passed" << endl; testSpanish(); cout << "test Spanish passed" << endl; // test Arabic testArabic(); cout << "reading from right to left test Arabic passed" << endl; return 0; }
33.524235
208
0.757973
[ "vector" ]
032562377c87fcd64a5807487ab16a39fc9dd527
3,521
hpp
C++
adaptors/generator/skeleton/job/###suite###_###type###_job_service.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
adaptors/generator/skeleton/job/###suite###_###type###_job_service.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
adaptors/generator/skeleton/job/###suite###_###type###_job_service.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
// Copyright (c) 2005-2007 Hartmut Kaiser // Copyright (c) 2005-2007 Andre Merzky (andre@merzky.net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef ADAPTORS_###SUITE###_###TYPE###_JOB__SERVICE_HPP #define ADAPTORS_###SUITE###_###TYPE###_JOB__SERVICE_HPP // stl includes #include <string> #include <iosfwd> // saga includes #include <saga/saga.hpp> #include <saga/saga/adaptors/task.hpp> // saga engine includes #include <saga/impl/engine/proxy.hpp> // saga adaptor includes #include <saga/saga/adaptors/task.hpp> #include <saga/saga/adaptors/adaptor.hpp> #include <saga/saga/adaptors/adaptor_data.hpp> // saga package includes #include <saga/impl/packages/job/job_service_cpi.hpp> // adaptor includes #include "###suite###_###type###_adaptor.hpp" //////////////////////////////////////////////////////////////////////// namespace ###suite###_###type### { class job_service_cpi_impl : public saga::adaptors::v1_0::job_service_cpi <job_service_cpi_impl> { private: typedef saga::adaptors::v1_0::job_service_cpi <job_service_cpi_impl> base_cpi; // adaptor data typedef saga::adaptors::adaptor_data <adaptor> adaptor_data_type; public: // constructor of the job_service cpi job_service_cpi_impl (proxy * p, cpi_info const & info, saga::ini::ini const & glob_ini, saga::ini::ini const & adap_ini, TR1::shared_ptr <saga::adaptor> adaptor); // destructor of the job_service cpi ~job_service_cpi_impl (void); // // CPI functions // void sync_create_job (saga::job::job & ret, // saga::job::description jd); // void sync_run_job (saga::job::job & ret, // std::string cmd, // std::string host, // saga::job::ostream & in, // saga::job::istream & out, // saga::job::istream & err); // void sync_list (std::vector <std::string> & ret); // void sync_get_job (saga::job::job & ret, // std::string jobid); // void sync_get_self (saga::job::self & ret); // // // This adaptor implements the async functions // // based on its own synchronous functions. // saga::task async_create_job (saga::job::description jd); // saga::task async_run_job (std::string cmd, // std::string host, // saga::job::ostream & in, // saga::job::istream & out, // saga::job::istream & err); // saga::task async_list (void); // saga::task async_get_job (std::string jobid); // saga::task async_get_self (void); }; // class job_service_cpi_impl } // namespace ###suite###_###type### //////////////////////////////////////////////////////////////////////// #endif // ADAPTORS_###SUITE###_###TYPE###_JOB_SERVICE_HPP
38.692308
75
0.494746
[ "vector" ]
0327907b84f1fffef9acb143c67c38b96eeeba9b
4,200
cpp
C++
Ejercicio02-Agregando Biblioteca/biblioteca.cpp
BranlyBC/ClassL2
2dc31c1fc0acd2e6d494b6b725dc561c141e9587
[ "MIT" ]
null
null
null
Ejercicio02-Agregando Biblioteca/biblioteca.cpp
BranlyBC/ClassL2
2dc31c1fc0acd2e6d494b6b725dc561c141e9587
[ "MIT" ]
null
null
null
Ejercicio02-Agregando Biblioteca/biblioteca.cpp
BranlyBC/ClassL2
2dc31c1fc0acd2e6d494b6b725dc561c141e9587
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <time.h> using namespace std; string libros[15][3]; //Biblioteca Cargado y nombramiento del libro void cargarLibros() { libros[0][0] = "Algoritmos"; libros[0][1] = "Algoritmos y Programacion (Guia para docentes)"; libros[0][2] = "Juan Carlos Lopez Garcia"; libros[1][0] = "Algoritmos"; libros[1][1] = "Apuntes de Algoritmos y Estructuras de Datos"; libros[1][2] = "ALfred V. Aho, Jeffrey D. Ullman"; libros[2][0] = "Algoritmos"; libros[2][1] = "Breves Notas sobre Analisis de Algoritmos"; libros[2][2] = "Jorge L. Ortega Arjona"; libros[3][0] = "Algoritmos"; libros[3][1] = "Fundamentos de Informatica y Programacion"; libros[3][2] = "Gregorio Martin Quetglas"; libros[4][0] = "Algoritmos"; libros[4][1] = "Temas selectos de estructuras de datos"; libros[4][2] = "Jorge L. Ortega Arjona"; libros[5][0] = "Algoritmos"; libros[5][1] = "Teoria sintactico-gramatical de objetos"; libros[5][2] = "Eugenio Bahit"; libros[6][0] = "Base de Datos"; libros[6][1] = "Apuntes de Base de Datos 1"; libros[6][2] = "Eva Gomez Ballester"; libros[7][0] = "Base de Datos"; libros[7][1] = "Base de Datos (2005)"; libros[7][2] = "Antonio Hernandez"; libros[8][0] = "Base de Datos"; libros[8][1] = "Base de Datos (2011)"; libros[8][2] = "Mercedez Marques"; libros[9][0] = "Base de Datos"; libros[9][1] = "Base de Datos Avanzadas (2013)"; libros[9][2] = "Juan Carlos Amaya"; libros[10][0] = "Base de Datos"; libros[10][1] = "Diseno Conceptual de Bases de Datos"; libros[10][2] = "Elena Castro"; libros[11][0] = "Ciencia Computacional"; libros[11][1] = "Breves Notas sobre Automatas y Lenguajes"; libros[11][2] = "Maria Elizabeth Villeda"; libros[12][0] = "Ciencia Computacional"; libros[12][1] = "Breves Notas sobre Teoria de la Computacion"; libros[12][2] = "Mateo Quintanilla"; libros[13][0] = "Metodologias de desarrollo de software"; libros[13][1] = "Compendio de Ingenieria del Software"; libros[13][2] = "Elmer Zacarias"; libros[14][0] = "Metodologias de desarrollo de software"; libros[14][1] = "Diseno agil con TDD"; libros[14][2] = "Stephan Aguilar"; } int main(int argc, char const *argv[]) { cargarLibros(); srand (time(NULL)); bool salir = false; while (salir == false) { string buscar = ""; system("cls"); cout << "Ingrese la descripcion del libro que busca: "; cin >> buscar; for (int i = 0; i < 15; i++) { string libro = libros[i][1]; string autor = libros[i][2]; string libroEnminuscula = libro; transform(libroEnminuscula.begin(), libroEnminuscula.end(), libroEnminuscula.begin(), ::tolower); transform(buscar.begin(), buscar.end(), buscar.begin(), ::tolower); if (libroEnminuscula.find(buscar) != string::npos) { cout << "Libro encontrado: " << libro << endl << "Autor: " << autor << endl; cout << endl; cout << "Tambien te sugerimos estos libros: " << endl; int sugerencia1 = rand() % 14 + 1; int sugerencia2 = rand() % 14 + 1; int sugerencia3 = rand() % 14 + 1; cout << " Sugerencia 1: " << libros[sugerencia1][1] << endl; cout << " Sugerencia 2: " << libros[sugerencia2][1] << endl; cout << " Sugerencia 3: " << libros[sugerencia3][1] << endl; salir = true; break; } } if (salir == false) { char continuar = 'n'; while(true) { system("cls"); cout << "No se encontro el libro que busca. Desea continuar? s/n "; cin >> continuar; if (continuar == 's' || continuar == 'S') { break; } else if (continuar == 'n' || continuar == 'N') { salir = true; break; } } } } return 0; }
30.434783
109
0.539286
[ "transform" ]
032d3aeb6238c0d8bfd0abe324971b465f49b8fe
22,837
cpp
C++
source/functions/adiosFunctions.cpp
pnorbert/ADIOS2
6bd06b550431cf3e354a1a0b3f0d825e39fe97a9
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
source/functions/adiosFunctions.cpp
pnorbert/ADIOS2
6bd06b550431cf3e354a1a0b3f0d825e39fe97a9
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
source/functions/adiosFunctions.cpp
pnorbert/ADIOS2
6bd06b550431cf3e354a1a0b3f0d825e39fe97a9
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * adiosFunctions.cpp * * Created on: Oct 10, 2016 * Author: wfg */ /// \cond EXCLUDED_FROM_DOXYGEN #include <algorithm> //std::count #include <cmath> // std::ceil, std::pow, std::log #include <cstring> //std::memcpy #include <fstream> #include <ios> //std::ios_base::failure #include <sstream> #include <stdexcept> #include <thread> //std::thread #include <sys/stat.h> //stat #include <sys/types.h> //CreateDirectory #include <unistd.h> //CreateDirectory /// \endcond #include "core/Support.h" #include "functions/adiosFunctions.h" #ifdef ADIOS_HAVE_BZIP2 #include "transform/BZip2.h" #endif namespace adios { void DumpFileToString(const std::string fileName, std::string &fileContent) { std::ifstream fileStream(fileName); if (fileStream.good() == false) { // check file throw std::ios_base::failure( "ERROR: file " + fileName + " could not be opened. Check permissions or file existence\n"); } std::ostringstream fileSS; fileSS << fileStream.rdbuf(); fileStream.close(); fileContent = fileSS.str(); // convert to string and check if (fileContent.empty()) { throw std::invalid_argument("ERROR: file " + fileName + " is empty\n"); } } void GetSubString(const std::string initialTag, const std::string finalTag, const std::string content, std::string &subString, std::string::size_type &currentPosition) { auto lf_Wipe = [](std::string &subString, std::string::size_type &currentPosition) { subString.clear(); currentPosition = std::string::npos; }; auto lf_SetPositions = [](const char quote, const std::string::size_type quotePosition, const std::string &content, std::string::size_type &currentPosition, std::string::size_type &closingQuotePosition) { currentPosition = quotePosition; closingQuotePosition = content.find(quote, currentPosition + 1); }; // BODY OF FUNCTION STARTS HERE std::string::size_type start(content.find(initialTag, currentPosition)); if (start == content.npos) { lf_Wipe(subString, currentPosition); return; } currentPosition = start; std::string::size_type end(content.find(finalTag, currentPosition)); if (end == content.npos) { lf_Wipe(subString, currentPosition); return; } // here make sure the finalTag is not a value surrounded by " " or ' ', if // so // find next bool isValue = true; while (isValue == true) { std::string::size_type singleQuotePosition = content.find('\'', currentPosition); std::string::size_type doubleQuotePosition = content.find('\"', currentPosition); if ((singleQuotePosition == content.npos && doubleQuotePosition == content.npos) || (singleQuotePosition == content.npos && end < doubleQuotePosition) || (doubleQuotePosition == content.npos && end < singleQuotePosition) || (end < singleQuotePosition && end < doubleQuotePosition)) { break; } // find the closing corresponding quote std::string::size_type closingQuotePosition; if (singleQuotePosition == content.npos) { // no ' anywhere lf_SetPositions('\"', doubleQuotePosition, content, currentPosition, closingQuotePosition); } else if (doubleQuotePosition == content.npos) { // no " anywhere lf_SetPositions('\'', singleQuotePosition, content, currentPosition, closingQuotePosition); } else { if (singleQuotePosition < doubleQuotePosition) { lf_SetPositions('\'', singleQuotePosition, content, currentPosition, closingQuotePosition); } else { // find the closing " lf_SetPositions('\"', doubleQuotePosition, content, currentPosition, closingQuotePosition); } } if (closingQuotePosition == content.npos) // if can't find closing it's open until the end { lf_Wipe(subString, currentPosition); return; } currentPosition = closingQuotePosition + 1; if (closingQuotePosition < end) { continue; } // if this point is reached it means it's a value inside " " or ' ', // move to // the next end end = content.find(finalTag, currentPosition); } subString = content.substr(start, end - start + finalTag.size()); currentPosition = end; } void GetQuotedValue(const char quote, const std::string::size_type &quotePosition, std::string &currentTag, std::string &value) { currentTag = currentTag.substr(quotePosition + 1); auto nextQuotePosition = currentTag.find(quote); if (nextQuotePosition == currentTag.npos) { throw std::invalid_argument("ERROR: Invalid attribute in..." + currentTag + "...check XML file\n"); } value = currentTag.substr(0, nextQuotePosition); currentTag = currentTag.substr(nextQuotePosition + 1); } void GetPairs(const std::string tag, std::vector<std::pair<const std::string, const std::string>> &pairs) noexcept { std::string currentTag( tag.substr(tag.find_first_of(" \t\n"))); // initialize current tag while (currentTag.find('=') != currentTag.npos) // equalPosition { currentTag = currentTag.substr(currentTag.find_first_not_of(" \t\n")); auto equalPosition = currentTag.find('='); const std::string field( currentTag.substr(0, equalPosition)); // get field std::string value; const char quote = currentTag[equalPosition + 1]; if (quote == '\'' || quote == '"') // single quotes { GetQuotedValue(quote, equalPosition + 1, currentTag, value); } pairs.push_back( std::pair<const std::string, const std::string>(field, value)); } } void GetPairsFromTag( const std::string &fileContent, const std::string tag, std::vector<std::pair<const std::string, const std::string>> &pairs) { if (tag.back() == '/') // last char is / --> "XML empty tag" { GetPairs(tag, pairs); } else if (tag[0] == '/') // first char is / ---> closing tag { } else // opening tag { const std::string tagName(tag.substr(0, tag.find_first_of(" \t\n\r"))); const std::string closingTagName("</" + tagName + ">"); // check for closing tagName if (fileContent.find(closingTagName) == fileContent.npos) { throw std::invalid_argument("ERROR: closing tag " + closingTagName + " missing, check XML file\n"); } GetPairs(tag, pairs); } } // void SetMembers( const std::string& fileContent, const MPI_Comm mpiComm, // const bool debugMode, // std::string& hostLanguage, std::vector< // std::shared_ptr<Transform> >& transforms, // std::map< std::string, Group >& groups ) //{ // //adios-config // std::string currentContent; // std::string::size_type currentPosition( 0 ); // GetSubString( "<adios-config ", "</adios-config>", fileContent, // currentContent, currentPosition ); // // //remove comment sections // std::string::size_type startComment ( currentContent.find( "<!--" ) ); // // while( startComment != currentContent.npos ) // { // std::string::size_type endComment( currentContent.find( "-->") ); // currentContent.erase( startComment, endComment-startComment+3 ); // startComment = currentContent.find( "<!--" ); // } // // //Tag <adios-config // currentPosition = 0; // // std::string tag; //use for < > tags // GetSubString( "<adios-config", ">", currentContent, tag, currentPosition // ); // tag = tag.substr( 1, tag.size() - 2 ); //eliminate < > // // std::vector< std::pair<const std::string, const std::string> > pairs; // // pairs in tag // GetPairsFromTag( currentContent, tag, pairs ); // // for( auto& pair : pairs ) // if( pair.first == "host-language" ) // hostLanguage = pair.second; // // if( debugMode == true ) // { // if( Support::HostLanguages.count( hostLanguage ) == 0 ) // throw std::invalid_argument("ERROR: host language " + hostLanguage // + " not supported.\n" ); // // if( hostLanguage.empty() == true ) // throw std::invalid_argument("ERROR: host language is empty.\n" ); // } // // //adios-group // currentPosition = 0; // // while( currentPosition != std::string::npos ) // { // std::string xmlGroup; // GetSubString("<adios-group ", "</adios-group>", currentContent, // xmlGroup, currentPosition ); //Get all group contents // // if( xmlGroup.empty() ) //no more groups to find // break; // // //get group name // std::string::size_type groupPosition( 0 ); // GetSubString( "<adios-group ", ">", xmlGroup, tag, groupPosition ); // if( debugMode == true ) // { // if( tag.size() < 2 ) // throw std::invalid_argument( "ERROR: wrong tag " + tag + " in // adios-group\n" ); //check < or <= // } // // tag = tag.substr( 1, tag.size() - 2 ); //eliminate < > // GetPairsFromTag( xmlGroup, tag, pairs ); // std::string groupName; // // for( auto& pair : pairs ) // { // if( pair.first == "name") // groupName = pair.second; // } // // if( debugMode == true ) // { // if( groupName.empty() ) // throw std::invalid_argument( "ERROR: group name not found. \n" // ); // // if( groups.count( groupName ) == 1 ) //group exists // throw std::invalid_argument( "ERROR: group " + groupName + " // defined twice.\n" ); // } // // groups.emplace( groupName, Group( groupName, xmlGroup, transforms, // debugMode ) ); // // currentContent.erase( currentContent.find( xmlGroup ), xmlGroup.size() // ); // currentPosition = 0; // } // // //transport // //lambda function to check priority and iteration casting to unsigned int // auto lf_UIntCheck = []( const std::string method, const std::string // fieldStr, const std::string fieldName, // const bool debugMode, int& field ) // { // field = 0; // if( fieldStr.empty() == false ) // { // field = std::stoi( fieldStr ); //throws invalid_argument // // if( debugMode == true ) // { // if( field < 0 ) // throw std::invalid_argument("ERROR: " + fieldName + " in // transport " + method + " can't be negative\n" ); // } // } // }; // // //this section will have to change, doing nothing for now // currentPosition = 0; // while( currentPosition != std::string::npos ) // { // GetSubString( "<transport ", ">", currentContent, tag, currentPosition // ); // if( tag.empty() ) break; // tag = tag.substr( 1, tag.size() - 2 ); //eliminate < > // pairs.clear(); // GetPairsFromTag( currentContent, tag, pairs ); // // std::string groupName, method, priorityStr, iterationStr; // for( auto& pair : pairs ) // { // if( pair.first == "group" ) groupName = pair.second; // else if( pair.first == "method" ) method = pair.second; // else if( pair.first == "priority" ) priorityStr = pair.second; // else if( pair.first == "iteration" ) iterationStr = pair.second; // } // // auto itGroup = groups.find( groupName ); // if( debugMode == true ) // { // if( itGroup == groups.end() ) //not found // throw std::invalid_argument( "ERROR: in transport " + method + // " group " + groupName + " not found.\n" ); // } // // int priority, iteration; // lf_UIntCheck( method, priorityStr, "priority", debugMode, priority ); // lf_UIntCheck( method, iterationStr, "iteration", debugMode, iteration // ); // //here do something with the capsule // } //} // void InitXML( const std::string xmlConfigFile, const MPI_Comm mpiComm, const // bool debugMode, // std::string& hostLanguage, std::vector< // std::shared_ptr<Transform> >& transforms, // std::map< std::string, Group >& groups ) //{ // int xmlFileContentSize; // std::string xmlFileContent; // // int rank; // MPI_Comm_rank( mpiComm, &rank ); // // if( rank == 0 ) //serial part // { // DumpFileToString( xmlConfigFile, xmlFileContent ); //in // ADIOSFunctions.h dumps all XML Config File to xmlFileContent // xmlFileContentSize = xmlFileContent.size( ) + 1; // add one for the // null character // // MPI_Bcast( &xmlFileContentSize, 1, MPI_INT, 0, mpiComm ); //broadcast // size for allocation // MPI_Bcast( (char*)xmlFileContent.c_str(), xmlFileContentSize, // MPI_CHAR, 0, mpiComm ); //broadcast contents // } // else // { // MPI_Bcast( &xmlFileContentSize, 1, MPI_INT, 0, mpiComm ); //receive // size // // char* xmlFileContentMPI = new char[ xmlFileContentSize ]; //allocate // xml C-char // MPI_Bcast( xmlFileContentMPI, xmlFileContentSize, MPI_CHAR, 0, mpiComm // ); //receive xml C-char // xmlFileContent.assign( xmlFileContentMPI ); //copy to a string // // delete []( xmlFileContentMPI ); //delete char* needed for MPI, might // add size is moving to C++14 for optimization, avoid memory leak // } // // SetMembers( xmlFileContent, mpiComm, debugMode, hostLanguage, transforms, // groups ); //} std::size_t GetTotalSize(const std::vector<std::size_t> &dimensions) { std::size_t product = 1; for (const auto dimension : dimensions) { product *= dimension; } return product; } void CreateDirectory(const std::string fullPath) noexcept { auto lf_Mkdir = [](const std::string directory, struct stat &st) { if (stat(directory.c_str(), &st) == -1) { mkdir(directory.c_str(), 0777); } }; auto directoryPosition = fullPath.find("/"); if (fullPath[0] == '/' || fullPath[0] == '.') { // find the second '/' directoryPosition = fullPath.find("/", directoryPosition + 1); } struct stat st = {0}; if (directoryPosition == fullPath.npos) // no subdirectories { lf_Mkdir(fullPath.c_str(), st); return; } std::string directory(fullPath.substr(0, directoryPosition)); lf_Mkdir(directory.c_str(), st); while (directoryPosition != fullPath.npos) { directoryPosition = fullPath.find("/", directoryPosition + 1); directory = fullPath.substr(0, directoryPosition); lf_Mkdir(directory.c_str(), st); } } void SetTransformsHelper(const std::vector<std::string> &transformNames, std::vector<std::shared_ptr<Transform>> &transforms, const bool debugMode, std::vector<short> &transformIndices, std::vector<short> &parameters) { // function to get a parameter from "method:parameter" auto lf_GetParameter = [](const std::string transformName, std::string &transformMethod, const bool debugMode) -> short { short parameter = -1; auto colonPosition = transformName.find(":"); if (colonPosition != transformName.npos) { if (debugMode == true) { if (colonPosition == transformName.size() - 1) { throw std::invalid_argument( "ERROR: wrong format for transform " + transformName + ", in call to SetTransform\n"); } } transformMethod = transformName.substr(0, colonPosition); parameter = std::stoi( transformName.substr(colonPosition + 1)); // need to test } return parameter; }; // Get transform index from transforms, if not found return -1 auto lf_GetTransformIndex = [](const std::string transformMethod, const std::vector<std::shared_ptr<Transform>> &transforms) -> short { short transformIndex = -1; for (unsigned int i = 0; i < transforms.size(); ++i) { if (transforms[i]->m_Method == transformMethod) { transformIndex = i; break; } } return transformIndex; }; // BODY of FUNCTION STARTS HERE for (const std::string transformName : transformNames) { std::string transformMethod(transformName); short parameter = lf_GetParameter(transformName, transformMethod, debugMode); // from transform = "method:parameter" short transformIndex = lf_GetTransformIndex(transformMethod, transforms); if (transformIndex == -1) // not found, then create a new transform { if (transformMethod == "bzip2") { #ifdef ADIOS_HAVE_BZIP2 transforms.push_back( std::make_shared<adios::transform::BZip2>()); #endif } transformIndex = static_cast<short>(transforms.size() - 1); } transformIndices.push_back(transformIndex); parameters.push_back(parameter); } } std::map<std::string, std::string> BuildParametersMap(const std::vector<std::string> &parameters, const bool debugMode) { auto lf_GetFieldValue = [](const std::string parameter, std::string &field, std::string &value, const bool debugMode) { auto equalPosition = parameter.find("="); if (debugMode == true) { if (equalPosition == parameter.npos) { throw std::invalid_argument( "ERROR: wrong format for parameter " + parameter + ", format must be field=value \n"); } if (equalPosition == parameter.size() - 1) { throw std::invalid_argument("ERROR: empty value in parameter " + parameter + ", format must be field=value \n"); } } field = parameter.substr(0, equalPosition); value = parameter.substr(equalPosition + 1); // need to test }; // BODY OF FUNCTION STARTS HERE std::map<std::string, std::string> parametersOutput; for (const auto parameter : parameters) { std::string field, value; lf_GetFieldValue(parameter, field, value, debugMode); if (debugMode == true) { if (parametersOutput.count(field) == 1) { throw std::invalid_argument( "ERROR: parameter " + field + " already exists, must be unique\n"); } } parametersOutput[field] = value; } return parametersOutput; } std::vector<int> CSVToVectorInt(const std::string csv) { std::vector<int> numbers; if (csv.empty()) { return numbers; } if (csv.find(",") == csv.npos) // check if no commas, one int { numbers.push_back(std::stoi(csv)); // might need to be checked } else { int count = std::count(csv.begin(), csv.end(), ','); numbers.reserve(count); std::istringstream csvSS(csv); std::string value; while (std::getline(csvSS, value, ',')) // need to test { numbers.push_back(std::stoi(csv)); } } return numbers; } void ConvertUint64VectorToSizetVector(const std::vector<std::uint64_t> &in, std::vector<std::size_t> &out) { out.clear(); out.reserve(in.size()); for (const auto inElement : in) { out.push_back(static_cast<std::size_t>(inElement)); } } bool CheckBufferAllocation(const std::size_t newSize, const float growthFactor, const std::size_t maxBufferSize, std::vector<char> &buffer) { // Check if data in buffer needs to be reallocated const std::size_t requiredDataSize = buffer.size() + newSize + 100; // adding some bytes for tolerance // might need to write payload in batches bool doTransportsFlush = (requiredDataSize > maxBufferSize) ? true : false; if (GrowBuffer(requiredDataSize, growthFactor, buffer) == -1) { doTransportsFlush = true; } return doTransportsFlush; } int GrowBuffer(const std::size_t incomingDataSize, const float growthFactor, std::vector<char> &buffer) { const std::size_t currentCapacity = buffer.capacity(); const std::size_t availableSpace = currentCapacity - buffer.size(); const double gf = static_cast<double>(growthFactor); if (incomingDataSize > availableSpace) { const std::size_t neededCapacity = incomingDataSize + buffer.size(); const double numerator = std::log(static_cast<double>(neededCapacity) / static_cast<double>(currentCapacity)); const double denominator = std::log(gf); double n = std::ceil(numerator / denominator); const std::size_t newSize = static_cast<std::size_t>( std::ceil(std::pow(gf, n) * currentCapacity)); try { buffer.reserve(newSize); } catch (std::bad_alloc &e) { return -1; } return 1; } return 0; } bool IsLittleEndian() noexcept { uint16_t hexa = 0x1234; return *reinterpret_cast<uint8_t *>(&hexa) != 0x12; // NOLINT } } // namespace adios
32.43892
80
0.560625
[ "vector", "transform" ]
0332ef907f2f0d6bff1e50fc65739e1cbf24e9bb
8,715
cpp
C++
src/prod/src/Reliability/Failover/ra/Test.Unit.Infrastructure.EntityScheduler.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Reliability/Failover/ra/Test.Unit.Infrastructure.EntityScheduler.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Reliability/Failover/ra/Test.Unit.Infrastructure.EntityScheduler.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Federation; using namespace Reliability; using namespace Reliability::ReconfigurationAgentComponent; using namespace Infrastructure; using namespace Reliability::ReconfigurationAgentComponent::ReliabilityUnitTest; using namespace Common; using namespace std; using namespace Reliability::ReconfigurationAgentComponent::Infrastructure::ReliabilityUnitTest; using Diagnostics::ScheduleEntityPerformanceData; namespace { const wstring Id1(L"id1"); const wstring Id2(L"id2"); const wstring Id3(L"id3"); const wstring Id4(L"id4"); const int TraceThreshold(40); } class TestFailoverUnitScheduler { protected: typedef EntityScheduler<TestEntity> EntitySchedulerType; TestFailoverUnitScheduler() { BOOST_REQUIRE(TestSetup()); } TEST_METHOD_SETUP(TestSetup); ~TestFailoverUnitScheduler() { BOOST_REQUIRE(TestCleanup()); } TEST_METHOD_CLEANUP(TestCleanup); ThreadpoolStub & GetThreadpool() { return testContext_->ThreadpoolStubObj; } TestJobItemSPtr CreateJobItem() { TestJobItem::Parameters parameters( entry_, L"aid", [](TestEntityHandlerParameters &, TestJobItemContext&) {return true; }, JobItemCheck::Default, *JobItemDescription::MessageProcessing); return make_shared<TestJobItem>(move(parameters)); } EntitySchedulerType & GetScheduler() { return entry_->Scheduler; } AsyncOperationSPtr Schedule(TestJobItemSPtr const & ji) { return GetScheduler().BeginScheduleWorkItem( ji, testContext_->RA.Threadpool, testContext_->Clock, testContext_->RA.PerfCounters, [](AsyncOperationSPtr const &) {}, testContext_->RA.Root.CreateAsyncOperationRoot()); } void ScheduleAndEnd(TestJobItemSPtr const & ji) { auto op = Schedule(ji); Verify::IsTrue(op->CompletedSynchronously, L"Should have been completed if calling schedule and end"); End(op); } void CreateScheduleFinishAndEnd() { auto initialJI = CreateJobItem(); auto initialOp = Schedule(initialJI); FinishQueuedThreadpoolWork(); End(initialOp); } EntityJobItemList End(AsyncOperationSPtr const & op) { EntityJobItemList result; ScheduleEntityPerformanceData perfData; auto error = GetScheduler().EndScheduleWorkItem(op, result, perfData); Verify::IsTrue(error.IsSuccess(), L"Schedule can never fail"); return result; } void EndAndVerifyPerfCounters( AsyncOperationSPtr const & op, int64 expectedScheduleTime, int64 expectedQueueTime) { EntityJobItemList result; ScheduleEntityPerformanceData perfData; auto error = GetScheduler().EndScheduleWorkItem(op, result, perfData); Verify::IsTrue(error.IsSuccess(), L"Schedule can never fail"); Verify::AreEqual(expectedScheduleTime, perfData.ScheduleDuration.TotalSeconds(), L"Schedule time"); Verify::AreEqual(expectedQueueTime, perfData.QueueDuration.TotalSeconds(), L"queue time"); } void EndAndVerifyQueued(AsyncOperationSPtr const & op) { auto result = End(op); Verify::IsTrue(result.empty(), L"Must be empty"); } void EndAndVerify(AsyncOperationSPtr const & op, TestJobItemSPtr const & ji) { vector<EntityJobItemBaseSPtr> v; v.push_back(ji); EndAndVerify(op, v); } void EndAndVerify(AsyncOperationSPtr const & op, TestJobItemSPtr const & ji1, TestJobItemSPtr const & ji2) { vector<EntityJobItemBaseSPtr> v; v.push_back(ji1); v.push_back(ji2); EndAndVerify(op, v); } void EndAndVerify(AsyncOperationSPtr const & op, EntityJobItemList const & expected) { EntityJobItemList result = End(op); Verify::IsTrue(!result.empty(), L"Result should not be empty if result is expected"); Verify::VectorStrict(expected, result);; } void FinishQueuedThreadpoolWork() { Verify::IsTrue(!GetThreadpool().FTQueue.IsEmpty, L"Threadpool cant be empty"); GetThreadpool().FTQueue.Drain(testContext_->RA); } void ReleaseLock() { GetScheduler().ReleaseLock(testContext_->Clock, testContext_->RA.PerfCounters); } void AdvanceTime(int seconds) { testContext_->Clock.AdvanceTimeBySeconds(seconds); } InfrastructureTestUtilityUPtr utility_; UnitTestContextUPtr testContext_; TestEntityEntrySPtr entry_; }; bool TestFailoverUnitScheduler::TestSetup() { testContext_ = InfrastructureTestUtility::CreateUnitTestContextWithTestEntityMap(); testContext_->Clock.SetManualMode(); utility_ = make_unique<InfrastructureTestUtility>(*testContext_); entry_ = dynamic_pointer_cast<TestEntityEntry>(utility_->SetupCreated()); return true; } bool TestFailoverUnitScheduler::TestCleanup() { testContext_->Cleanup(); return true; } BOOST_AUTO_TEST_SUITE(Unit) BOOST_FIXTURE_TEST_SUITE(TestFailoverUnitSchedulerSuite,TestFailoverUnitScheduler) BOOST_AUTO_TEST_CASE(PerformanceDataIsCorrectForScheduledEntity) { auto ji = CreateJobItem(); auto op = Schedule(ji); AdvanceTime(1); FinishQueuedThreadpoolWork(); EndAndVerifyPerfCounters(op, 1, 0); } BOOST_AUTO_TEST_CASE(WorkIsCompletedWithResultWhenScheduleCompletes) { auto ji = CreateJobItem(); auto op = Schedule(ji); Verify::IsTrue(!op->IsCompleted, L"Cannot be completed"); FinishQueuedThreadpoolWork(); EndAndVerify(op, ji); } BOOST_AUTO_TEST_CASE(BatchedWorkWhenScheduledReturnsIsPending) { auto ji1 = CreateJobItem(); auto ji2 = CreateJobItem(); auto op1 = Schedule(ji1); auto op2 = Schedule(ji2); Verify::IsTrue(op2->CompletedSynchronously, L"Op must be completed"); EndAndVerifyQueued(op2); FinishQueuedThreadpoolWork(); End(op1); } BOOST_AUTO_TEST_CASE(MultipleWorkIsBatchedIfWorkArrivesDuringScheduling) { auto ji1 = CreateJobItem(); auto ji2 = CreateJobItem(); auto op = Schedule(ji1); ScheduleAndEnd(ji2); FinishQueuedThreadpoolWork(); EndAndVerify(op, ji1, ji2); } BOOST_AUTO_TEST_CASE(EnqueueAfterReleaseLock) { CreateScheduleFinishAndEnd(); ReleaseLock(); auto ji2 = CreateJobItem(); auto op2 = Schedule(ji2); FinishQueuedThreadpoolWork(); EndAndVerify(op2, ji2); } BOOST_AUTO_TEST_CASE(NewWorkIsPendingUtilPreviousLockIsReleased) { CreateScheduleFinishAndEnd(); auto jiEnqueuedDuringLock = CreateJobItem(); auto opDuringLock = Schedule(jiEnqueuedDuringLock); Verify::IsTrue(!opDuringLock->IsCompleted, L"Cannot be completed"); Verify::IsTrue(GetThreadpool().FTQueue.IsEmpty, L"Cannot schedule while lock is held"); ReleaseLock(); // Work should now be scheduled and async op should complete FinishQueuedThreadpoolWork(); EndAndVerify(opDuringLock, jiEnqueuedDuringLock); } BOOST_AUTO_TEST_CASE(MultipleNewWorkIsQueuedUntilPreviousLockIsReleased) { CreateScheduleFinishAndEnd(); auto firstJobScheduledDuringLock = CreateJobItem(); auto firstJobOp = Schedule(firstJobScheduledDuringLock); Verify::IsTrue(!firstJobOp->IsCompleted, L"Cannot be completed"); Verify::IsTrue(GetThreadpool().FTQueue.IsEmpty, L"Cannot schedule while lock is held"); auto secondJobScheduledDuringLock = CreateJobItem(); auto secondJobOp = Schedule(secondJobScheduledDuringLock); EndAndVerifyQueued(secondJobOp); ReleaseLock(); // Work should now be scheduled and async op should complete FinishQueuedThreadpoolWork(); EndAndVerify(firstJobOp, firstJobScheduledDuringLock, secondJobScheduledDuringLock); } BOOST_AUTO_TEST_CASE(QueueTimeIsMeasured) { CreateScheduleFinishAndEnd(); auto ji = CreateJobItem(); auto op = Schedule(ji); AdvanceTime(2); ReleaseLock(); FinishQueuedThreadpoolWork(); EndAndVerifyPerfCounters(op, 0, 2); } BOOST_AUTO_TEST_CASE(ScheduleTimeForQueuedItemIsMeasured) { CreateScheduleFinishAndEnd(); auto ji = CreateJobItem(); auto op = Schedule(ji); ReleaseLock(); AdvanceTime(5); FinishQueuedThreadpoolWork(); EndAndVerifyPerfCounters(op, 5, 0); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
27.065217
110
0.698451
[ "vector" ]
0338dddaf5c23615654a3690d28dcd585586da16
7,167
hxx
C++
include/vigra/graph_rag_project_back.hxx
BSeppke/vigra
490213d8954a03bdb985b52cfaafd6389431efd8
[ "MIT" ]
316
2015-01-01T02:06:53.000Z
2022-03-28T08:37:28.000Z
include/vigra/graph_rag_project_back.hxx
BSeppke/vigra
490213d8954a03bdb985b52cfaafd6389431efd8
[ "MIT" ]
232
2015-01-06T23:51:07.000Z
2022-03-18T13:14:02.000Z
include/vigra/graph_rag_project_back.hxx
BSeppke/vigra
490213d8954a03bdb985b52cfaafd6389431efd8
[ "MIT" ]
150
2015-01-05T02:11:18.000Z
2022-03-16T09:44:14.000Z
/************************************************************************/ /* */ /* Copyright 2014 by Thorsten Beier and Ullrich Koethe */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://hci.iwr.uni-heidelberg.de/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* ullrich.koethe@iwr.uni-heidelberg.de or */ /* vigra@informatik.uni-hamburg.de */ /* */ /* 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. */ /* */ /************************************************************************/ /** * This header provides definitions of graph-related algorithms */ #ifndef VIGRA_GRAPH_RAG_PROJECT_BACK_HXX #define VIGRA_GRAPH_RAG_PROJECT_BACK_HXX /*std*/ #include <algorithm> #include <vector> #include <functional> #include <set> /*vigra*/ #include "graphs.hxx" #include "graph_generalization.hxx" #include "multi_gridgraph.hxx" #include "priority_queue.hxx" #include "union_find.hxx" #include "adjacency_list_graph.hxx" #include "graph_maps.hxx" namespace vigra{ /// \cond namespace detail_rag_project_back{ template< class BASE_GRAPH, class BASE_GRAPH_LABELS, class RAG_FEATURES, class BASE_GRAPH_FEATURES > struct RagProjectBack{ static void projectBack( const AdjacencyListGraph & rag, const BASE_GRAPH & bg, const Int64 ignoreLabel, const BASE_GRAPH_LABELS bgLabels, const RAG_FEATURES & ragFeatures, BASE_GRAPH_FEATURES & bgFeatures ){ typedef BASE_GRAPH Bg; typedef typename Bg::NodeIt BgNodeIt; typedef typename Bg::Node BgNode; if(ignoreLabel==-1){ for(BgNodeIt iter(bg); iter!=lemon::INVALID; ++iter){ const BgNode bgNode(*iter); bgFeatures[bgNode] = ragFeatures[rag.nodeFromId(bgLabels[bgNode])]; } } else{ for(BgNodeIt iter(bg); iter!=lemon::INVALID; ++iter){ const BgNode bgNode(*iter); if(static_cast<Int64>(bgLabels[bgNode])!=ignoreLabel) bgFeatures[bgNode] = ragFeatures[rag.nodeFromId(bgLabels[bgNode])]; } } } }; template< class BASE_GRAPH_LABELS, class RAG_FEATURES, class BASE_GRAPH_FEATURES > struct RagProjectBack< vigra::GridGraph<3, undirected_tag>, BASE_GRAPH_LABELS, RAG_FEATURES, BASE_GRAPH_FEATURES >{ typedef vigra::GridGraph<3, undirected_tag> BASE_GRAPH; static void projectBack( const AdjacencyListGraph & rag, const BASE_GRAPH & bg, const Int64 ignoreLabel, const BASE_GRAPH_LABELS bgLabels, const RAG_FEATURES & ragFeatures, BASE_GRAPH_FEATURES & bgFeatures ){ typedef BASE_GRAPH Bg; typedef typename Bg::Node BgNode; vigra::TinyVector<Int64, 3> shape = bg.shape(); if(ignoreLabel==-1){ // FIXME: replace with threadpool #pragma omp parallel for for(Int64 z=0; z<shape[2]; ++z){ BgNode node; node[2]=z; for(node[1]=0; node[1]<shape[1]; ++node[1]) for(node[0]=0; node[0]<shape[0]; ++node[0]){ bgFeatures[node] = ragFeatures[rag.nodeFromId(bgLabels[node])]; } } } else{ // FIXME: replace with threadpool #pragma omp parallel for for(Int64 z=0; z<shape[2]; ++z){ BgNode node; node[2]=z; for(node[1]=0; node[1]<shape[1]; ++node[1]) for(node[0]=0; node[0]<shape[0]; ++node[0]){ if(static_cast<Int64>(bgLabels[node])!=ignoreLabel) bgFeatures[node] = ragFeatures[rag.nodeFromId(bgLabels[node])]; } } } } }; } /// \endcond /// project node features of a region adjacency /// graph back to the base graph. /// /// This function can be used to show a segmentation /// or node features of RAG on pixel / voxel level template< class BASE_GRAPH, class BASE_GRAPH_LABELS, class RAG_FEATURES, class BASE_GRAPH_FEATURES > inline void projectBack( const AdjacencyListGraph & rag, const BASE_GRAPH & bg, const Int64 ignoreLabel, const BASE_GRAPH_LABELS bgLabels, const RAG_FEATURES & ragFeatures, BASE_GRAPH_FEATURES & bgFeatures ){ using namespace detail_rag_project_back; detail_rag_project_back::RagProjectBack< BASE_GRAPH,BASE_GRAPH_LABELS,RAG_FEATURES,BASE_GRAPH_FEATURES>::projectBack(rag, bg,ignoreLabel,bgLabels,ragFeatures,bgFeatures); } } #endif /* VIGRA_GRAPH_RAG_PROJECT_BACK_HXX */
36.943299
129
0.506349
[ "shape", "vector" ]
0339a605dbd179b96c5c6349f822fefbaef88387
8,432
cpp
C++
chromium/third_party/WebKit/Source/bindings/core/v8/ReadableStreamOperationsTest.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/bindings/core/v8/ReadableStreamOperationsTest.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/bindings/core/v8/ReadableStreamOperationsTest.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "bindings/core/v8/ReadableStreamOperations.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptFunction.h" #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8BindingForTesting.h" #include "bindings/core/v8/V8BindingMacros.h" #include "bindings/core/v8/V8IteratorResultValue.h" #include "bindings/core/v8/V8ThrowException.h" #include "platform/heap/Handle.h" #include "testing/gtest/include/gtest/gtest.h" #include <v8.h> namespace blink { namespace { class NotReached : public ScriptFunction { public: static v8::Local<v8::Function> createFunction(ScriptState* scriptState) { NotReached* self = new NotReached(scriptState); return self->bindToV8Function(); } private: explicit NotReached(ScriptState* scriptState) : ScriptFunction(scriptState) { } ScriptValue call(ScriptValue) override; }; ScriptValue NotReached::call(ScriptValue) { EXPECT_TRUE(false) << "'Unreachable' code was reached"; return ScriptValue(); } class Iteration final : public GarbageCollectedFinalized<Iteration> { public: Iteration() : m_isSet(false) , m_isDone(false) , m_isValid(true) {} void set(ScriptValue v) { ASSERT(!v.isEmpty()); m_isSet = true; v8::TryCatch block(v.scriptState()->isolate()); v8::Local<v8::Value> value; v8::Local<v8::Value> item = v.v8Value(); if (!item->IsObject() || !v8Call(v8UnpackIteratorResult(v.scriptState(), item.As<v8::Object>(), &m_isDone), value)) { m_isValid = false; return; } m_value = toCoreString(value->ToString()); } bool isSet() const { return m_isSet; } bool isDone() const { return m_isDone; } bool isValid() const { return m_isValid; } const String& value() const { return m_value; } DEFINE_INLINE_TRACE() {} private: bool m_isSet; bool m_isDone; bool m_isValid; String m_value; }; class Function : public ScriptFunction { public: static v8::Local<v8::Function> createFunction(ScriptState* scriptState, Iteration* iteration) { Function* self = new Function(scriptState, iteration); return self->bindToV8Function(); } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_iteration); ScriptFunction::trace(visitor); } private: Function(ScriptState* scriptState, Iteration* iteration) : ScriptFunction(scriptState) , m_iteration(iteration) { } ScriptValue call(ScriptValue value) override { m_iteration->set(value); return value; } Member<Iteration> m_iteration; }; class ReadableStreamOperationsTest : public ::testing::Test { public: ReadableStreamOperationsTest() : m_scope(v8::Isolate::GetCurrent()), m_block(isolate()) {} ~ReadableStreamOperationsTest() override { // Execute all pending microtasks isolate()->RunMicrotasks(); EXPECT_FALSE(m_block.HasCaught()); } ScriptState* scriptState() const { return m_scope.scriptState(); } v8::Isolate* isolate() const { return scriptState()->isolate(); } v8::MaybeLocal<v8::Value> eval(const char* s) { v8::Local<v8::String> source; v8::Local<v8::Script> script; if (!v8Call(v8::String::NewFromUtf8(isolate(), s, v8::NewStringType::kNormal), source)) { ADD_FAILURE(); return v8::MaybeLocal<v8::Value>(); } if (!v8Call(v8::Script::Compile(scriptState()->context(), source), script)) { ADD_FAILURE() << "Compilation fails"; return v8::MaybeLocal<v8::Value>(); } return script->Run(scriptState()->context()); } v8::MaybeLocal<v8::Value> evalWithPrintingError(const char* s) { v8::TryCatch block(isolate()); v8::MaybeLocal<v8::Value> r = eval(s); if (block.HasCaught()) { ADD_FAILURE() << toCoreString(block.Exception()->ToString(isolate())).utf8().data(); block.ReThrow(); } return r; } V8TestingScope m_scope; v8::TryCatch m_block; }; TEST_F(ReadableStreamOperationsTest, IsReadableStream) { EXPECT_FALSE(ReadableStreamOperations::isReadableStream(scriptState(), v8::Undefined(isolate()))); EXPECT_FALSE(ReadableStreamOperations::isReadableStream(scriptState(), v8::Null(isolate()))); EXPECT_FALSE(ReadableStreamOperations::isReadableStream(scriptState(), v8::Object::New(isolate()))); v8::Local<v8::Value> stream; ASSERT_TRUE(v8Call(evalWithPrintingError("new ReadableStream()"), stream)); EXPECT_TRUE(ReadableStreamOperations::isReadableStream(scriptState(), stream)); } TEST_F(ReadableStreamOperationsTest, IsReadableStreamReaderInvalid) { EXPECT_FALSE(ReadableStreamOperations::isReadableStreamReader(scriptState(), v8::Undefined(isolate()))); EXPECT_FALSE(ReadableStreamOperations::isReadableStreamReader(scriptState(), v8::Null(isolate()))); EXPECT_FALSE(ReadableStreamOperations::isReadableStreamReader(scriptState(), v8::Object::New(isolate()))); v8::Local<v8::Value> stream; ASSERT_TRUE(v8Call(evalWithPrintingError("new ReadableStream()"), stream)); EXPECT_FALSE(ReadableStreamOperations::isReadableStreamReader(scriptState(), stream)); } TEST_F(ReadableStreamOperationsTest, GetReader) { v8::Local<v8::Value> stream; ASSERT_TRUE(v8Call(evalWithPrintingError("new ReadableStream()"), stream)); EXPECT_FALSE(ReadableStreamOperations::isLocked(scriptState(), stream)); ScriptValue reader; { TrackExceptionState es; reader = ReadableStreamOperations::getReader(scriptState(), stream, es); ASSERT_FALSE(es.hadException()); } EXPECT_TRUE(ReadableStreamOperations::isLocked(scriptState(), stream)); ASSERT_FALSE(reader.isEmpty()); EXPECT_FALSE(ReadableStreamOperations::isReadableStream(scriptState(), reader.v8Value())); EXPECT_TRUE(ReadableStreamOperations::isReadableStreamReader(scriptState(), reader.v8Value())); // Already locked! { TrackExceptionState es; reader = ReadableStreamOperations::getReader(scriptState(), stream, es); ASSERT_TRUE(es.hadException()); } ASSERT_TRUE(reader.isEmpty()); } TEST_F(ReadableStreamOperationsTest, IsDisturbed) { v8::Local<v8::Value> stream; ASSERT_TRUE(v8Call(evalWithPrintingError("stream = new ReadableStream()"), stream)); EXPECT_FALSE(ReadableStreamOperations::isDisturbed(scriptState(), stream)); ASSERT_FALSE(evalWithPrintingError("stream.cancel()").IsEmpty()); EXPECT_TRUE(ReadableStreamOperations::isDisturbed(scriptState(), stream)); } TEST_F(ReadableStreamOperationsTest, Read) { v8::Local<v8::Value> reader; ASSERT_TRUE(v8Call(evalWithPrintingError( "var controller;" "function start(c) { controller = c; }" "new ReadableStream({start}).getReader()"), reader)); ASSERT_TRUE(ReadableStreamOperations::isReadableStreamReader(scriptState(), reader)); Iteration* it1 = new Iteration(); Iteration* it2 = new Iteration(); ReadableStreamOperations::read(scriptState(), reader).then( Function::createFunction(scriptState(), it1), NotReached::createFunction(scriptState())); ReadableStreamOperations::read(scriptState(), reader).then( Function::createFunction(scriptState(), it2), NotReached::createFunction(scriptState())); isolate()->RunMicrotasks(); EXPECT_FALSE(it1->isSet()); EXPECT_FALSE(it2->isSet()); ASSERT_FALSE(evalWithPrintingError("controller.enqueue('hello')").IsEmpty()); isolate()->RunMicrotasks(); EXPECT_TRUE(it1->isSet()); EXPECT_TRUE(it1->isValid()); EXPECT_FALSE(it1->isDone()); EXPECT_EQ("hello", it1->value()); EXPECT_FALSE(it2->isSet()); ASSERT_FALSE(evalWithPrintingError("controller.close()").IsEmpty()); isolate()->RunMicrotasks(); EXPECT_TRUE(it1->isSet()); EXPECT_TRUE(it1->isValid()); EXPECT_FALSE(it1->isDone()); EXPECT_EQ("hello", it1->value()); EXPECT_TRUE(it2->isSet()); EXPECT_TRUE(it2->isValid()); EXPECT_TRUE(it2->isDone()); } } // namespace } // namespace blink
32.682171
125
0.682045
[ "object" ]
033c6e80eb25a371f76d811be32dfc971f70ac8e
2,593
cpp
C++
More Advanced Topics/More Advanced Search Techniques/Meet in the Middle A* DA*/Editing a Book.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
3
2017-08-12T06:09:39.000Z
2018-09-16T02:31:27.000Z
More Advanced Topics/More Advanced Search Techniques/Meet in the Middle A* DA*/Editing a Book.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
More Advanced Topics/More Advanced Search Techniques/Meet in the Middle A* DA*/Editing a Book.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector <int> vi; int n; unordered_map <string, int> special, target, source; int used[12]; inline void init(int n){ string start; for(int i=0; i<n; i++) start += (char)('1' + i); queue <string> q; q.push(start); target[start] = 0; string current, t1, t2, t3; int distance; while(!q.empty()){ current = q.front(); q.pop(); distance = target[current]; if(distance == 2) break; for(int i=0; i<n; i++){ for(int j=i; j<n; j++){ t1 = current.substr(i, j-i+1); t2 = current; t2.erase(i, j-i+1); for(int k=0; k<t2.size(); k++){ t3 = t2; t3.insert(k, t1); if(target.find(t3) == target.end()){ //cout << t3 << " " << distance + 1 << "\n"; target[t3] = distance + 1; q.push(t3); } } } } } } int solve(const string &b){ if(!used[n]){ used[n] = 1; init(n); } if(target.find(b) != target.end()) return target[b]; queue <string> q; q.push(b); source[b] = 0; string current, t1, t2, t3; int distance; while(!q.empty()){ current = q.front(); q.pop(); distance = source[current]; if(distance == 2) break; for(int i=0; i<n; i++){ for(int j=i; j<n; j++){ t1 = current.substr(i, j-i+1); t2 = current; t2.erase(i, j-i+1); for(int k=0; k<t2.size(); k++){ t3 = t2; t3.insert(k, t1); if(source.find(t3) == source.end()){ source[t3] = distance + 1; if(target.find(t3) != target.end()){ return (target[t3] + source[t3]); } q.push(t3); } } } } } return 5; } int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); memset(used, 0, sizeof used); int cas = 1; while(cin >> n, n){ source.clear(); char last; string b; for(int i=0; i<n; i++){ cin >> last; b += last; } int ans = solve(b); cout << "Case " << cas++ << ": " << ans << "\n"; } return 0; }
28.494505
68
0.404551
[ "vector" ]
033d8f9bb4f1eb5fdffb1e7e83aa616dbb08b603
4,446
hpp
C++
modules/aruco/test/test_aruco_utils.hpp
pccvlab/opencv_contrib
f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93
[ "Apache-2.0" ]
null
null
null
modules/aruco/test/test_aruco_utils.hpp
pccvlab/opencv_contrib
f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93
[ "Apache-2.0" ]
null
null
null
modules/aruco/test/test_aruco_utils.hpp
pccvlab/opencv_contrib
f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93
[ "Apache-2.0" ]
null
null
null
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #include "test_precomp.hpp" namespace opencv_test { namespace { static inline vector<Point2f> getAxis(InputArray _cameraMatrix, InputArray _distCoeffs, InputArray _rvec, InputArray _tvec, float length, const float offset = 0.f) { vector<Point3f> axis; axis.push_back(Point3f(offset, offset, 0.f)); axis.push_back(Point3f(length+offset, offset, 0.f)); axis.push_back(Point3f(offset, length+offset, 0.f)); axis.push_back(Point3f(offset, offset, length)); vector<Point2f> axis_to_img; projectPoints(axis, _rvec, _tvec, _cameraMatrix, _distCoeffs, axis_to_img); return axis_to_img; } static inline vector<Point2f> getMarkerById(int id, const vector<vector<Point2f> >& corners, const vector<int>& ids) { for (size_t i = 0ull; i < ids.size(); i++) if (ids[i] == id) return corners[i]; return vector<Point2f>(); } static inline double deg2rad(double deg) { return deg * CV_PI / 180.; } /** * @brief Get rvec and tvec from yaw, pitch and distance */ static inline void getSyntheticRT(double yaw, double pitch, double distance, Mat& rvec, Mat& tvec) { rvec = Mat::zeros(3, 1, CV_64FC1); tvec = Mat::zeros(3, 1, CV_64FC1); // rotate "scene" in pitch axis (x-axis) Mat rotPitch(3, 1, CV_64FC1); rotPitch.at<double>(0) = -pitch; rotPitch.at<double>(1) = 0; rotPitch.at<double>(2) = 0; // rotate "scene" in yaw (y-axis) Mat rotYaw(3, 1, CV_64FC1); rotYaw.at<double>(0) = 0; rotYaw.at<double>(1) = yaw; rotYaw.at<double>(2) = 0; // compose both rotations composeRT(rotPitch, Mat(3, 1, CV_64FC1, Scalar::all(0)), rotYaw, Mat(3, 1, CV_64FC1, Scalar::all(0)), rvec, tvec); // Tvec, just move in z (camera) direction the specific distance tvec.at<double>(0) = 0.; tvec.at<double>(1) = 0.; tvec.at<double>(2) = distance; } /** * @brief Project a synthetic marker */ static inline void projectMarker(Mat& img, Ptr<aruco::Board> board, int markerIndex, Mat cameraMatrix, Mat rvec, Mat tvec, int markerBorder) { // canonical image Mat markerImg; const int markerSizePixels = 100; aruco::drawMarker(board->dictionary, board->ids[markerIndex], markerSizePixels, markerImg, markerBorder); // projected corners Mat distCoeffs(5, 1, CV_64FC1, Scalar::all(0)); vector< Point2f > corners; // get max coordinate of board Point3f maxCoord = board->rightBottomBorder; // copy objPoints vector<Point3f> objPoints = board->objPoints[markerIndex]; // move the marker to the origin for (size_t i = 0; i < objPoints.size(); i++) objPoints[i] -= (maxCoord / 2.f); projectPoints(objPoints, rvec, tvec, cameraMatrix, distCoeffs, corners); // get perspective transform vector< Point2f > originalCorners; originalCorners.push_back(Point2f(0, 0)); originalCorners.push_back(Point2f((float)markerSizePixels, 0)); originalCorners.push_back(Point2f((float)markerSizePixels, (float)markerSizePixels)); originalCorners.push_back(Point2f(0, (float)markerSizePixels)); Mat transformation = getPerspectiveTransform(originalCorners, corners); // apply transformation Mat aux; const char borderValue = 127; warpPerspective(markerImg, aux, transformation, img.size(), INTER_NEAREST, BORDER_CONSTANT, Scalar::all(borderValue)); // copy only not-border pixels for (int y = 0; y < aux.rows; y++) { for (int x = 0; x < aux.cols; x++) { if (aux.at< unsigned char >(y, x) == borderValue) continue; img.at< unsigned char >(y, x) = aux.at< unsigned char >(y, x); } } } /** * @brief Get a synthetic image of GridBoard in perspective */ static inline Mat projectBoard(Ptr<aruco::GridBoard>& board, Mat cameraMatrix, double yaw, double pitch, double distance, Size imageSize, int markerBorder) { Mat rvec, tvec; getSyntheticRT(yaw, pitch, distance, rvec, tvec); Mat img = Mat(imageSize, CV_8UC1, Scalar::all(255)); for (unsigned int index = 0; index < board->ids.size(); index++) { projectMarker(img, board.staticCast<aruco::Board>(), index, cameraMatrix, rvec, tvec, markerBorder); } return img; } } }
34.734375
122
0.664417
[ "vector", "transform" ]
0345098de59be5681e6a79449d8cb3116274e40e
75,621
cpp
C++
src/method.cpp
giag3/peng-utils
f0883ffbf3b422de2e0ea326861114b1f5809037
[ "MIT" ]
1
2022-03-28T11:20:50.000Z
2022-03-28T11:20:50.000Z
src/method.cpp
giag3/peng-utils
f0883ffbf3b422de2e0ea326861114b1f5809037
[ "MIT" ]
null
null
null
src/method.cpp
giag3/peng-utils
f0883ffbf3b422de2e0ea326861114b1f5809037
[ "MIT" ]
null
null
null
#include "compiler/method.hpp" #include "vars.hpp" #include "error_handler/error_handler.hpp" #include "compiler/assembly_shortcuts.hpp" #include "parser/parser.hpp" #include "error_handler/console.hpp" // Get token with removing comments extern std::string get_token(source_file* file); extern std::string check_token(source_file* file); extern bool is_token(source_file* file, std::string token); // Get parsing functions extern nclass* get_nclass_or_create(source_file* file, std::string& keyword); using namespace assembler; extern NAMESPACE* get_namespace(std::vector<NAMESPACE*>& namespaces, std::string& name); extern NAMESPACE* compiling_namespace; extern std::vector<NAMESPACE*> namespaces; extern std::vector<ENUM*> enums; DATA_TYPE* get_data_type(std::string& keyword); extern ulong size(TYPE& type, bool capped = false); // Alignment method extern long align8(long val); // Skip till extern void skip_till(source_file* file, std::string token); // Skips a bracket body extern void skip_bracket_body(source_file* file); // Reads an array into a type extern void read_array(std::string& iden, source_file* file, TYPE& t); // Get expression TYPE get_expression(std::string& name, std::string& iden, source_file* file, DATA_TYPE dtype, nclass* obj_nclass = nullptr, ENUM* en = nullptr) { // ********************************** // PARSE TYPE // ********************************** // Info about the type (meta data) TYPE type = {dtype, META_DATA_TYPE::STORAGE}; // Set obj nclass type.obj_nclass = obj_nclass; type.en = en; // Parse secondary meta_data_type if (file->check_token() == "*") type.mdata_type = META_DATA_TYPE::POINTER; // Pointer found while (file->is_token("*")) // Increase it's size type.mdata_size++; // ********************************** // PARSE IDENTIFICATION // ********************************** // The name name = file->get_token(); // If comma or ending found => nameless argument if (name == "," || name == ")") { // Set nameless and identification iden = name, name = ""; return type; } // Read nameless array else if (name == "[") { // Reads an array read_array(name, file, type); // Set nameless iden = name, name = ""; return type; } // Identification iden = file->get_token(); // Reads an array read_array(iden, file, type); return type; } // Get namespace from previous namespaces NAMESPACE* get_from_prev_namespaces(NAMESPACE* ns, std::string& token) { // If nullptr => none found so return nullptr if (ns == nullptr) return nullptr; if (ns->in_namespace == nullptr) return nullptr; // If current namespace is equal to token if (ns->in_namespace->name == token) return ns->in_namespace; // Else check all previous namespaces for (NAMESPACE* n : ns->in_namespace->namespaces) { // Do not check yourself again if (n == ns) continue; // Check all previous namespaces get_from_prev_namespaces(n, token); } // If not found => return nullptr return nullptr; } // Checks all default namespaces NAMESPACE* check_default_namespaces(std::string& token) { for (NAMESPACE* ns : namespaces) if (ns->name == token) return ns; return nullptr; } // List of default nclasses extern nclass_list nclasses; // Search util function NAMESPACE* search(std::string& token) { NAMESPACE* ns; // Get the namespace if (compiling_namespace == nullptr) { // Get namespace from no namespace ns = get_namespace(namespaces, token); } else { // Check if searched namespace is current one if (compiling_namespace->name != token) { // Get namespace from namespaces within current namespace ns = get_namespace(compiling_namespace->namespaces, token); // If namespace is not found => check all namespaces before this namespace if (ns == nullptr) ns = get_from_prev_namespaces(compiling_namespace, token); // If namespace is still not found => check all default namespaces if (ns == nullptr) ns = check_default_namespaces(token); } // Set current to compiling namespace else { ns = compiling_namespace; } } return ns; } // Searches for a namespace void search_namespace(std::string& token) { // The namespace pointer NAMESPACE* ns = search(token); // Check if the namespace exists if (ns != nullptr) { // And if it does, change compiling namespace to it compiling_namespace = ns; } else { // Throw error error_handler::compilation_error("namespace with the name '" + C_GREEN + token + C_CLR + "' not found"); // Create a new error namespace compiling_namespace = new NAMESPACE(); compiling_namespace->name = token; } } // Searches for a method static void search_namespace_for_method(source_file* file, std::string& token, method_list** methods) { // The namespace pointer NAMESPACE* ns = search(token); // Check if the namespace exists if (ns != nullptr) { // And if it does, change compiling namespace to it compiling_namespace = ns; } else { // Get nclass list nclass_list* nl; if (compiling_namespace == nullptr) nl = &nclasses; else nl = &compiling_namespace->nclasses; // Check nclasses for (nclass*& nc : *nl) { if (nc->get_name() == token) { // Change methods *methods = &nc->get_methods(); return; } } // Throw error error_handler::compilation_error("namespace with the name '" + C_GREEN + token + C_CLR + "' not found"); // Create a new error namespace compiling_namespace = new NAMESPACE(); compiling_namespace->name = token; } } // Checks for a namespace / method for precompiling stage void check_for_namespace(std::string& token, source_file* file, method_list** methods = nullptr) { // Reset compiling namespace if ::(namespace) found if (token == ":") { // Reset compiling namespace compiling_namespace = nullptr; // Missing colon if (!file->is_token(":")) error_handler::compilation_error("missing colon for a default namespace"); // Get next token token = file->get_token(); } // Check for a namespace while (file->is_token(":")) { // Check for single colon if (!file->is_token(":")) { error_handler::compilation_error("namespace checking error; mismatched colon(s) found"); // Get next token -> error token = file->get_token(); return; } // The namespace pointer if (methods == nullptr) search_namespace(token); else search_namespace_for_method(file, token, methods); // Get the next token token = file->get_token(); } } // Gets global enum extern ENUM* get_enum(std::string& name); // Compiling nclass, method extern method* compiling_method; extern nclass* compiling_nclass; extern NAMESPACE* compiling_namespace; // Searches for an enum static void search_namespace_for_enum(source_file* file, std::string& token, ENUM*& en, bool error) { // The namespace pointer NAMESPACE* ns = search(token); // Check if the namespace exists if (ns != nullptr) { // And if it does, change compiling namespace to it compiling_namespace = ns; } else { // The enum ENUM* e; // If enum found if ((e = get_enum(token)) != nullptr) { // Set enum and return en = e; return; } // Throw error if (error) { error_handler::compilation_error("namespace with the name '" + C_GREEN + token + C_CLR + "' not found"); // Create a new error namespace compiling_namespace = new NAMESPACE(); compiling_namespace->name = token; } } } // Checks for a namespace / enum void check_for_namespace(std::string& token, source_file* file, ENUM*& en, bool error = true) { // Reset compiling namespace if ::(namespace) found if (token == ":") { // Reset compiling namespace compiling_namespace = nullptr; // Missing colon if (!file->is_token(":")) error_handler::compilation_error("missing colon for a default namespace"); // Get next token token = file->get_token(); } // Check for a namespace while (file->check_token() == ":" && file->check_second_token() == ":") { // Remove two tokens file->get_token(), file->get_token(); // The namespace pointer search_namespace_for_enum(file, token, en, error); // Get the next token token = file->get_token(); } } // Default constructor for the method method::method(std::string name, TYPE type, PRE_TYPE pre_types) : name(name), type(type), pre_types(pre_types) {}; // Default constructor for the method method::method(std::string name, TYPE type, PRE_TYPE pre_types, source_file* file) : name(name), type(type), pre_types(pre_types), file(file) { // Precompile arguments std::string token; // While ending bracket is encountered, parse main: while ((token = file->get_token()) != ")") { // Check for empty if (token == "") break; // Check for a data type DATA_TYPE* data; if (data = get_data_type(token)) { // Variable name, end value std::string var_name, end_val; // The type of the argument TYPE type = get_expression(var_name, end_val, file, *data); // Check for duplicates if (var_name != "") for (variable& arg : arguments) if (arg.get_name() == var_name) error_handler::assembling_error("argument with the name '" + C_GREEN + var_name + C_CLR + "' already exists"); // Adds the type to the argument list variable arg; // Set var name, type, line, offset arg.get_name() = var_name; arg.get_type() = type; arg.get_line() = file->get_current_line(); arg.get_offset() = file->get_current_offset(); arguments.push_back( arg ); // If end value found -> exit if (end_val == ")") goto end; // Check for error else if (end_val != ",") error_handler::assembling_error("missing a comma after argument"); // Continue with the main loop goto main; } // Object type // Check for a namespace check_for_namespace(token, file); // Enum pointer ENUM* en; // Check enums if (en = get_enum(token)) { // Variable name, end value std::string var_name, end_val; // The type of the argument TYPE type = get_expression(var_name, end_val, file, DATA_TYPE::ENUM, nullptr, en); // Check for duplicates if (var_name != "") for (variable& arg : arguments) if (arg.get_name() == var_name) error_handler::assembling_error("argument with the name '" + C_GREEN + var_name + C_CLR + "' already exists"); // Adds the type to the argument list variable arg; // Set var name, type, line, offset arg.get_name() = var_name; arg.get_type() = type; arg.get_line() = file->get_current_line(); arg.get_offset() = file->get_current_offset(); arguments.push_back( arg ); // If end value found -> exit if (end_val == ")") goto end; // Check for error else if (end_val != ",") error_handler::assembling_error("missing a comma after argument"); // Continue with the main loop goto main; } // Set compiling namespace for a search if (compiling_namespace == nullptr && compiling_nclass != nullptr && compiling_nclass->get_namespace() != nullptr) compiling_namespace = compiling_nclass->get_namespace(); // Creates/Gets a reference to the nclass with the name nclass* obj_nclass = get_nclass_or_create(file, token); // Variable name, end value std::string var_name, end_val; // The type of the argument TYPE type = get_expression(var_name, end_val, file, DATA_TYPE::NCLASS, obj_nclass); // Check for duplicates if (var_name != "") for (variable& arg : arguments) if (arg.get_name() == var_name) error_handler::assembling_error("argument with the name '" + C_GREEN + var_name + C_CLR + "' already exists"); // Adds the type to the argument list variable arg; // Set var name, type, line, offset arg.get_name() = var_name; arg.get_type() = type; arg.get_line() = file->get_current_line(); arg.get_offset() = file->get_current_offset(); arguments.push_back(arg); // If end value found -> exit if (end_val == ")") break; // Check for error else if (end_val != ",") { error_handler::assembling_error("missing a comma after argument"); } } // Check for ending bracket end: if (!file->is_token("{")) { error_handler::compilation_error("missing bracket in method creation"); } // Set offset, line offset = file->get_current_offset(); line = file->get_current_line(); } // Default constructor for the method method::method(std::string name, TYPE type, PRE_TYPE pre_types, std::vector<variable> arguments) : name(name), type(type), pre_types(pre_types), arguments(arguments) {} // Get info about types extern std::string get_name_from_type(TYPE& type); extern std::string get_name_from_meta_type(META_DATA_TYPE& mdtype); #ifdef DEBUG void print_arguments(std::vector<variable>& vars) { debug("ARGUMENTS: "); for (variable& var : vars) var.print_info(); debug("--ARGUMENTS END--"); } #endif // NClasses, NAMESPACES extern std::vector<nclass*> nclasses; extern std::vector<NAMESPACE*> namespaces; #ifdef DEBUG // Prints info about the method void method::print_info() { std::string str = ((int) get_type().data_type == 9) ? ((type.obj_nclass != nullptr) ? " (" + type.obj_nclass->get_name() + ")" : "") : ""; std::cout << "METHOD: " << get_name() << " OF DATA_TYPE: " << get_name_from_type(type) << str << " OF META_DATA_TYPE: " << get_name_from_meta_type(get_type().mdata_type) << ": (" << get_type().mdata_size << ")" << " STATIC: " << pre_types._static << std::endl; print_arguments(arguments); } #endif // Returns the name std::string& method::get_name() { return name; } // Get namespace NAMESPACE*& method::get_namespace() { return in_namespace; } // Get the pre types PRE_TYPE& method::get_pre_types() { return pre_types; } // Returns the type TYPE& method::get_type() { return type; } // Returns the line int& method::get_line() { return line; } // Returns the offset int& method::get_offset() { return line; } // Returns arguments std::vector<variable>& method::get_arguments() { return arguments; } // The stack of instructions std::vector<INSTRUCTION> st_insts; std::vector<INST_ID> st_instids; std::stack<IF_STATEMENT> st_ifs; std::stack<FOR_STATEMENT> st_fors; std::stack<WHILE_STATEMENT> st_whiles; // Rbp offsets uint rbp_offset = 8, begin_rbp_offset = 8; // The size to remove after method calling uint rbp_remove; // Parsing utility methods extern TYPE parse_type(source_file* file, DATA_TYPE& type, PRE_TYPE& pre_types, nclass* obj_nclass = nullptr, ENUM* en = nullptr); extern PRE_TYPE parse_pre_types(source_file* file, std::string& keyword); // RAX=0, RCX=1, RDX=2, RBX=3, RSP=4, RBP=5, RSI=6, RDI=7, R8, R9, R10, R11, R12, R13, R14, R15 std::vector<unsigned char> arg_regs = {7, 6, 2, 1, 8, 9}; // AL=0, CL=1, DL=2, BL=3, AH=4, CH=5, DH=6, BH=7, R8B, R9B, R10B, R11B, R12B, R13B, R14B, R15B, SPL=16, BPL=17, SIL=18, DIL=19 std::vector<unsigned char> arg_regs8 = {19, 18, 2, 1, 8, 9}; // Converts a register to a smaller one void convert_reg(uint num, uint var_size, uint pe_var_size, bool is_signed) { // Only if var size is greater if (var_size > pe_var_size) { // Convert to 8 if (var_size == 8) { switch (pe_var_size) { case 2: is_signed ? _WI(MOVSX(reg64(arg_regs[num]), reg16(arg_regs[num]))) : _WI(MOVZX(reg64(arg_regs[num]), reg16(arg_regs[num]))); break; case 1: is_signed ? _WI(MOVSX(reg64(arg_regs[num]), reg8(arg_regs8[num]))) : _WI(MOVZX(reg64(arg_regs[num]), reg8(arg_regs8[num]))); break; } } // Convert to 4 else if (var_size == 4) { switch (pe_var_size) { case 2: is_signed ? _WI(MOVSX(reg32(arg_regs[num]), reg16(arg_regs[num]))) : _WI(MOVZX(reg32(arg_regs[num]), reg16(arg_regs[num]))); break; case 1: is_signed ? _WI(MOVSX(reg32(arg_regs[num]), reg8(arg_regs8[num]))) : _WI(MOVZX(reg32(arg_regs[num]), reg8(arg_regs8[num]))); break; } } // Convert to 2 else if (var_size == 2) { switch (pe_var_size) { case 1: is_signed ? _WI(MOVSX(reg16(arg_regs[num]), reg8(arg_regs8[num]))) : _WI(MOVZX(reg16(arg_regs[num]), reg8(arg_regs8[num]))); break; } } } } // Converts a register to a smaller one void convert_eff(uint num, uint var_size, uint pe_var_size, variable& var, bool pop = true) { // Only if var size is greater if (var_size > pe_var_size) { // Convert to 8 if (var_size == 8) { switch (pe_var_size) { case 4: _WI(MOV(reg64(arg_regs[num]), var.get_eff(pop))); break; case 2: var.is_signed() ? _WI(MOVSX(reg64(arg_regs[num]), var.get_eff(pop), PTR_SIZE::WORD)) : _WI(MOVZX(reg64(arg_regs[num]), var.get_eff(pop), PTR_SIZE::WORD)); break; case 1: var.is_signed() ? _WI(MOVSX(reg64(arg_regs[num]), var.get_eff(pop), PTR_SIZE::BYTE)) : _WI(MOVZX(reg64(arg_regs[num]), var.get_eff(pop), PTR_SIZE::BYTE)); break; } } // Convert to 4 else if (var_size == 4) { switch (pe_var_size) { case 2: var.is_signed() ? _WI(MOVSX(reg32(arg_regs[num]), var.get_eff(pop), PTR_SIZE::WORD)) : _WI(MOVZX(reg32(arg_regs[num]), var.get_eff(pop), PTR_SIZE::WORD)); break; case 1: var.is_signed() ? _WI(MOVSX(reg32(arg_regs[num]), var.get_eff(pop), PTR_SIZE::BYTE)) : _WI(MOVZX(reg32(arg_regs[num]), var.get_eff(pop), PTR_SIZE::BYTE)); break; } } // Convert to 2 else if (var_size == 2) { switch (pe_var_size) { case 1: var.is_signed() ? _WI(MOVSX(reg16(arg_regs[num]), var.get_eff(pop), PTR_SIZE::BYTE)) : _WI(MOVZX(reg16(arg_regs[num]), var.get_eff(pop), PTR_SIZE::BYTE)); break; } } } } // Copy the nclass extern void nclass_copy(variable& var, bool stack = false); // Rsp offset uint rsp_off = 0; // Move argument to register/stack void move_args(uint num, parser_expression& pe, variable& var) { // Use assembler using namespace assembler; uint var_size, pe_var_size; // If out of index, push to stack if (num > 5) { // Add to rbp_remove rbp_remove += 8; // Push number to stack if (pe.is_number()) { switch (var.size()) { case 8: _WI(MOV(reg64::RAX, (int) pe.number)); _WI(PUSH(reg64::RAX)); break; case 4: _WI(PUSH((int) pe.number)); break; case 2: _WI(MOV(reg16::AX, (short) pe.number)); _WI(PUSH(reg64::RAX)); break; case 1: _WI(MOV(reg8::AL, (char) pe.number)); _WI(PUSH(reg64::RAX)); break; } // Push variable to stack } else if (pe.is_variable()) { // Convert from pe.var.get_type() to var.get_type() var_size = var.size(); pe_var_size = pe.var.size(); // Convert if greater if (var_size > pe_var_size && !pe.var.is_pointer()) { // Convert size and push to stack conv::convert_eff((int) reg64::RAX, var_size, pe_var_size, pe.var); _WI(PUSH(reg64::RAX)); } // Else just push to stack else { pe.var.push_to_stack(); } } // Else => Already on stack, but convert if needed else if ((var_size = var.size()) > (pe_var_size = pe.var.size())){ // Convert and push back to stack conv::convert_rsp((int) reg64::RAX, var_size, pe_var_size, var.is_signed()); _WI(PUSH(reg64::RAX)); } } // Don't push to stack, but move to registers else { // Move number to register if (pe.is_number()) { switch (var.size()) { case 8: _WI(MOV_opt((reg64) arg_regs[num], (long long) pe.number)); break; case 4: _WI(MOV((reg32) arg_regs[num], (int) pe.number)); break; case 2: _WI(MOV((reg16) arg_regs[num], (short) pe.number)); break; case 1: _WI(MOV((reg8) arg_regs8[num], (char) pe.number)); break; } // Move variable to register } else if (pe.is_variable()) { // Convert from pe.var.get_type() to var.get_type() uint var_size = var.size(); uint pe_var_size = pe.var.size(); // If nclass type found if (pe.var.is_nclass_type()) { // Alloc space for var size // Add var.size() to rbp_remove // _WI(SUB(reg64::RSP, (int) (rbp_remove += var.size()))); // Copy nclass variable // nclass_copy(pe.var, false); // Move pointer to register pe.var.move_to_reg(int(arg_regs[num]), false); // Mov pointer (RSP) to REG // _WI(MOV(reg64(arg_regs[num]), reg64::RSP)); // Convert to a different type of a primitive } else if (var_size > pe_var_size && !pe.var.is_pointer()) { // Convert size convert_eff(num, var_size, pe_var_size, pe.var, false); } else { // Change size if diff size if (pe_var_size == 1) pe.var.move_to_reg(arg_regs8[num], false); else pe.var.move_to_reg(arg_regs[num], false); } // Add to rsp_off if on stack if (pe.var.on_stack) rsp_off += 8, rbp_remove += 8; // Already on stack, pop to register } else { // Pop to var // Bad idea // _WI(POP((reg64) arg_regs[num])); // Even worse _WI(MOV((reg64) arg_regs[num], effective_address<reg64>(reg64::RSP, (int) rsp_off))), rsp_off += 8; // Add to rbp_remove rbp_remove += 8; // Convert from pe.var.get_type() to var.get_type() uint var_size = var.size(); uint pe_var_size = pe.var.size(); // Convert register to smaller size convert_reg(num, var_size, pe_var_size, pe.var.is_signed()); } } } // Move arguments to registers or on stack void method::move_args_to_regs(std::vector<parser_expression>& args, bool returning_nclass, bool nclass) { // Rsp offset int val = (args.size() + (nclass ? 1 : 0) + (returning_nclass ? 1 : 0) - 6) * 8; // Only positive if (val < 0) rsp_off = 0; else rsp_off = val; // Current reg => the size of args // Set all arguments for (int i = args.size() - 1; i >= 0; i--) move_args(i + (nclass ? 1 : 0) + (returning_nclass ? 1 : 0), args[i], arguments[i]); // Reset rsp off rsp_off = 0; } // Get current namespace name std::string get_namespace_name(NAMESPACE*& nc) { // If nullptr, return "" if (nc == nullptr) return ""; // Get the names of the namespaces std::string name = nc->name; if (nc->in_namespace != nullptr) name += get_namespace_name(nc->in_namespace) + "$"; return "$" + name; } // Get signature from type std::string get_type_signature(TYPE& type) { // The type signature std::string sig; // Resolve data type switch (type.data_type) { case DATA_TYPE::VOID: sig += "v"; break; case DATA_TYPE::CHAR: sig += "c"; break; case DATA_TYPE::UCHAR: sig += "uc"; break; case DATA_TYPE::SHORT: sig += "s"; break; case DATA_TYPE::USHORT: sig += "us"; break; case DATA_TYPE::INT: sig += "i"; break; case DATA_TYPE::UINT: sig += "ui"; break; case DATA_TYPE::LONG: sig += "l"; break; case DATA_TYPE::ULONG: sig += "ul"; break; case DATA_TYPE::NCLASS: sig += "n_" + type.obj_nclass->get_name() + get_namespace_name(type.obj_nclass->get_namespace()); break; case DATA_TYPE::ENUM: sig += "e_" + type.en->name + get_namespace_name(type.en->in_namespace); break; } // If pointer -> get size and append if (type.mdata_type == META_DATA_TYPE::POINTER) for (uint i = 0; i < type.mdata_size; i++) sig += "p"; // Return the signature return sig; } // Get argument signatures std::string method::get_argument_signature() { // The argument signature std::string arg_sig; // For every argument -> get type and its signature for (variable& var : arguments) arg_sig += get_type_signature(var.get_type()); // Return argument signature return arg_sig; } // The externed object files needed (library) extern std::vector<std::string> object_files; // Externed methods -> do not add them again to externals std::vector<std::string> externed_methods; // Check if externed already bool externed(const std::string& mname) { for (auto& name : externed_methods) if (name == mname) return true; return false; } // Calls non-nclass method void method::call(std::vector<parser_expression>& args) { // Reset rbp remove rbp_remove = 0; // If returning an nclass => mov pointer to RDI bool returning_nclass; if (returning_nclass = (get_type().data_type == DATA_TYPE::NCLASS && get_type().mdata_type == META_DATA_TYPE::STORAGE && get_type().obj_nclass->size() != 0)) _WI(LEA(reg64::RDI, effective_address<reg64>(reg64::RBP, (int) -(begin_rbp_offset - 8 + align8(get_type().obj_nclass->size()))))); // Move to args to regs/stack move_args_to_regs(args, returning_nclass); // Method name std::string mname = "m#" + get_namespace_name(get_namespace()) + name + "#" + get_argument_signature(); // If in lib -> add this called method /*if (lib) { // Adding method debug("ADDING METHOD: " << asm_library_path + mname + ".o"); // If the method has already been added -> do not add again for (std::string& obj : object_files) if (obj == asm_library_path + mname + ".o") goto found; // Tell assembler to use this function and add the object file _EXTERN(mname); object_files.push_back(asm_library_path + mname + ".o"); }*/ // If already compiled => get from another object file if ((compiled || !defined) && !externed(mname)) { // Method full name -> no namespace _EXTERN(mname); // Add to list (so we do not add it again) externed_methods.push_back(mname); } // Call the method assembler::write_inst(assembler::CALL(mname)); // Remove rbp_remove size if (rbp_remove != 0) _WI(ADD(reg64::RSP, (int) rbp_remove)); } // Calls nclass method void method::in_nclass_call(variable& caller, std::vector<parser_expression>& args, nclass* obj_nclass) { // Reset rbp remove rbp_remove = 0; // Check empty bool empty = obj_nclass->size() == 0; // If return nclass bool rc = get_type().data_type == DATA_TYPE::NCLASS && get_type().mdata_type == META_DATA_TYPE::STORAGE && get_type().obj_nclass->size() != 0; // Move to args to regs/stack move_args_to_regs(args, rc, !empty); // If not empty -> move variable pointer to RDI if (!empty) { // Call method from this nclass if (caller.is_nclass_pointer_type()) caller.move_pointer_to_reg(reg64::RDI); else caller.move_to_reg((int) reg64::RDI); // If returning an nclass => mov pointer to RSI if (rc) _WI(LEA(reg64::RSI, effective_address<reg64>(reg64::RBP, (int) -(begin_rbp_offset - 8 + align8(get_type().obj_nclass->size()))))); } // If returning nclass else if (rc) { // If returning an nclass => mov pointer to RDI _WI(LEA(reg64::RDI, effective_address<reg64>(reg64::RBP, (int) -(begin_rbp_offset - 8 + align8(get_type().obj_nclass->size()))))); } // The method name std::string mname; // Constructor found if (obj_nclass->get_name() == name) { // Get method name mname = "c#" + get_namespace_name(obj_nclass->get_namespace()) + obj_nclass->get_name() + "#" + get_argument_signature(); } else { // Get method name mname = "m#" + name + "#" + get_namespace_name(obj_nclass->get_namespace()) + obj_nclass->get_name() + "#" + get_argument_signature(); } // If already compiled => get from another object file if ((compiled || !defined) && !externed(mname)) { // Method full name -> no namespace _EXTERN(mname); // Add to list (so we do not add it again) externed_methods.push_back(mname); } // Call the method assembler::write_inst(assembler::CALL(mname)); // Remove rbp_remove size if (rbp_remove != 0) _WI(ADD(reg64::RSP, (int) rbp_remove)); } // Check for duplicates void check_for_duplicates(std::vector<variable>& variables, std::vector<variable>* arguments, std::string& name) { // Check all variables for (variable& var : variables) if (var.get_name() == name) error_handler::compilation_error("variable with the name '" + frg(color_code::GREEN, graphic_rendition::NORMAL) + name + clr() + "' already defined at line " + frg(color_code::CYAN, graphic_rendition::BOLD) + std::to_string(var.get_line()+1) + clr() + ""); // If arguments defined => check them if (arguments != nullptr) for (variable& var : *arguments) if (var.get_name() == name) error_handler::compilation_error("variable with the name '" + frg(color_code::GREEN, graphic_rendition::NORMAL) + name + clr() + "' already defined at line " + frg(color_code::CYAN, graphic_rendition::BOLD) + std::to_string(var.get_line()+1) + clr() + ""); } // Return keyword inline void method::do_return() { // Check if Void return found if (compiling_method->get_type().data_type == DATA_TYPE::VOID && compiling_method->get_type().mdata_type == META_DATA_TYPE::STORAGE) { // If end right now if (file->is_token(";")) { // Remove stack frame ::LEAVE(); // Return from function _WI(RET()); } else { error_handler::compilation_error("cannot return the value in a '" + C_GREEN + "void" + C_CLR + "' function"); } return; } // Parse the next value parser p; // Assign to RAX p.parse_value_and_assign_to_reg((uint) reg64::RAX, {';'}, *file, compiling_method->get_type()); // Remove stack frame ::LEAVE(); // Return from function _WI(RET()); } // Identification // IF uint if_start = 0; uint if_end = 0; // FOR uint for_start = 0; uint for_end = 0; // WHILE uint while_start = 0; uint while_end = 0; // Get if start name inline std::string get_if_start(uint if_id) { return "s" + std::to_string(if_id); } // Get if end name inline std::string get_if_end(uint if_id) { return "e" + std::to_string(if_id); } // Get for start name inline std::string get_for_start(uint for_id) { return "f" + std::to_string(for_id); } // Get for end name inline std::string get_for_end(uint for_id) { return "g" + std::to_string(for_id); } // Get for end name inline std::string get_for_cont(uint for_id) { return "h" + std::to_string(for_id); } // Get for end name inline std::string get_for_end_out(uint for_id) { return "p" + std::to_string(for_id); } // Get while start name inline std::string get_while_start(uint for_id) { return "w" + std::to_string(for_id); } // Get while end name inline std::string get_while_end(uint for_id) { return "r" + std::to_string(for_id); } // Get while end name inline std::string get_while_cont(uint for_id) { return "z" + std::to_string(for_id); } // Get while end name inline std::string get_while_end_out(uint for_id) { return "t" + std::to_string(for_id); } // Checks else keyword inline void method::check_else() { // End here -> check for else/else if // Check else statement, as it can only go after if if (file->is_token("else")) // If next token is if if (file->is_token("if")) // Else if keyword do_if_condition(CONDITION_IF::ELSE_IF); else // Else keyword do_if_condition(CONDITION_IF::ELSE); } // Gets the byte size of the variables uint get_size(std::vector<variable>& variables) { uint size = 0; for (variable& var : variables) size += align8(var.size(false)); return size; } // Unloads the variables void unload_variables() { // Unload variables uint unload_size = get_size(st_instids.back().variables); if (unload_size != 0) _ADD_NUM(RSP, (int) unload_size); } // The condition type should be bool; but it can also be int (number) TYPE CONDITION_TYPE = {DATA_TYPE::BOOL}; // Normal type for numbers TYPE NORMAL_TYPE = {DATA_TYPE::INT}; // Parses the next condition and moves it to RAX register TYPE method::parse_condition(std::vector<char> terminate_chars) { // ********************* // PARSE CONDITION // ********************* // Create a new parser parser p; // Parse the condition return p.parse_value_and_assign_to_reg((int) reg64::RAX, {terminate_chars}, *file, CONDITION_TYPE); } // Compile statement void method::compile_statement() { // The current stack size uint st_size = st_insts.size(); // Do till we don't step out while (st_insts.size() >= st_size) { // Compile instruction compile_inst(); } } // Compares values void compare_values(TYPE t) { // Compare values switch (::size(t)) { case 8: _WI(TEST(reg64::RAX, reg64::RAX)); break; case 4: _WI(TEST(reg32::EAX, reg32::EAX)); break; case 2: _WI(TEST(reg16::AX, reg16::AX)); break; case 1: _WI(TEST(reg8::AL, reg8::AL)); break; } } // If keyword inline void method::do_if_condition(CONDITION_IF cond_if) { // Check condition if IF or ELSE IF found if (cond_if == CONDITION_IF::IF || cond_if == CONDITION_IF::ELSE_IF) { // Check for bracket; this bracket has to follow 'if' if (file->get_token() != "(") { error_handler::compilation_error("missing bracket after '" + C_BLUE + "if" + C_CLR + "' keyword"); return; } // Compares value compare_values(parse_condition({')'})); } // ********************* // IF/ELSE/ELSE IF BODY // ********************* // Check beginning bracket -> If not found, one instruction if expected bool one_inst = !file->is_token("{"); // If condition IF if (cond_if == CONDITION_IF::IF) { // Jump over if zero _WI(JZ(get_if_start(if_start))); // Push to stack st_instids.push_back({rbp_offset}); st_ifs.push({if_start++, ::if_end++}); // Ignore this statement if (file->is_token(";")) { // If ending if_end(false); return; } // Compile next instruction if (one_inst) compile_inst(); else st_insts.push_back(INSTRUCTION::IF), compile_statement(); // If ending if_end(false); } // If condition ELSE else if (cond_if == CONDITION_IF::ELSE_IF) { // Jump over if zero _WI(JZ(get_if_start(st_ifs.top().start_id))); // Ignore this statement if (file->is_token(";")) { // Else if ending else_if_end(false); return; } // Compile next instruction if (one_inst) compile_inst(); else st_insts.push_back(INSTRUCTION::ELSE_IF), compile_statement(); // Else if ending else_if_end(false); } // If condition ELSE else if (cond_if == CONDITION_IF::ELSE) { // Ignore this statement if (file->is_token(";")) { // Else end else_end(); return; } // Compile next instruction if (one_inst) compile_inst(); else st_insts.push_back(INSTRUCTION::ELSE), compile_statement(); // Else end else_end(); } } // If end void method::if_end(bool remove_from_stack) { // Unload variables unload_variables(); // Jump if else found bool else_found = false; if (else_found = (file->check_token() == "else")) // Jump to end if else found _WI(JMP(get_if_end(st_ifs.top().end_id))); // Create the label to jump to CREATE_LABEL(get_if_start(st_ifs.top().start_id), false); // Load rbp offset rbp_offset = st_instids.back().starting_rbp_offset; // If next is not an else if (!else_found) { // Create the label to jump to CREATE_LABEL(get_if_end(st_ifs.top().end_id), false); // Remove from stack st_instids.pop_back(); st_ifs.pop(); } else { // Set if start for next instruction st_ifs.top().start_id = if_start++; // Clear for next else statement st_instids.back().variables.clear(); } if (remove_from_stack) // Pop inst from stack, effectively stepping out st_insts.pop_back(); // Check for else/else if if (else_found) check_else(); } // Else if end void method::else_if_end(bool remove_from_stack) { // Unload variables unload_variables(); // Jump if else found bool else_found = false; if (else_found = (file->check_token() == "else")) // Jump to end _WI(JMP(get_if_end(st_ifs.top().end_id))); // Create the label to jump to CREATE_LABEL(get_if_start(st_ifs.top().start_id), false); // Load rbp offset rbp_offset = st_instids.back().starting_rbp_offset; // If next is not an else if (!else_found) { // Create the label to jump to CREATE_LABEL(get_if_end(st_ifs.top().end_id), false); // Remove from stack st_instids.pop_back(); st_ifs.pop(); } else { // Set if start for next instruction st_ifs.top().start_id = if_start++; // Clear for next else statement st_instids.back().variables.clear(); } if (remove_from_stack) // Pop inst from stack, effectively stepping out st_insts.pop_back(); // Check for else/else if if (else_found) check_else(); } // Else end void method::else_end() { // Unload variables unload_variables(); // Create the label to jump to CREATE_LABEL(get_if_start(st_ifs.top().start_id), false); // Create the label to jump to CREATE_LABEL(get_if_end(st_ifs.top().end_id), false); // Load last saved rbp_offset rbp_offset = st_instids.back().starting_rbp_offset; // Pop id st_instids.pop_back(); st_ifs.pop(); } // For end void method::for_end(FOR_STATEMENT& f) { // Unload variables uint unload_size = get_size(st_instids.back().variables) - align8(f.unload_after); if (unload_size > 0) _ADD_NUM(RSP, (int) unload_size); // Load last saved rbp_offset rbp_offset = st_instids.back().starting_rbp_offset; // Save offset, line uint off = file->get_current_offset(), line = file->get_current_line(); // Load saved second instructions's offset, line file->get_current_offset() = f.si_offset; file->get_current_line() = f.si_line; // If no instruction -> skip if (file->check_token() != ")") { // Create a parser parser p; // Parse the next value p.parse_value(*file, {')'}, &NORMAL_TYPE, false); } // Load saved condition's offset, line file->get_current_offset() = f.c_offset; file->get_current_line() = f.c_line; // For loop end CREATE_LABEL(get_for_end(f.end_id), false); // If no instruction -> skip if (file->check_token() != ";") { // If the condition is true -> jmp back // Compare values compare_values(parse_condition({';'})); // Jump to start if not zero _WI(JNZ(get_for_start(f.start_id))); } else { // Jump to start _WI(JMP(get_for_start(f.start_id))); } // Load saved offset, line file->get_current_offset() = off, file->get_current_line() = line; // Remove variables from stack st_instids.pop_back(); // For loop ending CREATE_LABEL(get_for_end_out(f.end_id), false); // Unload static variables if (f.unload_after != 0) _ADD_NUM(RSP, (int) align8(f.unload_after)); } // While end void method::while_end(WHILE_STATEMENT& w) { // Unload variables unload_variables(); // Load last saved rbp_offset rbp_offset = st_instids.back().starting_rbp_offset; // Save offset, line uint off = file->get_current_offset(), line = file->get_current_line(); // Load saved condition's offset, line file->get_current_offset() = w.c_offset; file->get_current_line() = w.c_line; // While loop end CREATE_LABEL(get_while_end(w.end_id), false); // Parse the condition and compare values compare_values(parse_condition({')'})); // Load saved offset, line file->get_current_offset() = off, file->get_current_line() = line; // Jump to start if not zero _WI(JNZ(get_while_start(w.start_id))); // Remove variables from stack st_instids.pop_back(); // While loop ending CREATE_LABEL(get_while_end_out(w.end_id), false); } // For keyword inline void method::do_for_loop() { // Check for bracket; this bracket has to follow 'for' if (file->get_token() != "(") { error_handler::compilation_error("missing bracket after '" + C_BLUE + "for" + C_CLR + "' keyword"); return; } // Push for to stack st_instids.push_back({rbp_offset}); // for (inst1; cond; inst2) // ********************* // INSTRUCTION 1 // ********************* // If ; present -> skip inst1 // Otherwise compile inst if (!file->is_token(";")) { // Compile next instruction compile_inst(); } // Jmp to check for condition _WI(JMP(get_for_end(::for_end))); // For loop start CREATE_LABEL(get_for_start(for_start), false); // ********************* // CONDITION/INST save // ********************* FOR_STATEMENT f; // Unload these variables afterwards for (variable& var : st_instids.back().variables) f.unload_after += var.size(false); // Set for start, end f.start_id = for_start++; f.end_id = ::for_end++; // Save condition current line, current offset f.c_offset = file->get_current_offset(); f.c_line = file->get_current_line(); // Skip the condition skip_till(file, ";"); // Save the second instruction's offset, line f.si_offset = file->get_current_offset(); f.si_line = file->get_current_line(); // Skip till ')' skip_bracket_body(file); // Ignore this statement if (file->is_token(";")) { // For end for_end(f); return; } // Add to stack st_fors.push(f), st_insts.push_back(INSTRUCTION::FOR); // If bracket not found // Compile next instruction if (!file->is_token("{")) compile_inst(), st_insts.pop_back(), st_fors.pop(); // Compile till '}' found else compile_statement(); // For loop cont label CREATE_LABEL(get_for_cont(f.end_id), false); // For end for_end(f); } // While keyword inline void method::do_while_loop() { // Check for bracket; this bracket has to follow 'while' if (file->get_token() != "(") { error_handler::compilation_error("missing bracket after '" + C_BLUE + "while" + C_CLR + "' keyword"); return; } // Push for to stack st_instids.push_back({rbp_offset}); // ********************* // CONDITION/INST save // ********************* // Jmp to check for condition _WI(JMP(get_while_end(::while_end))); // While loop start CREATE_LABEL(get_while_start(while_start), false); // While statement struct WHILE_STATEMENT w; // Set for start, end w.start_id = while_start++; w.end_id = ::while_end++; // Save condition current line, current offset w.c_offset = file->get_current_offset(); w.c_line = file->get_current_line(); // Skip till ')' skip_bracket_body(file); // Skip statement if (file->is_token(";")) { // While end while_end(w); // Semicolon ignores this statement return; } // Add to stack st_whiles.push(w), st_insts.push_back(INSTRUCTION::WHILE); // If bracket not found // Compile next statement if (!file->is_token("{")) compile_inst(), st_insts.pop_back(), st_whiles.pop(); // Compile till '}' found else compile_statement(); // While loop cont label CREATE_LABEL(get_while_cont(w.end_id), false); // While end while_end(w); } // Adds a variable to a list void method::add_variable(variable& var) { // If statement stack not empty if (!st_instids.empty()) { // Check for duplicates check_for_duplicates(st_instids.back().variables, nullptr, var.get_name()); // Compile variable var.compile(); // Save variable st_instids.back().variables.push_back(var); } else { // Check for duplicates check_for_duplicates(variables, &arguments, var.get_name()); // Compile variable var.compile(); // Save variable variables.push_back(var); } } // Get namespace method extern NAMESPACE* get_namespace(std::vector<NAMESPACE*>& namespaces, std::string& name); // The value to subtract before calling a method // that returns an nclass -> needs to be the highest val extern std::vector<assembler::byte>* obj_rbp_sub; extern uint obj_rbp_sub_val; // Get using keyword extern void do_using_keyword(source_file* file); extern nclass* get_nclass(std::string& name); // Saved namespace NAMESPACE* save_ns; // Create a parser parser p; // Compiles instruction inline void method::compile_inst() { // The instruction keyword std::string keyword = file->get_token(); // Reset obj rbp sub obj_rbp_sub = nullptr; obj_rbp_sub_val = 0; // Save namespace save_ns = compiling_namespace; // ************************** // Keyword resolving // ************************** // Pre types PRE_TYPE pre_types = parse_pre_types(file, keyword); // Ending bracket if (keyword == "}") { // Secluded ending bracket if (st_insts.empty()) { error_handler::compilation_error("secluded ending curly bracket"); return; } // Do after each instruction's end switch (st_insts.back()) { // Endings case INSTRUCTION::METHOD: case INSTRUCTION::IF: case INSTRUCTION::ELSE: case INSTRUCTION::ELSE_IF: case INSTRUCTION::FOR: case INSTRUCTION::WHILE: break; // Throw error -> no ending found default: { error_handler::compilation_error("no ending instruction found"); } } // Pop inst from stack, effectively stepping out st_insts.pop_back(); return; } // Using else if (keyword == "using") { // Using keyword do_using_keyword(file); return; } // Return else if (keyword == "return") { // Return keyword do_return(); return; } // If statement else if (keyword == "if") { // If keyword do_if_condition(CONDITION_IF::IF); return; } // For loop else if (keyword == "for") { // For keyword do_for_loop(); return; } // While loop else if (keyword == "while") { // While keyword do_while_loop(); return; } // Break else if (keyword == "break") { // Unload all variables unload_variables(); // Check empty if (st_insts.empty()) { error_handler::compilation_error("break outside of a statement"); return; } // Whether we found the searched inst bool found_inst = false; // Check the stack for (int i = st_insts.size() - 1; i >= 0; i--) { // The last instruction on stack INSTRUCTION& inst = st_insts[i]; // Check for suitable instruction // WHILE if (inst == INSTRUCTION::WHILE) { // Jmp to check for condition _WI(JMP(get_while_end_out(st_whiles.top().end_id))); found_inst = true; break; } // FOR else if (inst == INSTRUCTION::FOR) { // Jmp to check for condition _WI(JMP(get_for_end_out(st_fors.top().end_id))); found_inst = true; break; } } // No isnt for the break if (!found_inst) error_handler::compilation_error("could not find a suitable instruction in which to break"); // Semicolon check if (!file->is_token(";")) error_handler::compilation_error("missing semicolon after break"); return; } // Asm else if (keyword == "asm" && file->is_token("(")) { // Do while ending found do { // Check for quote if (!file->is_token("\"")) { error_handler::compilation_error("missing quotes after asm"); return; } // Parse the string assembler::write_string_to_inst(*file, true); // Remove comma if any file->is_token(","); } // While not found ending bracket while (!file->is_token(")")); // Check semicolon if (!file->is_token(";")) error_handler::compilation_error("missing semicolon"); return; } // Continue else if (keyword == "continue") { // Unload all variables unload_variables(); // Check empty if (st_insts.empty()) { error_handler::compilation_error("continue outside of a statement"); return; } // Whether we found the searched inst bool found_inst = false; // Check the stack for (int i = st_insts.size() - 1; i >= 0; i--) { // The last instruction on stack INSTRUCTION& inst = st_insts[i]; // Check for suitable instruction // WHILE if (inst == INSTRUCTION::WHILE) { // Jmp to check for condition _WI(JMP(get_while_cont(st_whiles.top().end_id))); found_inst = true; break; } // FOR else if (inst == INSTRUCTION::FOR) { // Jmp to check for condition _WI(JMP(get_for_cont(st_fors.top().end_id))); found_inst = true; break; } } // No inst for the break if (!found_inst) error_handler::compilation_error("could not find a suitable instruction in which to continue"); // Semicolon check if (!file->is_token(";")) error_handler::compilation_error("missing semicolon after continue"); return; } // If prompting for a namespace // If a single : is used, this will break it // Data creation DATA_TYPE* data; if (data = get_data_type(keyword)) { // Variable type TYPE t = parse_type(file, *data, pre_types); // Variable name std::string name = file->get_token(); // Create the variable variable var = {name, t, pre_types, file, file->get_current_offset(), file->get_current_line(), false}; // Add the variable to the list add_variable(var); return; } // Check for a namespace check_for_namespace(keyword, file); // NClass pointer nclass* n; // Instance creation if (n = get_nclass(keyword)) { // NClass data type DATA_TYPE dt = DATA_TYPE::NCLASS; // Variable type TYPE t = parse_type(file, dt, pre_types, n); // Create the variable variable var = {file->get_token(), t, pre_types, file, file->get_current_offset(), file->get_current_line(), false}; // Add the variable to the list add_variable(var); // Load namespace compiling_namespace = save_ns; return; } // Enum pointer ENUM* en; // Check enums if (en = get_enum(keyword)) { // NClass data type DATA_TYPE dt = DATA_TYPE::ENUM; // Variable type TYPE t = parse_type(file, dt, pre_types, nullptr, en); // Create the variable variable var = {file->get_token(), t, pre_types, file, file->get_current_offset(), file->get_current_line(), false}; // Add the variable to the list add_variable(var); // Load compiling namespace compiling_namespace = save_ns; return; } // Go back by this keyword (as we want to reuse it) file->get_current_offset() -= keyword.size(); // The terminate character char term; // Do expressions until ';' found, delimited by commas do { // Parse value until ';' found p.parse_value(*file, {';', ','}, nullptr, false); // Get terminate character term = p.terminate_character; // Clean parser p = parser(); } while (term == ','); // Load namespace compiling_namespace = save_ns; } // Checks if types are equal extern bool type_equal(TYPE& t1, TYPE& t2); // Copies all constructor nclass variables void con_variables(uint offset, variable_list& vars) { // Compile all local methods and move to the pointer for (variable* v : vars) { if (v->is_nclass_type()) con_variables(v->get_var_offset() + offset, v->get_type().obj_nclass->get_variables()); else { // Move to variable // Change register size for different sizes switch (v->size()) { // Move to rbx, then to variable (pointer in rsp) case 8: { _WI(assembler::MOV(reg64::RBX, effective_address<reg64>(reg64::RSI, (int) (offset + v->get_var_offset())))); _WI(assembler::MOV(effective_address<reg64>(reg64::RDI, (int) (offset + v->get_var_offset())), reg64::RBX)); break; } case 4: { _WI(assembler::MOV(reg32::EBX, effective_address<reg64>(reg64::RSI, (int) (offset + v->get_var_offset())))); _WI(assembler::MOV(effective_address<reg64>(reg64::RDI, (int) (offset + v->get_var_offset())), reg32::EBX)); break; } case 2: { _WI(assembler::MOV(reg16::BX, effective_address<reg64>(reg64::RSI, (int) (offset + v->get_var_offset())))); _WI(assembler::MOV(effective_address<reg64>(reg64::RDI, (int) (offset + v->get_var_offset())), reg16::BX)); break; } case 1: { _WI(assembler::MOV(reg8::BL, effective_address<reg64>(reg64::RSI, (int) (offset + v->get_var_offset())))); _WI(assembler::MOV(effective_address<reg64>(reg64::RDI, (int) (offset + v->get_var_offset())), reg8::BL)); break; } } } } } // Compiles vars void method::compile_vars(nclass* n, bool copy_constructor) { // If empty => return if (variables.empty()) return; // Add ME to their paths path p; p.get_instances().push_back(variables[0]); // Copy constructor if (copy_constructor) { // This would be the default way to copy everything, but it would take a lot of memory // in the program, so we shall use the REP MOVSQ instruction to help us // Copy all variables inside instance /*if (v->is_nclass_type()) { con_variables(v->get_var_offset(), v->get_type().obj_nclass->get_variables()); } else { // Check for array -> copy whole array if (!v->get_type().asize.empty()) { // TODO: Copy array } // Change register size for different sizes switch (v->size()) { // Move to rbx, then to variable (pointer in rsp) case 8: { _WI(assembler::MOV(reg64::RBX, effective_address<reg64>(reg64::RSI, (int) v->get_var_offset()))); _WI(assembler::MOV(effective_address<reg64>(reg64::RDI, (int) v->get_var_offset()), reg64::RBX)); break; } case 4: { _WI(assembler::MOV(reg32::EBX, effective_address<reg64>(reg64::RSI, (int) v->get_var_offset()))); _WI(assembler::MOV(effective_address<reg64>(reg64::RDI, (int) v->get_var_offset()), reg32::EBX)); break; } case 2: { _WI(assembler::MOV(reg16::BX, effective_address<reg64>(reg64::RSI, (int) v->get_var_offset()))); _WI(assembler::MOV(effective_address<reg64>(reg64::RDI, (int) v->get_var_offset()), reg16::BX)); break; } case 1: { _WI(assembler::MOV(reg8::BL, effective_address<reg64>(reg64::RSI, (int) v->get_var_offset()))); _WI(assembler::MOV(effective_address<reg64>(reg64::RDI, (int) v->get_var_offset()), reg8::BL)); break; } } }*/ // Set me to path n->get_variables()[0]->get_path() = p; // REP MOVSQ - This instruction is really cool! It's my favorite now! // Move the size/8 to rcx // align8(n->size) is divisible by 8 _WI(MOV(reg64::RCX, (int) align8(n->size()) / 8)); // Repeteadly move RCX qwords from [RSI] to [RDI] _WI(REP_MOVSQ()); } // Compile variables else { // Compile all local methods and move to the pointer for (variable* v : n->get_variables()) { // Set variable path v->get_path() = p; // Not in data v->is_in_data() = false; // Set offset, line n->set_file(v->get_file()), n->get_file()->get_current_offset() = v->get_offset(), n->get_file()->get_current_line() = v->get_line(); // Compile the variable v->compile(v); } } } // Copy and set nclass void method::copy_and_set_nclass() { // After pushing all arguments => copy nclass methods // We could technically just put it before the method to temporaries (obj_sub_rbp), // but we would need to tamper with the get_eff function to get it properly working for (int i = 0; i < arguments.size(); i++) { // Get variable variable& var = arguments[i]; // If variable is the nclass type if (var.is_nclass_type() && var.size() != 0) { // Call copy constructor // Move pointer to copy from to RSI _WI(assembler::MOV(reg64::RSI, effective_address<reg64>(reg64::RBP, (int) -var.get_rbp_offset()))); // The instance size in bytes int size = align8(var.size()); // Allocate to stack _WI(assembler::SUB(reg64::RSP, (int) size)); // Move the new variable's pointer to RDI _WI(assembler::MOV(reg64::RDI, reg64::RSP)); // The constructor to call std::string mname = "c#" + get_namespace_name(var.get_type().obj_nclass->get_namespace()) + var.get_type().obj_nclass->get_name() + "#n_" + var.get_type().obj_nclass->get_name() + get_namespace_name(var.get_type().obj_nclass->get_namespace()) + + "p"; // If already compiled => get from another object file if ((compiled || !defined) && !externed(mname)) { // Method full name -> no namespace _EXTERN(mname); // Add to list (so we do not add it again) externed_methods.push_back(mname); } // Call copy constructor _WI(assembler::CALL(mname)); // Set rbp offset var.get_rbp_offset() = (rbp_offset += size) - 8; ::begin_rbp_offset += size; } } } // Get info stuff extern std::string get_all_namespaces(NAMESPACE*& nc); extern std::string get_arg_info(std::vector<variable>& args); // Compiles the method void method::compile(bool constructor, nclass* obj_nclass) { // Set the file error_handler::set_file(*file); // If not defined and not compiled => throw warning if (!defined && !compiled) { error_handler::warning("method '" + C_GREEN + get_all_namespaces(compiling_namespace) + C_RED + "::" + C_BLUE + name + C_CLR + "' with arguments (" + get_arg_info(arguments) + C_CLR + ") has not been defined"); return; } // If already defined -> don't compile if (compiled) return; // Reset rbp offset rbp_offset = 8, begin_rbp_offset = 8; debug("COMPILING_METHOD: " << name); // Set offset, line if (file != nullptr) file->get_current_offset() = offset, file->get_current_line() = line; // Create the label for the assembler; different naming for the constructor if (constructor) assembler::CREATE_GLOBAL_LABEL("c#" + get_namespace_name(obj_nclass->get_namespace()) + obj_nclass->get_name() + "#" + get_argument_signature()); else if (obj_nclass != nullptr) assembler::CREATE_GLOBAL_LABEL("m#" + name + "#" + get_namespace_name(obj_nclass->get_namespace()) + obj_nclass->get_name() + "#" + get_argument_signature()); else assembler::CREATE_GLOBAL_LABEL("m#" + get_namespace_name(compiling_namespace) + get_name() + "#" + get_argument_signature()); // Set up stack frame if (!pre_types.nosf) { ::ENTER(); // If method is a constructor / in an nclass if (obj_nclass != nullptr) { // Whether this method is returning a copy of the nclass bool returning_nclass = get_type().data_type == DATA_TYPE::NCLASS && get_type().mdata_type == META_DATA_TYPE::STORAGE && get_type().obj_nclass->size() != 0; // The size of the current nclass uint size = obj_nclass->size(); // If not empty if (size != 0) { // Push this instance (RDI) to stack _PUSH_REG(RDI); // Create the ME variable variable me("me", {DATA_TYPE::NCLASS, META_DATA_TYPE::POINTER, 1, obj_nclass, nullptr}); me.get_rbp_offset() = ::rbp_offset; me.get_var_offset() = 0; ::rbp_offset += 8; // Push it to local variables variables.push_back(me); // If returning nclass if (returning_nclass) // Push (RSI) to stack _PUSH_REG(RSI), ::rbp_offset += 8; } // If only returning nclass => mov to rdi else if (returning_nclass) { // Push (RDI) to stack _PUSH_REG(RDI), ::rbp_offset += 8; } // Empty bool emp = size == 0; // For every argument -> set rbp offset for (int i = 0; i < arguments.size(); ++i) { // Get variable variable& var = arguments[i]; // Push variable to stack from registers / or stack if (emp) { if (returning_nclass) { // i < available_registers if (i < 5) _WI(assembler::PUSH((reg64) (arg_regs[i + 1]))); else _WI(assembler::PUSH(effective_address<reg64>(reg64::RBP, 8 * (i - 3)), PTR_SIZE::QWORD)); } else { // i < available_registers if (i < 6) _WI(assembler::PUSH((reg64) (arg_regs[i]))); else _WI(assembler::PUSH(effective_address<reg64>(reg64::RBP, 8 * (i - 4)), PTR_SIZE::QWORD)); } } // Not empty else { if (returning_nclass) { // i < available_registers if (i < 4) _WI(assembler::PUSH((reg64) (arg_regs[i + 2]))); else _WI(assembler::PUSH(effective_address<reg64>(reg64::RBP, 8 * (i - 2)), PTR_SIZE::QWORD)); } else { if (i < 5) _WI(assembler::PUSH((reg64) (arg_regs[i + 1]))); else _WI(assembler::PUSH(effective_address<reg64>(reg64::RBP, 8 * (i - 3)), PTR_SIZE::QWORD)); } } // Set rbp offset var.get_rbp_offset() = ::rbp_offset; ::rbp_offset += 8; } // Copy nclass and set to argument copy_and_set_nclass(); // Only if constructor if (constructor) { // Whether this is a copy constructor bool copy_constructor = false; // Check if copy constructor if (arguments.size() == 1) if (arguments[0].is_nclass_pointer_type() && arguments[0].get_type().obj_nclass == obj_nclass) copy_constructor = true; // Compiles vars compile_vars(obj_nclass, copy_constructor); } } // Outside method else { // Whether this method is returning a copy of the nclass bool returning_nclass = get_type().data_type == DATA_TYPE::NCLASS && get_type().mdata_type == META_DATA_TYPE::STORAGE && get_type().obj_nclass->size() != 0; // If not empty and returning an nclass if (returning_nclass) { // Push RDI to stack _PUSH_REG(RDI); // Add to rsp ::rbp_offset += 8; } // For every argument -> set rbp offset for (int i = 0; i < arguments.size(); ++i) { // Get variable variable& var = arguments[i]; // Push variable to stack from registers / or stack // Moves the pointer where to store the returning nclass (call the copy constructor) to RDI // Starting arguments at RSI unless empty if (returning_nclass) { // Push variable to stack from registers / or stack // i < available_registers if (i < 5) _WI(assembler::PUSH((reg64) (arg_regs[i + 1]))); else _WI(assembler::PUSH(effective_address<reg64>(reg64::RBP, 8 * (i - 3)), PTR_SIZE::QWORD)); } // Starting arguments at RDI else { // Push variable to stack from registers / or stack // i < available_registers if (i < 6) _WI(assembler::PUSH((reg64) (arg_regs[i]))); else _WI(assembler::PUSH(effective_address<reg64>(reg64::RBP, 8 * (i - 4)), PTR_SIZE::QWORD)); } // Set rbp offset var.get_rbp_offset() = ::rbp_offset; // Add to rbp offset ::rbp_offset += 8; } // Copy nclass and set to argument copy_and_set_nclass(); } } // Set again as compiling variables may change the file/offest/line // Set offset, line if (file != nullptr) file->get_current_offset() = offset, file->get_current_line() = line; // ********************** // COMPILE // ********************** // Artificial constructor has no code if (file != nullptr) { // Set in method st_insts.push_back(INSTRUCTION::METHOD); #ifdef DEBUG #include <chrono> auto start = std::chrono::steady_clock::now(); #endif // Compile method while (!st_insts.empty()) { // Compile instructions compile_inst(); } #ifdef DEBUG auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::cout << "method: " << elapsed_seconds.count() << "s\n"; #endif } // ********************** // TODO: Check returns and throw warning if none found => (add leave & ret if not found) // Remove stack frame if (!pre_types.nosf) ::LEAVE(); // Returns back to initial position _WI(assembler::RET()); } // Returns variables std::vector<variable>& method::get_variables() { return variables; } // Won't compile this method by setting compiled to true void method::dont_compile() { compiled = true; } // Returns the offset source_file*& method::get_file() { return file; } /** * @brief is_compiled Whether this method has already been compiled * @return yes/no */ bool method::is_compiled() { return compiled; } // Gets using namespaces std::vector<NAMESPACE*>& method::get_using_namespaces() { return using_namespaces; } // Sets defined bool method::set_defined(bool flags) { defined = flags; } // Gets defined bool& method::is_defined() { return defined; }
31.760185
264
0.542746
[ "object", "vector" ]
0345f38c8fd807333e5855fb02535ee75447bde0
12,525
cpp
C++
PCEater.cpp
TCLRainbow/PCEater
b1ed5d68fcde1a928a65c7a9c7ad82fdc2a04d21
[ "MIT" ]
null
null
null
PCEater.cpp
TCLRainbow/PCEater
b1ed5d68fcde1a928a65c7a9c7ad82fdc2a04d21
[ "MIT" ]
null
null
null
PCEater.cpp
TCLRainbow/PCEater
b1ed5d68fcde1a928a65c7a9c7ad82fdc2a04d21
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <chrono> #include <thread> #include <future> #include <cmath> #include <omp.h> #include "flags.h" #include <boost/compute/core.hpp> #include <boost/compute/algorithm/transform.hpp> #include <boost/compute/container/vector.hpp> #include <boost/compute/algorithm/iota.hpp> #include <boost/compute/algorithm/adjacent_difference.hpp> using namespace std; namespace compute = boost::compute; #define step_factor 8 [[noreturn]] void ram_easy() { uint64_t i = 0; vector<uint64_t> v; while (true) { i++; v.push_back(i); printf("Address of %lu is 0x%x\n", i, &v[i]); } } [[noreturn]] void ram_normal() { uint64_t i = 0; vector<array<uint64_t, 200000>> v; while (true) { v.push_back(*new array<uint64_t ,200000> {i}); printf("Address of %lu is 0x%x\n", i, &v[i]); i++; } } void print_time(const chrono::time_point<chrono::system_clock> &t, const string& msg) { auto allocate_time = chrono::high_resolution_clock::now(); auto time = (allocate_time - t) / chrono::milliseconds(1); printf("%s: %ldms\n", msg.c_str(), time); } long cpu_hard(uint32_t size, const string& id) { auto start_time = chrono::high_resolution_clock::now(); vector<uint32_t[25000]> frame(size); uint32_t i = 0; string id_s = "[" + id + "] "; cout << id_s << "Creating table..." << endl; for (auto & row : frame) { for (uint32_t & px : row) { px = i; i++; } } print_time(start_time, id_s + "Allocation time"); cout << id_s << "Flipping table..." << endl; for (auto & row : frame) { reverse(begin(row), end(row)); } reverse(frame.begin(), frame.end()); print_time(start_time, id_s + "Table flipped. Time taken"); auto allocate_time = chrono::high_resolution_clock::now(); return (allocate_time - start_time) / chrono::milliseconds(1); } void multi_cpu_hard(uint32_t height, uint8_t cores) { uint16_t size = height / cores; uint8_t remainder = height % cores; future<long> jobs[cores]; char id_s[2]; for (uint8_t i = 0; i < remainder; i++) { sprintf(id_s, "%d", i); jobs[i] = async(cpu_hard, size + 1, id_s); } for (uint8_t i = remainder; i < cores; i++) { sprintf(id_s, "%d", i); jobs[i] = async(cpu_hard, size, id_s); } long results[cores]; for (uint8_t i = 0; i < cores; i++) { results[i] = jobs[i].get(); } long total = 0; for (long l : results) total += l; printf("Average execution time: %ldms", total / cores); } void cpu_ram_extreme() { const uint32_t size = 250000; struct Row {uint64_t px[size];}; vector<Row> frame; uint64_t i = 0; cout << "Your PC may lag, like HUGE lag spikes. Enter something to continue."; char x; cin >> x; for (uint32_t j = 0; j < size; j++) { Row r{}; for (uint64_t & k : r.px) { i++; k = i; } printf("Address of %lu: 0x%x\n", i, &frame[i-1]); frame.push_back(r); } } uint16_t get_benchmark_target() { cout << endl <<"Note: For this option, the larger integer you input, the longer it takes to finish this benchmark, " "but it is also more accurate because it actually stresses your system."<< endl; cout << "I don't recommend you to enter something >5000." << endl; cout << "Here are some examples for multi-core : 128-> ~100s, 5000-> ~1000-1100s" << endl; uint16_t ans; do { cout << "Please enter the target ms to pass a test (128-65535): "; string input; cin >> input; ans = atoi(input.c_str()); } while (ans < 128 || ans > 65535); return ans; } uint32_t benchmark(const string& t, const uint16_t& target) { long elapsed; uint32_t size = 6000; uint16_t step = 65535; bool run = true; uint16_t limit = target - step_factor * 16; while (run) { auto start_time = chrono::high_resolution_clock::now(); vector<double> v(size); for (uint32_t i = 0; i < size; ++i) { v[i] = i*i; } while (v.size() > 1) { for (uint64_t d = 0; d < v.size() - 1; d++) v[d] += v[d+1]; v.pop_back(); } v[0] = sqrt(v[0]); elapsed = (chrono::high_resolution_clock::now() - start_time) / chrono::milliseconds(1); uint64_t count = (size * (size - 1)) >> 1; printf("%sSize %d (0x%X), count %lu (0x%lX). Step: %d (0x%X), Time: %ldms, Step limit: %dms.\n", t.c_str(), size, size, count, count, step, step, elapsed, limit); if (elapsed < limit & step < 65535) { cout << t << "Stepping up..." << endl; step <<= 1; limit -= step_factor; } else if (elapsed > target) { if (step == 1) { run = false; size -= 2; } else { cout << t << "Stepping down..." << endl; size -= step; step >>= 1; limit += step_factor; } } size += step; } cout << t << "Score: " << size << endl; return size; } BOOST_COMPUTE_FUNCTION(double, square, (double x), { return x*x; }); uint32_t cl_benchmark(const compute::device& gpu, const uint16_t& target) { printf("This GPU has %d Compute Units.\n", gpu.compute_units()); compute::context ctx(gpu); compute::command_queue queue(ctx, gpu); long elapsed; uint32_t size = 6000; uint16_t step = 1024; bool run = true; uint16_t limit = target - step_factor * 16; while (run) { auto start_time = chrono::high_resolution_clock::now(); compute::vector<double> v(size, ctx); compute::iota(v.begin(), v.end(), 1, queue); compute::transform( // b^2 and c^2 in one function v.begin(), v.end(), v.begin(), square, queue ); for (uint32_t temp_size = size; temp_size > 1; temp_size--) { compute::adjacent_difference( // b^2 + c^2 v.begin(), v.end(), v.begin(), compute::plus<double>(), queue ); v.erase(v.begin(), queue); } compute::transform( // sqrt(a) v.begin(), v.end(), v.begin(), compute::sqrt<double>(), queue ); print_time(start_time, "Done"); cout << size << endl; size += step; auto allocate_time = chrono::high_resolution_clock::now(); auto time = (allocate_time - start_time) / chrono::milliseconds(1); run = time < target; } return size; } void display_cl_dev() { cout << "Detecting OpenCL devices..." << endl; uint8_t i = 0; for (auto & device : compute::system::devices()) { i++; printf("%d. %s | %s | %s\n", i, device.vendor().c_str(), device.name().c_str(), device.version().c_str()); } } #pragma clang diagnostic push #pragma ide diagnostic ignored "openmp-use-default-none" int main() { const uint8_t cores = thread::hardware_concurrency(); cout << "©2021 Dim. All rights reserved." << endl << "PCEater v1.3 compiled with gcc " << __VERSION__ << " " << PCEaterFlags << endl << "Using Boost " << BOOST_VERSION / 100000 << "." << BOOST_VERSION / 100 % 1000 << "." << BOOST_VERSION % 100 << ", OpenCL " << CL_TARGET_OPENCL_VERSION / 100 << "." << CL_TARGET_OPENCL_VERSION / 10 % 10 << " via Boost.Compute" << endl << "Your CPU has " << to_string(cores) << " cores. PLEASE OPEN TASK MANAGER->Performance WHEN TRYING THIS PROGRAM!" << endl; while (true) { cout << endl << "-------------------------------------------------------" << endl << "RAM usage experiments:" << endl << "1. 1 core spamming 8 bytes with 0 each time (A few MB/s)" << endl << "2. 1 core spamming 200kB with 0 each time (Max RAM + A few MB/s page file)" << endl << "3. 1 core create a 250k x 250k integer table (Max 1 core + Max RAM + Max page file)" << endl << "-------------------------------------------------------" << endl << "CPU usage experiments:" << endl << "4. 1 core create a 25kx25k integer table, flip it horizontally then vertically. (Max 1 core, ~1.3s)" << endl << "5. All cores create a 25kx25k integer table, flip it horizontally then vertically. (Max all cores, ~0.94s)" << endl << "6. 1 core create a 25kx100k integer table, flip it horizontally then vertically. (Max 1 core, 10GB RAM, ~5.1s)" << endl << "7. All cores create a 25kx100k integer table, flip it horizontally then vertically. (Max all cores, 10GB RAM, ~3.7s)" << endl << "-------------------------------------------------------" << endl << "Dim's Pascal Pythagoras theorem benchmark" << endl << "8. Single core" << endl << "9. All cores (std::async)" << endl << "10. All cores (OpenMP)" << endl << "11. OpenCL device (usually GPU)" << endl << endl << "Please enter an option: "; string input; cin >> input; switch (atoi(input.c_str())) { case 1: ram_easy(); case 2: ram_normal(); case 3: cpu_ram_extreme(); break; case 4: cpu_hard(25000, ""); break; case 5: multi_cpu_hard(25000, cores); break; case 6: cpu_hard(100000, ""); break; case 7: multi_cpu_hard(100000, cores); break; case 8: benchmark("", get_benchmark_target()); break; case 9: { uint16_t target = get_benchmark_target(); future<uint32_t> jobs[cores]; auto start_time = chrono::high_resolution_clock::now(); for (uint8_t i = 0; i < cores; i++) { ostringstream oss; oss << i + 1; jobs[i] = async(benchmark, "[" + oss.str() + "] ", target); oss.clear(); } uint32_t total = 0; uint32_t scores[cores]; for (uint8_t i = 0; i < cores; i++) { scores[i] = jobs[i].get(); total += scores[i]; } cout << "=============Scores=============" << endl; for (uint8_t i = 0; i < cores; i++) printf("[%d]: %d\n", i+1, scores[i]); printf("Total score: %d. Average: %d ", total, total / cores); print_time(start_time, "Total time elapsed"); break; } case 10: { uint16_t target = get_benchmark_target(); uint32_t scores[cores]; auto start_time = chrono::high_resolution_clock::now(); #pragma omp parallel for for (uint32_t & score : scores) score = benchmark("[" + to_string(omp_get_thread_num()+1) + "] ", target); cout << "=============Scores=============" << endl; uint32_t total = 0; for (uint16_t i = 0; i < cores; i++) { total += scores[i]; printf("[%d: %d\n", i+1, scores[i]); } printf("Total score: %d. Average: %d ", total, total / cores); print_time(start_time, "Total time elapsed"); break; } case 11: { uint16_t target = get_benchmark_target(); display_cl_dev(); uint8_t option; do { cout << "Please enter the ID of GPU that you want to benchmark: "; string gpu_id; cin >> gpu_id; option = atoi(gpu_id.c_str()) - 1; } while (option >= compute::system::device_count()); uint32_t score = cl_benchmark(compute::system::devices()[option], target); cout << score << endl; break; } case 12: { compute::vector<double> test(100000); compute::iota(test.begin(), test.end(), 1); } default: cout << "I don't understand that." << endl << endl; } } } #pragma clang diagnostic pop
35.785714
137
0.511457
[ "vector", "transform" ]
0347213bcde4bf48627ad1b2bdeb0f4b9fafe422
1,271
cpp
C++
libraries/community/p1/All/NAVCOM AI Reference Design/AI_CURRENT_WORKING_STABLE/CoordThingy/c/My Project/Settings.Designer.cpp
deets/propeller
1468c8b334266f899882f404903b2dd833168799
[ "MIT" ]
82
2018-11-29T19:02:44.000Z
2022-03-11T18:50:24.000Z
libraries/community/p1/All/NAVCOM AI Reference Design/AI_CURRENT_WORKING_STABLE/CoordThingy/c/My Project/Settings.Designer.cpp
pik33/propeller
861213b91d4e6bd4e724a21389a5311d452f369d
[ "MIT" ]
30
2019-01-31T02:20:23.000Z
2022-01-26T17:50:25.000Z
libraries/community/p1/All/NAVCOM AI Reference Design/AI_CURRENT_WORKING_STABLE/CoordThingy/c/My Project/Settings.Designer.cpp
pik33/propeller
861213b91d4e6bd4e724a21389a5311d452f369d
[ "MIT" ]
73
2018-11-28T15:10:12.000Z
2022-03-22T21:00:25.000Z
#include "stdafx.h" #include "Settings.Designer.h" //INSTANT C++ NOTE: Formerly VB.NET project-level imports: using namespace System; using namespace System::Collections; using namespace System::Collections::Generic; using namespace System::Data; using namespace System::Drawing; using namespace System::Diagnostics; using namespace System::Windows::Forms; void My::MySettings::AutoSaveSettings(System::Object ^sender, System::EventArgs ^e) { if (My::MyApplication::Application::SaveMySettingsOnExit) { defaultInstance::Save(); } } MySettings ^My::MySettings::Default::get() { //INSTANT C++ WARNING: This conditional compilation directive cannot be used in C++: // #if _MyType == "WindowsForms" if (! addedHandler) { //INSTANT C++ NOTE: The following 'SyncLock' block is replaced by its VC++ equivalent: //ORIGINAL LINE: SyncLock addedHandlerLockObject System::Threading::Monitor::Enter(addedHandlerLockObject); try { if (! addedHandler) { My::MyApplication::Application::Shutdown += gcnew System::EventHandler(this, &MySettings::AutoSaveSettings); addedHandler = true; } } finally { System::Threading::Monitor::Exit(addedHandlerLockObject); } } //#endif return defaultInstance; }
27.630435
114
0.712825
[ "object" ]
0353d17ad2d96ccf864d889a19f8db330f51776b
1,010
hpp
C++
shared_model/validators/validation_error.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
1,467
2016-10-25T12:27:19.000Z
2022-03-28T04:32:05.000Z
shared_model/validators/validation_error.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
2,366
2016-10-25T10:07:57.000Z
2022-03-31T22:03:24.000Z
shared_model/validators/validation_error.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
662
2016-10-26T04:41:22.000Z
2022-03-31T04:15:02.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_VALIDATION_ERROR_HPP #define IROHA_VALIDATION_ERROR_HPP #include <string> #include <vector> namespace shared_model { namespace validation { using ReasonType = std::string; using ReasonName = std::string; /// Represents a validation error. struct ValidationError { ValidationError(ReasonName name, std::vector<ReasonType> errors, std::vector<ValidationError> child_errors = {}); std::string toString() const; /// Merge another validation error into this. ValidationError &operator|=(ValidationError other); ReasonName name; ///< Error reason kind. std::vector<ReasonType> my_errors; ///< Errors of this kind. std::vector<ValidationError> child_errors; ///< Subkind errors. }; } // namespace validation } // namespace shared_model #endif
26.578947
75
0.644554
[ "vector" ]
03549c23582b65957abf6d9b5e3f7acd71f98ec5
1,927
cpp
C++
projects/RealTimeEngine/code/LightNode.cpp
Nechrito/s0009d-lab-env
61599401536205c344654ef2a270a010df0e2254
[ "MIT" ]
null
null
null
projects/RealTimeEngine/code/LightNode.cpp
Nechrito/s0009d-lab-env
61599401536205c344654ef2a270a010df0e2254
[ "MIT" ]
null
null
null
projects/RealTimeEngine/code/LightNode.cpp
Nechrito/s0009d-lab-env
61599401536205c344654ef2a270a010df0e2254
[ "MIT" ]
null
null
null
// Copyright © 2020 Philip Lindh // All rights reserved #include "LightNode.h" #include "Camera.h" void LightNode::IncreaseIntensity(const float deltaTime) { if (intensity < maxIntensity) intensity += intensityChange * deltaTime; else intensity = maxIntensity; } void LightNode::DecreaseIntensity(const float deltaTime) { if (intensity > 0.01) intensity -= intensityChange * deltaTime; else intensity = 0.01; } void LightNode::Render(Matrix4x4& view, Matrix4x4& projection, const std::vector<Shader>& entities) const { if (this->model != nullptr) { this->model->SetPosition(position); this->model->Draw(view, projection); } for (Shader shader : entities) { shader.Bind(); shader.SetValue("CameraPosition", cameraPosition); shader.SetValue("GammaValue", gammaValue); shader.SetValue("LightType", static_cast<int>(type)); shader.SetValue("light.Position", position); shader.SetValue("light.Direction", direction); shader.SetValue("light.Color", color); shader.SetValue("light.Intensity", intensity); switch (type) { case LightType::DIRECTLIGHT: shader.SetValue("directAttribs.direction", direction); break; case LightType::POINTLIGHT: shader.SetValue("pointAttribs.constant", 1.0f); shader.SetValue("pointAttribs.linear", 0.14f); shader.SetValue("pointAttribs.quadratic", 0.07f); break; case LightType::SPOTLIGHT: shader.SetValue("light.Position", Vector3(0, 4,0)); shader.SetValue("spotAttribs.direction", Vector3(0, -1, 0)); shader.SetValue("spotAttribs.constant", 1.0f); shader.SetValue("spotAttribs.linear", 0.14f); shader.SetValue("spotAttribs.quadratic", 0.07f); shader.SetValue("spotAttribs.outerCutOff", DEG2RAD * 17.5f); shader.SetValue("spotAttribs.innerCutOff", DEG2RAD * 12.5f); break; } Shader::UnBind(); } }
27.528571
106
0.677737
[ "render", "vector", "model" ]
03567bab58ec02a0e8c8eb2641ee3c8c2c448152
2,675
hh
C++
src/gpu-compute/cl_driver.hh
dependablecomputinglab/gem5-mirror
67a00596f19c5afeb439e89468d2600dc189e5f6
[ "BSD-3-Clause" ]
3
2020-01-19T04:02:56.000Z
2022-03-29T02:12:41.000Z
src/gpu-compute/cl_driver.hh
dependablecomputinglab/gem5-mirror
67a00596f19c5afeb439e89468d2600dc189e5f6
[ "BSD-3-Clause" ]
2
2022-02-13T15:54:43.000Z
2022-03-22T06:19:28.000Z
src/gpu-compute/cl_driver.hh
dependablecomputinglab/gem5-mirror
67a00596f19c5afeb439e89468d2600dc189e5f6
[ "BSD-3-Clause" ]
3
2019-02-14T13:54:31.000Z
2021-07-09T11:06:26.000Z
/* * Copyright (c) 2012-2015 Advanced Micro Devices, Inc. * All rights reserved. * * For use for simulation and test purposes only * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Anthony Gutierrez */ #ifndef __CL_DRIVER_HH__ #define __CL_DRIVER_HH__ #include <vector> #include "gpu-compute/hsa_kernel_info.hh" #include "sim/emul_driver.hh" class GpuDispatcher; class HsaCode; class LiveProcess; class ThreadContext; struct ClDriverParams; class ClDriver final : public EmulatedDriver { public: ClDriver(ClDriverParams *p); void handshake(GpuDispatcher *_dispatcher); int open(LiveProcess *p, ThreadContext *tc, int mode, int flags); int ioctl(LiveProcess *p, ThreadContext *tc, unsigned req); const char* codeOffToKernelName(uint64_t code_ptr); private: GpuDispatcher *dispatcher; std::vector<const std::string*> codeFiles; // All the kernels we know about std::vector<HsaCode*> kernels; std::vector<HsaCode*> functions; std::vector<HsaKernelInfo> kernelInfo; // maximum size necessary for function arguments int maxFuncArgsSize; // The host virtual address for the kernel code uint64_t hsaCode; }; #endif // __CL_DRIVER_HH__
34.294872
80
0.757383
[ "vector" ]
035743abea25df09e1957cab34107a0272a5d073
349
cpp
C++
Microsoft/3.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
Microsoft/3.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
Microsoft/3.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void rotate(vector<vector<int>>& matrix) { int n = matrix.size(), m = matrix[0].size(); for (auto& x : matrix) { reverse(x.begin(), x.end()); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i > j) { swap(matrix[i][j], matrix[j][i]); } } } }
19.388889
46
0.47851
[ "vector" ]
035c0f06ac5d5c77675661ccdf272a980567501e
662
hpp
C++
include/terrain/IVoxelChunkMeshGenerator.hpp
jarrettchisholm/glr
79a57b12e26fe84595e833cace3528cb9c82bc20
[ "WTFPL" ]
11
2015-08-19T23:15:41.000Z
2018-05-15T21:53:28.000Z
include/terrain/IVoxelChunkMeshGenerator.hpp
jarrettchisholm/glr
79a57b12e26fe84595e833cace3528cb9c82bc20
[ "WTFPL" ]
2
2015-05-21T06:37:24.000Z
2015-05-23T05:37:16.000Z
include/terrain/IVoxelChunkMeshGenerator.hpp
jarrettchisholm/glr
79a57b12e26fe84595e833cace3528cb9c82bc20
[ "WTFPL" ]
5
2016-10-31T08:02:15.000Z
2018-08-24T07:40:23.000Z
#ifndef IVOXELCHUNKMESHGENERATOR_H_ #define IVOXELCHUNKMESHGENERATOR_H_ #include "IFieldFunction.hpp" #include "VoxelChunk.hpp" namespace glr { namespace terrain { class IVoxelChunkMeshGenerator { public: /** * Will generate a mesh of the provided VoxelChunk, and put the data in the provided vectors (vertices, normals, and textureBlendingValues). */ virtual void generateMesh(VoxelChunk& chunk, glm::detail::int32 length, glm::detail::int32 width, glm::detail::int32 height, std::vector<glm::vec3>& vertices, std::vector<glm::vec3>& normals, std::vector<glm::vec4>& textureBlendingValues) const = 0; }; } } #endif /* IVOXELCHUNKMESHGENERATOR_H_ */
25.461538
250
0.761329
[ "mesh", "vector" ]
035cfd78e0a927ce549bd067d9421a4405ab0ffb
1,199
cpp
C++
OJ/LeetCode/leetcode/problems/1207.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
null
null
null
OJ/LeetCode/leetcode/problems/1207.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
2
2021-10-31T10:05:45.000Z
2022-02-12T15:17:53.000Z
OJ/LeetCode/leetcode/1207.cpp
ONGOING-Z/Learn-Algorithm-and-DataStructure
3a512bd83cc6ed5035ac4550da2f511298b947c0
[ "MIT" ]
null
null
null
#//include <stdio.h> #include <vector> #include <algorithm> using namespace std; /* Leetcode */ /* Type: */ /* 题目信息 */ /* *1207. Unique Number of Occurrences Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique. Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. Example 2: Input: arr = [1,2] Output: false Example 3: Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] Output: true Constraints: 1 <= arr.length <= 1000 -1000 <= arr[i] <= 1000 */ /* my solution */ /* better solution */ // map, set ✓ class Solution { public: bool uniqueOccurrences(vector<int>& arr) { map<int, int> mp; set<int> s; // find out each number's occurrence number for (int i = 0; i < arr.size(); i++) { mp[arr[i]]++; } for (auto it = mp.begin(); it != mp.end(); it++) { s.insert(it->second); } return mp.size() == s.size(); } }; /* 一些总结 */ // 1. 题意: // // 需要注意的点: // 1. // 2. // 3.
18.166667
145
0.562135
[ "vector" ]
24e94f5d463bdf8331f6d14e054fac71fa8756bc
1,690
cpp
C++
Codechef/Interesting XOR!/Interesting XOR!.cpp
rahil-1407/Data-Structure-and-Algorithms
ea3eb9849aeb2716ef5812a0b5621a28120b1880
[ "MIT" ]
51
2021-01-14T04:05:55.000Z
2022-01-25T11:25:37.000Z
Codechef/Interesting XOR!/Interesting XOR!.cpp
rahil-1407/Data-Structure-and-Algorithms
ea3eb9849aeb2716ef5812a0b5621a28120b1880
[ "MIT" ]
638
2020-12-27T18:49:53.000Z
2021-11-21T05:22:52.000Z
Codechef/Interesting XOR!/Interesting XOR!.cpp
rahil-1407/Data-Structure-and-Algorithms
ea3eb9849aeb2716ef5812a0b5621a28120b1880
[ "MIT" ]
124
2021-01-30T06:40:20.000Z
2021-11-21T15:14:40.000Z
#include <bits/stdc++.h> using namespace std; int main() { // your code goes here ios_base::sync_with_stdio(false); cin.tie(NULL); long int t,n,count=0,i; cin>>t; //test cases while(t--){ cin>>n; stack<int> binary; //stack to store binary 0, 1 values i = 0; while (n > 0) { // storing remainder in binary array binary.push(n%2); n = n / 2; i++; } count=i; vector<int> num1,num2; //binary digits of both numbers stored for (int i=0;i<count;i++){ //iterate through the binary form of the entered digit if (i==0){ num1.push_back(1); if (binary.top()==0){ num2.push_back(1); } else num2.push_back(0); } else if (i==1){ num2.push_back(1); if (binary.top()==0){ num1.push_back(1); } else num1.push_back(0); } else if (binary.top()==0){ num1.push_back(1); num2.push_back(1); } else{ num1.push_back(0); num2.push_back(1); } binary.pop(); } long long int n1=0,n2=0; //convert numbers from binary to decimal for (int i=0;i<num1.size();i++){ n1*=2; n1+=(num1[i]*2); } for (int i=0;i<num2.size();i++){ n2*=2; n2+=num2[i]*2; } // cout<<n1<<" "<<n2<<" "; cout<<n1*n2/4<<"\n"; } return 0; }
24.852941
89
0.405917
[ "vector" ]
24ed3077a51e4062b7410fc2986067743e489747
4,203
cpp
C++
source/geometry/GeometryTile.cpp
xhuan28/MNN
81df3a48d79cbc0b75251d12934345948866f7be
[ "Apache-2.0" ]
6,958
2019-05-06T02:38:02.000Z
2022-03-31T18:08:48.000Z
source/geometry/GeometryTile.cpp
xhuan28/MNN
81df3a48d79cbc0b75251d12934345948866f7be
[ "Apache-2.0" ]
1,775
2019-05-06T04:40:19.000Z
2022-03-30T15:39:24.000Z
source/geometry/GeometryTile.cpp
xhuan28/MNN
81df3a48d79cbc0b75251d12934345948866f7be
[ "Apache-2.0" ]
1,511
2019-05-06T02:38:05.000Z
2022-03-31T16:59:39.000Z
// // GeometryTile.cpp // MNN // // Created by MNN on 2020/04/21. // Copyright © 2018, Alibaba Group Holding Limited // #include "geometry/GeometryComputer.hpp" #include "core/Macro.h" #include "core/OpCommonUtils.hpp" namespace MNN { class GeometryTile : public GeometryComputer { public: virtual bool onCompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, Context& context, CommandBuffer& res) const override { MNN_ASSERT(1 == outputs.size()); auto multiples = inputs[1]; auto output = outputs[0]; auto input = inputs[0]; // Compute Remain size and stride because region can only support up to 3 int remainSize = 1; std::vector<int> remainDims; for (int i = 0; i < input->dimensions() - 3; ++i) { remainSize *= input->length(i); remainDims.emplace_back(input->length(i)); } std::vector<int32_t> mod(remainDims.size()); OpCommonUtils::computeStride(mod.data(), remainDims.data(), remainDims.size()); // Compute Multiply Stride auto mulPtr = multiples->host<int32_t>(); int copyTimes = 1; for (int i = 0; i < input->dimensions(); ++i) { copyTimes *= mulPtr[i]; } std::vector<int32_t> modMulti(input->dimensions()); for (int i = 0; i < modMulti.size(); ++i) { int value = 1; for (int j = i + 1; j < input->dimensions(); ++j) { value *= mulPtr[j]; } modMulti[i] = value; } // Compute input and output stride // input stride use for remainSize split // output stride use for remainSize split and tile split std::vector<int> inputStrides(input->dimensions()); std::vector<int> outputStrides(input->dimensions()); { int strides = 1; int outStrides = 1; for (int i = input->dimensions() - 1; i >= 0; --i) { inputStrides[i] = strides; strides *= input->length(i); outputStrides[i] = outStrides; outStrides *= output->length(i); } } // Compute regions, first iter copyTimes, second iter remainSize auto outputDes = TensorUtils::getDescribe(output); outputDes->regions.resize(copyTimes * remainSize); outputDes->memoryType = Tensor::InsideDescribe::MEMORY_VIRTUAL; std::vector<int> coordinates(modMulti.size()); for (int u = 0; u < copyTimes; ++u) { int dstOffset = 0; OpCommonUtils::unravelIndexHelper(coordinates, modMulti, modMulti.size(), u); for (int i = 0; i < modMulti.size(); ++i) { dstOffset += coordinates[i] * input->length(i) * outputStrides[i]; } for (int v = 0; v < remainSize; ++v) { auto& region = outputDes->regions[u * remainSize + v]; region.src.offset = 0; region.origin = input; auto value = v; region.dst.offset = dstOffset; for (int i = 0; i < 3; ++i) { auto match = input->dimensions() - i - 1; if (match < 0) { continue; } region.size[3 - i - 1] = input->length(match); region.src.stride[3 - i - 1] = inputStrides[match]; region.dst.stride[3 - i - 1] = outputStrides[match]; } for (int i = 0; i < remainDims.size(); ++i) { auto coordinate = value / mod[i]; region.src.offset += coordinate * inputStrides[i]; region.dst.offset += coordinate * outputStrides[i]; value = value % mod[i]; } } } return true; } }; static void _create() { std::shared_ptr<GeometryComputer> comp(new GeometryTile); GeometryComputer::registerGeometryComputer(comp, {OpType_Tile}); } REGISTER_GEOMETRY(GeometryTile, _create); } // namespace MNN
39.280374
113
0.526291
[ "geometry", "vector" ]
24ed422a10f88b1efae520fa84245662941844d6
27,611
cpp
C++
trajectory_planner/src/c_manage_trajectory.cpp
ricardolfsilva/trajectory_planner
0840d74921feb79569de67a765c7d3c011ff8868
[ "MIT" ]
1
2021-09-25T15:05:04.000Z
2021-09-25T15:05:04.000Z
trajectory_planner/src/c_manage_trajectory.cpp
ricardolfsilva/trajectory_planner
0840d74921feb79569de67a765c7d3c011ff8868
[ "MIT" ]
null
null
null
trajectory_planner/src/c_manage_trajectory.cpp
ricardolfsilva/trajectory_planner
0840d74921feb79569de67a765c7d3c011ff8868
[ "MIT" ]
null
null
null
/************************************************************************************************** Software License Agreement (BSD License) Copyright (c) 2011-2013, LAR toolkit developers - University of Aveiro - http://lars.mec.ua.pt All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: *Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. *Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. *Neither the name of the University of Aveiro nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************************************/ /** * @file c_manage_trajectory.cpp * @brief c_manage_trajectory class manager * @author Joel Pereira * @version v0 * @date 2012-04-19 */ /** * @file c_manage_trajectory.cpp * @brief c_manage_trajectory class manager * @author Ricardo Silva * @version v1 * @date 2018-06-06 */ #include <trajectory_planner/c_manage_trajectory.h> #include <trajectory_planner/trajectory_planner_nodelet.h> /** * @brief Compute the free space. Determines the inclusion of a point in the rectangle that represents the car geometry. * @param trajectory_planner * @param vo * @return t_func_output */ t_func_output c_manage_trajectory::compute_DLO(c_trajectoryPtr& trajectory, std::vector<t_obstacle>& vo) { // delete all previous computed collision pts trajectory->collision_pts.erase(trajectory->collision_pts.begin(), trajectory->collision_pts.end()); if (trajectory->closest_node < 0 || trajectory->closest_node >= (int)trajectory->x.size()) { ROS_ERROR("Error on node"); return FAILURE; } // cycle all nodes until the closest node trajectory->score.DLO = 10.0; // Equal to maximum_admissible_to_DLO trajectory->score.FS = 1; trajectory->score.CL = 1; trajectory->score.EVAL = 10.0; for (int n = 0; n <= trajectory->closest_node; ++n) { if (trajectory->v_lines.size() - 1 != trajectory->x.size()) { ROS_ERROR("Node lines and number of nodes not equal"); } // polygon to calculate intersections geometry_msgs::Polygon car_polygon; for (size_t l = 0; l < trajectory->v_lines[n].size(); ++l) { geometry_msgs::Point32 point; point.x = trajectory->v_lines[n][l].x[0]; point.y = trajectory->v_lines[n][l].y[0]; point.z = 0; // pointPcl.z; car_polygon.points.push_back(point); if (l == (trajectory->v_lines[n].size() - 1)) { point.x = trajectory->v_lines[n][l].x[1]; point.y = trajectory->v_lines[n][l].y[1]; point.z = 0; // pointPcl.z; car_polygon.points.push_back(point); } } int car_polygon_size = car_polygon.points.size() - 1; // ROS_INFO("polygon size = %ld", car_polygon.points.size()); // cycle all vehicle lines for (size_t l = 0; l < trajectory->v_lines[n].size(); ++l) { double Ax = trajectory->v_lines[n][l].x[0]; double Ay = trajectory->v_lines[n][l].y[0]; double Bx = trajectory->v_lines[n][l].x[1]; double By = trajectory->v_lines[n][l].y[1]; // cycle all obstacles // ROS_INFO("vo size = %ld", vo.size()); for (size_t o = 0; o < vo.size(); ++o) { // cycle all lines inside each obstacle for (size_t lo = 0; lo < vo[o].x.size(); ++lo) { double DLOprev = sqrt(pow(trajectory->v_lines[n][l].x[0] - vo[o].x[lo], 2) + pow(trajectory->v_lines[n][l].y[0] - vo[o].y[lo], 2)); if (trajectory->score.DLO > DLOprev) { trajectory->score.DLO = DLOprev; } // simulator evaluation if (n == 0 && trajectory->score.EVAL > DLOprev) { trajectory->score.EVAL = DLOprev; } geometry_msgs::Point32 P; P.x = vo[o].x[lo]; P.y = vo[o].y[lo]; P.z = 0; // pointPcl.z; int wn = wn_PnPoly(P, &car_polygon, car_polygon_size); if (wn != 0) { t_point p; p.x = P.x; p.y = P.y; trajectory->collision_pts.push_back(p); trajectory->score.FS *= 0; } } } // road lines if (_simulation_) { // ROS_INFO("vl size = %ld", vl.size()); for (size_t oo = 0; oo < vl.size(); ++oo) { for (size_t ll = 0; ll < vl[oo].x.size(); ++ll) { geometry_msgs::Point32 P; P.x = vl[oo].x[ll]; P.y = vl[oo].y[ll]; P.z = 0; // pointPcl.z; int wn = wn_PnPoly(P, &car_polygon, car_polygon_size); if (wn != 0) { t_point p; p.x = P.x; p.y = P.y; if (trajectory->alpha[0] >= 0) { trajectory->score.CL = W_CL; } } } } } } } return SUCCESS; } /** * @brief Winding number test for a point in a polygon * @param P = a point * @param V[] = vertex points of a polygon V[n+1] with V[n]=V[0] * @param n = number of points * @return wn = the winding number (=0 only when P is outside) */ int c_manage_trajectory::wn_PnPoly(geometry_msgs::Point32 P, geometry_msgs::Polygon* V, int n) { int wn = 0; // the winding number counter // loop through all edges of the polygon for (int i = 0; i < n; i++) { // edge from V[i] to V[i+1] if (V->points[i].y <= P.y) { // start y <= P.y if (V->points[i + 1].y > P.y) // an upward crossing if (isLeft(V->points[i], V->points[i + 1], P) > 0) // P left of edge ++wn; // have a valid up intersect } else { // start y > P.y (no test needed) if (V->points[i + 1].y <= P.y) // a downward crossing if (isLeft(V->points[i], V->points[i + 1], P) < 0) // P right of edge --wn; // have a valid down intersect } } return wn; } /** * @brief Tests if a point is Left|On|Right of an infinite line * @param P0, P1, and P2 = points * @return >0 for P2 left of the line through P0 and P1 =0 for P2 on the line <0 for P2 right of the line */ inline int c_manage_trajectory::isLeft(geometry_msgs::Point32 P0, geometry_msgs::Point32 P1, geometry_msgs::Point32 P2) { return ((P1.x - P0.x) * (P2.y - P0.y) - (P2.x - P0.x) * (P1.y - P0.y)); } /** * @brief Verifies intersections between lines * * @param Ax * @param Ay * @param Bx * @param By * @param Cx * @param Cy * @param Dx * @param Dy * @param X * @param Y * @return int */ int c_manage_trajectory::lineSegmentIntersection(double Ax, double Ay, double Bx, double By, double Cx, double Cy, double Dx, double Dy, double* X, double* Y) { double distAB, theCos, theSin, newX, ABpos; // Fail if either line segment is zero-length. if (((Ax == Bx) && (Ay == By)) || ((Cx == Dx) && (Cy == Dy))) return DONT_INTERSECT; // Fail if the segments share an end-point. if (((Ax == Cx) && (Ay == Cy)) || ((Bx == Cx) && (By == Cy)) || ((Ax == Dx) && (Ay == Dy)) || ((Bx == Dx) && (By == Dy))) { return DONT_INTERSECT; } // (1) Translate the system so that point A is on the origin. Bx -= Ax; By -= Ay; Cx -= Ax; Cy -= Ay; Dx -= Ax; Dy -= Ay; // Discover the length of segment A-B. distAB = sqrt(Bx * Bx + By * By); // (2) Rotate the system so that point B is on the positive X axis. theCos = Bx / distAB; theSin = By / distAB; newX = Cx * theCos + Cy * theSin; Cy = Cy * theCos - Cx * theSin; Cx = newX; newX = Dx * theCos + Dy * theSin; Dy = Dy * theCos - Dx * theSin; Dx = newX; // Fail if segment C-D doesn't cross line A-B. if ((Cy < 0. && Dy < 0.) || (Cy >= 0. && Dy >= 0.)) return DONT_INTERSECT; // (3) Discover the position of the intersection point along line A-B. ABpos = Dx + (Cx - Dx) * Dy / (Dy - Cy); // Fail if segment C-D crosses line A-B outside of segment A-B. if (ABpos < 0. || ABpos > distAB) return DONT_INTERSECT; // (4) Apply the discovered position to line A-B in the original coordinate system. *X = Ax + ABpos * theCos; *Y = Ay + ABpos * theSin; // Success. return DO_INTERSECT; } /** * @brief Sets the obstacles * @param mtt::TargetListPC& msg * @return t_func_output */ t_func_output c_manage_trajectory::set_obstacles(mtt::TargetListPC& msg) { vo.erase(vo.begin(), vo.end()); // ROS_INFO("msg_obstacles size = %ld", msg.obstacle_lines.size()); for (size_t i = 0; i < msg.obstacle_lines.size(); ++i) { t_obstacle o; pcl::PointCloud<pcl::PointXYZ> pc; pcl::PCLPointCloud2 pcl_pc; pcl_conversions::toPCL(msg.obstacle_lines[i], pcl_pc); pcl::fromPCLPointCloud2(pcl_pc, pc); for (size_t j = 0; j < pc.points.size(); ++j) { o.x.push_back(pc.points[j].x); o.y.push_back(pc.points[j].y); } vo.push_back(o); } return SUCCESS; } /** * @brief Sets the obstacles * @param mtt::TargetListPC& msg * @return t_func_output */ t_func_output c_manage_trajectory::set_lines(mtt::TargetListPC& msg) { vl.erase(vl.begin(), vl.end()); // ROS_INFO("msg_lines size = %ld", msg.obstacle_lines.size()); for (size_t i = 0; i < msg.obstacle_lines.size(); ++i) { t_obstacle o; pcl::PointCloud<pcl::PointXYZ> pc; pcl::PCLPointCloud2 pcl_pc; pcl_conversions::toPCL(msg.obstacle_lines[i], pcl_pc); pcl::fromPCLPointCloud2(pcl_pc, pc); for (size_t j = 0; j < pc.points.size(); ++j) { o.x.push_back(pc.points[j].x); o.y.push_back(pc.points[j].y); } vl.push_back(o); } return SUCCESS; } /** * @brief Set the vehicle description * * @param w * @param lb * @param lf * @param ht * @param hb * @return t_func_output */ t_func_output c_manage_trajectory::set_vehicle_description(double w, double lb, double lf, double ht, double hb) { vehicle_description.width = w; vehicle_description.lenght_back = lb; vehicle_description.lenght_front = lf; vehicle_description.height_top = ht; vehicle_description.height_bottom = hb; return SUCCESS; } /** * @brief Gets the info of chosen nodes * * @param info * @return t_func_output */ t_func_output c_manage_trajectory::get_traj_info_msg_from_chosen(trajectory_planner::traj_info* info) { info->arc.erase(info->arc.begin(), info->arc.end()); info->total_arc.erase(info->total_arc.begin(), info->total_arc.end()); info->alpha.erase(info->alpha.begin(), info->alpha.end()); info->speed.erase(info->speed.begin(), info->speed.end()); for (int j = 0; j <= (int)vt[chosen_traj.index]->closest_node; ++j) { info->arc.push_back(vt[chosen_traj.index]->arc[j]); info->total_arc.push_back(vt[chosen_traj.index]->total_arc[j]); info->alpha.push_back(vt[chosen_traj.index]->alpha[j]); } set_speed_vector(info); // cout<<"ARC SIZE (when constructing) "<<info->arc.size()<<endl; // cout<<"TOTAL ARC SIZE (when constructing) "<<info->total_arc.size()<<endl; // cout<<"ALPHA SIZE (when constructing) "<<info->alpha.size()<<endl; // cout<<"SPEED SIZE (when constructing) "<<info->speed.size()<<endl; return SUCCESS; } /** * @brief Determine the speed vector * * @param info * @return t_func_output */ t_func_output c_manage_trajectory::set_speed_vector(trajectory_planner::traj_info* info) { for (int i = 0; i <= (int)vt[chosen_traj.index]->closest_node; ++i) { if (i < ((int)vt[chosen_traj.index]->arc.size() - 1)) { if ((info->arc[i]) * (info->arc[i + 1]) < 0.0) { info->speed.push_back((info->arc[i] / fabs(info->arc[i])) * _SPEED_SAFFETY_); // This is the speed set to reverse/forward or forward/reverse } else { info->speed.push_back((info->arc[i] / fabs(info->arc[i])) * _SPEED_REQUIRED_); } } else { info->speed.push_back((info->arc[i] / fabs(info->arc[i])) * _SPEED_REQUIRED_); } } return SUCCESS; } /** * @brief Set the chosen trajectory * @param int n * @return int */ int c_manage_trajectory::set_chosen_traj(int n) { chosen_traj.index = n; return 1; } /** * @brief Set the attractor point * @param x * @param y * @param theta * @return t_func_output */ t_func_output c_manage_trajectory::set_attractor_point(double x, double y, double theta) { AP.x = x; AP.y = y; AP.theta = theta; return SUCCESS; } /** * @brief Computes the trajectory global score * @param trajectory * @return t_func_output */ t_func_output c_manage_trajectory::compute_global_traj_score(c_trajectoryPtr& trajectory) { // double W_DAP = 0.40; // double W_ADAP = 0.35; // double W_DLO = 0.25; trajectory->score.overall_norm = (W_DAP * trajectory->score.DAPnorm + W_ADAP * trajectory->score.ADAPnorm + W_DLO * trajectory->score.DLOnorm) * trajectory->score.FS * trajectory->score.CL; // cout<<"Overallscore= "<<trajectory->score.overall_norm<<endl; return SUCCESS; } /** * @brief Set the inter-axis distance of the vehicle * @param val * @return t_func_output */ t_func_output c_manage_trajectory::set_inter_axis_distance(double val) { inter_axis_distance = val; return SUCCESS; } /** * @brief Create a trajectory * @param alpha_in * @param arc_in * @param speed_in * @return t_func_output */ t_func_output c_manage_trajectory::create_new_trajectory(vector<double> alpha_in, vector<double> arc_in, vector<double> speed_in) { // allocate space for new traj c_trajectoryPtr t_ptr(new c_trajectory(inter_axis_distance)); vt.push_back(t_ptr); // set the parameters of the traj return vt[vt.size() - 1]->generate(alpha_in, arc_in, speed_in, vehicle_description); } /** * @brief Update a trajectory during planning execution * @param alpha_in * @param arc_in * @param speed_in * @param traj_num * @return t_func_output */ t_func_output c_manage_trajectory::update_trajectory(vector<double> alpha_in, vector<double> arc_in, vector<double> speed_in, int traj_num) { // set the parameters of the traj return vt[traj_num]->generate(alpha_in, arc_in, speed_in, vehicle_description); } /** * @brief Chooses the trajectory * @return t_func_output */ t_func_output c_manage_trajectory::compute_chosen_traj(void) { double max_val = -1000; chosen_traj.index = -1; for (int i = 0; i < (int)vt.size(); i++) { if (vt[i]->score.overall_norm > max_val) { chosen_traj.index = i; chosen_traj.min_dist = vt[i]->score.EVAL; chosen_traj.alpha = vt[i]->alpha[0]; chosen_traj.score = vt[i]->score.overall_norm; max_val = vt[i]->score.overall_norm; } } if (chosen_traj.index != -1) return SUCCESS; else return FAILURE; } /** * @brief Create a static marker * @return t_func_output */ t_func_output c_manage_trajectory::create_static_markers(void) { // cout<<"ja create static"<<endl; static_marker_vec.clear(); int marker_count = 0; for (int i = 0; i < (int)vt.size(); i++) { vt[i]->create_markers(&static_marker_vec, &marker_count, i); } return SUCCESS; } /** * @brief Compute the markers array * @param marker_array * @return t_func_output */ t_func_output c_manage_trajectory::compute_vis_marker_array(visualization_msgs::MarkerArray* marker_array) { std::vector<visualization_msgs::Marker> marker_vec; // ROS_INFO("static marker vec size=%ld", static_marker_vec.size()); for (size_t i = 0; i < static_marker_vec.size(); ++i) { marker_vec.push_back(static_marker_vec[i]); } int marker_count = 0; for (int i = 0; i < (int)vt.size(); ++i) { // draw_on_node(vt[i], &marker_vec, &marker_count, 0.15, vt[i]->score.DAP, vt[i]->score.DAPnorm, "DAP "); // draw_on_node(vt[i], &marker_vec, &marker_count, 0.30, vt[i]->score.ADAP, vt[i]->score.ADAPnorm, "ADAP "); // draw_on_node(vt[i], &marker_vec, &marker_count, 0.45, vt[i]->score.DLO, vt[i]->score.DLOnorm, "DLO "); draw_on_node(vt[i], &marker_vec, &marker_count, 0.60, (vt[i]->score.DAP + vt[i]->score.ADAP + vt[i]->score.DLO) * vt[i]->score.FS, vt[i]->score.overall_norm, "P = "); } // ________________________________ //| | //| Line List | //|________________________________| // Line marker to trajectory visualization_msgs::Marker marker2; geometry_msgs::Point p; marker2.header.frame_id = "/vehicle_odometry"; marker2.header.stamp = ros::Time::now(); marker2.ns = "chosen_trajectory"; marker2.id = 0; marker2.action = visualization_msgs::Marker::ADD; marker2.type = visualization_msgs::Marker::LINE_LIST; marker2.scale.x = 0.08; marker2.color.r = 0.039; marker2.color.g = 0.619; marker2.color.b = 0.039; marker2.color.a = 1.00; int first_step = 1; for (size_t i = 0; i < vt[chosen_traj.index]->x.size(); ++i) { if (first_step == 1) { p.x = 0; p.y = 0; p.z = 2; marker2.points.push_back(p); p.x = vt[chosen_traj.index]->x[i]; p.y = vt[chosen_traj.index]->y[i]; p.z = 2; marker2.points.push_back(p); first_step = 0; } else { p.x = vt[chosen_traj.index]->x[i - 1]; p.y = vt[chosen_traj.index]->y[i - 1]; p.z = 2; marker2.points.push_back(p); p.x = vt[chosen_traj.index]->x[i]; p.y = vt[chosen_traj.index]->y[i]; p.z = 2; marker2.points.push_back(p); } } marker_vec.push_back(marker2); // ________________________________ //| | //| Rectangle (actual) | //|________________________________| // Represents the form of the car in each node visualization_msgs::Marker marker5; marker5.header.frame_id = "/vehicle_odometry"; marker5.header.stamp = ros::Time::now(); marker5.ns = "car_actual_traj"; marker5.id = 0; marker5.action = visualization_msgs::Marker::ADD; marker5.type = visualization_msgs::Marker::CUBE; marker5.scale.x = _VEHICLE_LENGHT_FRONT_ + _VEHICLE_LENGHT_BACK_; marker5.scale.y = _VEHICLE_WIDTH_; marker5.scale.z = 0.001; marker5.color.r = 0; marker5.color.g = 1; marker5.color.b = 0; marker5.color.a = 0.1; for (size_t i = 0; i <= vt[chosen_traj.index]->x.size(); ++i) { if (i == 0) { marker5.pose.position.x = ((_VEHICLE_LENGHT_FRONT_ + _VEHICLE_LENGHT_BACK_) / 2 - _VEHICLE_LENGHT_BACK_) * cos(0); marker5.pose.position.y = ((_VEHICLE_LENGHT_FRONT_ + _VEHICLE_LENGHT_BACK_) / 2 - _VEHICLE_LENGHT_BACK_) * sin(0); marker5.pose.position.z = -0.1; marker5.pose.orientation.z = sin(0); marker5.pose.orientation.w = cos(0); } else { marker5.pose.position.x = vt[chosen_traj.index]->x[i - 1] + ((_VEHICLE_LENGHT_FRONT_ + _VEHICLE_LENGHT_BACK_) / 2 - _VEHICLE_LENGHT_BACK_) * cos(vt[chosen_traj.index]->theta[i - 1]); marker5.pose.position.y = vt[chosen_traj.index]->y[i - 1] + ((_VEHICLE_LENGHT_FRONT_ + _VEHICLE_LENGHT_BACK_) / 2 - _VEHICLE_LENGHT_BACK_) * sin(vt[chosen_traj.index]->theta[i - 1]); marker5.pose.position.z = -0.1; marker5.pose.orientation.z = sin(vt[chosen_traj.index]->theta[i - 1] / 2); marker5.pose.orientation.w = cos(vt[chosen_traj.index]->theta[i - 1] / 2); } marker_vec.push_back(marker5); marker5.id += 1; } // ________________________________ //| | //| Best node (sphere) | //|________________________________| // Represents the form of the car in each node visualization_msgs::Marker marker3; marker3.header.frame_id = "/vehicle_odometry"; marker3.header.stamp = ros::Time::now(); marker3.ns = "closest_node"; marker3.action = visualization_msgs::Marker::ADD; marker3.type = visualization_msgs::Marker::SPHERE; marker3.scale.x = 0.2; marker3.scale.y = 0.2; marker3.scale.z = 0.2; marker3.color.r = 1.0; marker3.color.g = 0.0; marker3.color.b = 0.1; marker3.color.a = 0.6; for (size_t i = 0; i < vt.size(); ++i) { marker3.id += 2; marker3.pose.position.x = vt[i]->x[vt[i]->closest_node]; marker3.pose.position.y = vt[i]->y[vt[i]->closest_node]; marker3.pose.position.z = 0; marker_vec.push_back(marker3); } // ________________________________ //| | //| Colision (cylinder) | //|________________________________| // Represents the form of the car in each node visualization_msgs::Marker marker4; marker4.header.frame_id = "/vehicle_odometry"; marker4.header.stamp = ros::Time::now(); marker4.ns = "colision_points"; marker4.action = visualization_msgs::Marker::ADD; marker4.type = visualization_msgs::Marker::CYLINDER; marker4.scale.x = 0.12; marker4.scale.y = 0.12; marker4.scale.z = 0.1; marker4.color.r = 1.0; marker4.color.g = 0.84; marker4.color.b = 0.0; marker4.color.a = 1.0; static size_t coli_marker_total = 0; int total = 0; for (size_t j = 0; j < vt.size(); ++j) { // ROS_INFO("Traj%ld has %ld collisions\n", j, vt[j]->collision_pts.size()); for (size_t i = 0; i < vt[j]->collision_pts.size(); ++i) { marker4.id = total; marker4.pose.position.x = vt[j]->collision_pts[i].x; marker4.pose.position.y = vt[j]->collision_pts[i].y; marker_vec.push_back(marker4); total++; } } // ROS_INFO("total=%d coli=%ld", total, coli_marker_total); // erase old colision markers for (size_t j = total; j < coli_marker_total; ++j) { // ROS_INFO("deleting marker "); marker4.header.frame_id = "/vehicle_odometry"; marker4.id = j; marker4.action = visualization_msgs::Marker::DELETE; marker_vec.push_back(marker4); } coli_marker_total = total; marker_array->markers = marker_vec; return SUCCESS; } /** * @brief Compute trajectories scores * @return t_func_output */ t_func_output c_manage_trajectory::compute_trajectories_scores(void) { double maximum_admissible_to_DAP = 8.0; // ATENTION to negative values if bigger than maximum double maximum_admissible_to_DLO = 10.0; // ATENTION to negative values if bigger than maximum for (int i = 0; i < (int)vt.size(); ++i) { // Compute DAP and ADAP compute_DAP(vt[i], AP); // Compute DLO compute_DLO(vt[i], vo); // normalize DAP vt[i]->score.DAPnorm = max(0.0, (1 - (vt[i]->score.DAP) / maximum_admissible_to_DAP)); // normalize ADAP vt[i]->score.ADAPnorm = max(0.0, (1 - (vt[i]->score.ADAP / (M_PI)))); // normalize DLO vt[i]->score.DLOnorm = (vt[i]->score.DLO) / maximum_admissible_to_DLO; } // compute overall score for each traj for (size_t i = 0; i < vt.size(); ++i) { compute_global_traj_score(vt[i]); } compute_chosen_traj(); return SUCCESS; } /** * @brief Compute the distance to application point * @param trajectory * @param AP * @return t_func_output */ t_func_output c_manage_trajectory::compute_DAP(c_trajectoryPtr& trajectory, t_desired_coordinates& AP) { trajectory->score.DAP = 10e6; trajectory->closest_node = -1; for (size_t i = 0; i < trajectory->x.size(); ++i) { double DAP_prev = sqrt(pow(trajectory->x[i] - AP.x, 2) + pow(trajectory->y[i] - AP.y, 2)); if (DAP_prev < trajectory->score.DAP) { trajectory->score.DAP = DAP_prev; trajectory->closest_node = i; } } if (trajectory->closest_node != -1) { trajectory->score.ADAP = compute_ADAP(trajectory, AP, trajectory->closest_node); return SUCCESS; } else { return FAILURE; } } /** * @brief Compute the angular difference * @param trajectory * @param AP * @param i * @return double */ double c_manage_trajectory::compute_ADAP(c_trajectoryPtr& trajectory, t_desired_coordinates& AP, int i) { double adap = abs(trajectory->theta[i] - AP.theta); if (adap > M_PI) adap = 2 * M_PI - adap; return adap; } /** * @brief Draw some informations about trajectories * @param trajectory_planner * @param marker_vec * @param marker_count * @param z_high * @param value * @param normalized_value * @param string_init */ void c_manage_trajectory::draw_on_node(c_trajectoryPtr& trajectory, std::vector<visualization_msgs::Marker>* marker_vec, int* marker_count, double z_high, double value, double normalized_value, string string_init) { // Create a marker visualization_msgs::Marker marker; std_msgs::ColorRGBA color; // ________________________________ //| | //| text nodes | //|________________________________| // Points marker to t nodes marker.header.frame_id = "/vehicle_odometry"; marker.header.stamp = ros::Time::now(); marker.ns = "info"; marker.action = visualization_msgs::Marker::ADD; marker.type = visualization_msgs::Marker::TEXT_VIEW_FACING; marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; marker.scale.z = 0.6; marker.color.r = 0.039; marker.color.g = 0.207; marker.color.b = 0.619; marker.color.a = 1.0; marker.id = (*marker_count)++; marker.pose.position.x = trajectory->x[trajectory->x.size() - 1] + (_VEHICLE_LENGHT_FRONT_ + (_VEHICLE_LENGHT_FRONT_ + _VEHICLE_LENGHT_BACK_) / 2 - _VEHICLE_LENGHT_BACK_) * cos(trajectory->theta[trajectory->theta.size() - 1]); marker.pose.position.y = trajectory->y[trajectory->y.size() - 1] + (_VEHICLE_LENGHT_FRONT_ + (_VEHICLE_LENGHT_FRONT_ + _VEHICLE_LENGHT_BACK_) / 2 - _VEHICLE_LENGHT_BACK_) * sin(trajectory->theta[trajectory->theta.size() - 1]); marker.pose.position.z = z_high; marker.text = string_init + str(boost::format("%.2f") % normalized_value); // string_init + str(boost::format("%.2f") % value) + " (" + str(boost::format("%.2f") % normalized_value) + ")"; marker_vec->push_back(marker); }
31.058493
120
0.615697
[ "geometry", "vector" ]
24f6c3da40dfeadbdbf24330c1a9e3b85f9f4fa9
13,025
cxx
C++
smtk/mesh/testing/cxx/UnitTestModelToMesh3D.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
40
2015-02-21T19:55:54.000Z
2022-01-06T13:13:05.000Z
smtk/mesh/testing/cxx/UnitTestModelToMesh3D.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
127
2015-01-15T20:55:45.000Z
2021-08-19T17:34:15.000Z
smtk/mesh/testing/cxx/UnitTestModelToMesh3D.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
27
2015-03-04T14:17:51.000Z
2021-12-23T01:05:42.000Z
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/io/ModelToMesh.h" #include "smtk/io/WriteMesh.h" #include "smtk/mesh/core/Resource.h" #include "smtk/model/EntityIterator.h" #include "smtk/model/Resource.h" #include "smtk/model/Volume.h" #include "smtk/mesh/testing/cxx/helpers.h" #include "smtk/model/testing/cxx/helpers.h" #include <sstream> namespace { class CountCells : public smtk::mesh::CellForEach { //keep the range of points we have seen so we can verify that we //seen all the cells that we expect to be given smtk::mesh::HandleRange pointsSeen; //keep a physical count of number of cells so that we can verify we //don't iterate over a cell more than once int numCellsVisited{ 0 }; //total number of points seen, relates to the total size of the connectivity //array for this cellset int numPointsSeen{ 0 }; public: CountCells() = default; void forCell(const smtk::mesh::Handle& cellId, smtk::mesh::CellType cellType, int numPts) override { (void)cellId; (void)cellType; this->numCellsVisited++; this->numPointsSeen += numPts; this->pointsSeen.insert( smtk::mesh::HandleInterval(*this->pointIds(), *(this->pointIds() + numPts - 1))); } int numberOCellsVisited() const { return numCellsVisited; } int numberOPointsSeen() const { return numPointsSeen; } smtk::mesh::HandleRange points() const { return pointsSeen; } }; std::size_t numTetsInModel = 4; void create_simple_model(smtk::model::ResourcePtr resource) { using namespace smtk::model::testing; smtk::model::SessionPtr session = smtk::model::Session::create(); smtk::model::SessionRef sess(resource, session); smtk::model::Model model = resource->addModel(); for (std::size_t i = 0; i < numTetsInModel; ++i) { smtk::common::UUIDArray uids = createTet(resource); model.addCell(smtk::model::Volume(resource, uids[21])); } model.setSession(sess); resource->assignDefaultNames(); } void verify_empty_model() { smtk::model::ResourcePtr modelResource = smtk::model::Resource::create(); smtk::io::ModelToMesh convert; smtk::mesh::ResourcePtr mr = convert(modelResource); test(!mr, "mesh resource should be invalid for an empty model"); } void verify_model_association() { smtk::model::ResourcePtr modelResource = smtk::model::Resource::create(); create_simple_model(modelResource); smtk::io::ModelToMesh convert; smtk::mesh::ResourcePtr mr = convert(modelResource); //we need to verify that the mesh resource is now has an associated model test(mr->hasAssociations(), "mesh resource should have associations"); test( (mr->associatedModel() != smtk::common::UUID()), "mesh resource should be associated to a real model"); test((mr->isAssociatedToModel()), "mesh resource should be associated to a real model"); test(mr->isModified(), "A mesh created in memory with no file is considered modified"); //verify the MODEL_ENTITY is correct smtk::model::EntityRefs currentModels = modelResource->entitiesMatchingFlagsAs<smtk::model::EntityRefs>(smtk::model::MODEL_ENTITY); if (!currentModels.empty()) { //presuming only a single model in the model resource test( (mr->associatedModel() == currentModels.begin()->entity()), "mesh resource associated model should match model resource"); } } template<int Dim> void testFindAssociations( smtk::mesh::ResourcePtr mr, smtk::model::EntityIterator& it, std::size_t correct) { std::size_t numNonEmpty = 0; numNonEmpty = 0; for (it.begin(); !it.isAtEnd(); ++it) { smtk::mesh::MeshSet entMesh = mr->findAssociatedMeshes(*it, static_cast<smtk::mesh::DimensionType>(Dim)); if (entMesh.size()) { ++numNonEmpty; std::cout << " " << it->entity().toString() << " " << entMesh.size() << " sets " << entMesh.cells().size() << " cells" << " " << it->flagSummary(0) << "\n"; } /* test( (tess && tess->begin() != tess->end() && entMesh.size()) || ((!tess || tess->begin() == tess->end()) && !entMesh.size()), "Model and mesh do not agree."); */ } std::ostringstream msg; msg << "Expected " << (correct ? 1 : 0) << " non-empty meshset of dimension " << Dim << " per test tetrahedron."; test(numNonEmpty == correct, msg.str()); } template<> void testFindAssociations<-1>( smtk::mesh::ResourcePtr mr, smtk::model::EntityIterator& it, std::size_t correct) { std::size_t numNonEmpty = 0; for (it.begin(); !it.isAtEnd(); ++it) { smtk::mesh::MeshSet entMesh = mr->findAssociatedMeshes(*it); const smtk::model::Tessellation* tess = it->hasTessellation(); if (entMesh.size()) std::cout << " " << it->entity().toString() << " " << entMesh.size() << " sets " << entMesh.cells().size() << " cells" << " " << it->flagSummary(0) << "\n"; /* */ test( (tess && tess->begin() != tess->end() && entMesh.size()) || ((!tess || tess->begin() == tess->end()) && !entMesh.size()), "Model and mesh do not agree."); if (entMesh.size()) ++numNonEmpty; } test(numNonEmpty == correct, "Expected a non-empty meshset per test tetrahedron."); } template<int Dim> void testFindAssociationsByRef( smtk::mesh::ResourcePtr mr, smtk::model::EntityIterator& it, std::size_t correct) { smtk::mesh::MeshSet entMesh = mr->findAssociatedMeshes(it, static_cast<smtk::mesh::DimensionType>(Dim)); smtk::mesh::CellSet entCells = mr->findAssociatedCells(it, static_cast<smtk::mesh::DimensionType>(Dim)); test(entMesh.cells() == entCells, "Expected mesh cellset to be the same as queried cellset."); std::ostringstream msg; msg << "Expected " << !entMesh.is_empty() << " non-empty meshset of dimension " << Dim << " for all tetrahedra."; test(entMesh.size() == correct, msg.str()); } template<> void testFindAssociationsByRef<-1>( smtk::mesh::ResourcePtr mr, smtk::model::EntityIterator& it, std::size_t correct) { smtk::mesh::MeshSet entMesh = mr->findAssociatedMeshes(it); smtk::mesh::CellSet entCells = mr->findAssociatedCells(it); smtk::mesh::TypeSet entTypes = mr->findAssociatedTypes(it); const smtk::model::Tessellation* tess = it->hasTessellation(); (void)tess; test(entMesh.cells() == entCells, "Expected mesh cellset to be the same as queried cellset."); test(entMesh.types() == entTypes, "Expected mesh typeset to be the same as queried typeset."); test(entMesh.size() == correct, "Expected a non-empty meshset for all tetrahedra."); } void verify_cell_conversion() { smtk::model::ResourcePtr modelResource = smtk::model::Resource::create(); create_simple_model(modelResource); smtk::io::ModelToMesh convert; smtk::mesh::ResourcePtr mr = convert(modelResource); test(mr->isValid(), "mesh resource should be valid"); test(mr->numberOfMeshes() == numTetsInModel, "mesh resource should have a mesh per tet"); //confirm that we have the proper number of volume cells smtk::mesh::CellSet tri_cells = mr->cells(smtk::mesh::Dims2); test(tri_cells.size() == (numTetsInModel * 10)); smtk::mesh::CellSet edge_cells = mr->cells(smtk::mesh::Dims1); test(edge_cells.size() == 0); smtk::mesh::CellSet vert_cells = mr->cells(smtk::mesh::Dims0); test(vert_cells.size() == 0); // verify that we get a non-empty mesh set association back for some cells smtk::model::EntityIterator it; smtk::model::EntityRefs models = modelResource->entitiesMatchingFlagsAs<smtk::model::EntityRefs>(smtk::model::MODEL_ENTITY); it.traverse(models.begin(), models.end(), smtk::model::ITERATE_MODELS); std::cout << "All associations:\n"; testFindAssociations<-1>(mr, it, numTetsInModel); std::cout << "Dim 0 associations:\n"; testFindAssociations<0>(mr, it, 0); std::cout << "Dim 1 associations:\n"; testFindAssociations<1>(mr, it, 0); std::cout << "Dim 2 associations:\n"; testFindAssociations<2>(mr, it, numTetsInModel); std::cout << "Dim 3 associations:\n"; testFindAssociations<3>(mr, it, 0); { it.traverse(models.begin(), models.end(), smtk::model::ITERATE_MODELS); std::cout << "All associations:\n"; testFindAssociationsByRef<-1>(mr, it, numTetsInModel); std::cout << "Dim 0 associations:\n"; testFindAssociationsByRef<0>(mr, it, 0); std::cout << "Dim 1 associations:\n"; testFindAssociationsByRef<1>(mr, it, 0); std::cout << "Dim 2 associations:\n"; testFindAssociationsByRef<2>(mr, it, numTetsInModel); std::cout << "Dim 3 associations:\n"; testFindAssociationsByRef<3>(mr, it, 0); } { std::cout << "Querying an empty mesh resource:\n"; it.traverse(models.begin(), models.end(), smtk::model::ITERATE_MODELS); std::cout << "All associations:\n"; smtk::mesh::ResourcePtr emptyResource = smtk::mesh::Resource::create(); testFindAssociationsByRef<-1>(emptyResource, it, 0); } std::cout << "Find type info of first cell:\n"; if (!models.empty()) { smtk::model::CellEntities cells = models.begin()->as<smtk::model::Model>().cells(); if (!cells.empty()) { smtk::mesh::TypeSet meshedTypes = mr->findAssociatedTypes(cells[0]); smtk::mesh::CellTypes cellTypes = meshedTypes.cellTypes(); //the model we have been given only has triangles, and while those //triangles has physical coordinates we don't model each of those coordinates //as an explicit cell vertex. That is why we only expect to find triangle //cells in the following check std::cout << " Cell " << cells[0].name() << "\n"; static bool expected[smtk::mesh::CellType_MAX] = { false, false, true, false, false, false, false, false, false }; for (int i = 0; i < smtk::mesh::CellType_MAX; ++i) { smtk::mesh::CellType ct = static_cast<smtk::mesh::CellType>(i); std::cout << " Has mesh items of type " << cellTypeSummary(ct) << "? " << (cellTypes[ct] ? "Y" : "N") << "\n"; if (cellTypes[ct] != expected[ct]) { std::ostringstream msg; msg << (expected[i] ? "Expected" : "Did not expect") << " this cell to have mesh " << cellTypeSummary(ct, 1); std::cout << " " << msg.str() << "\n"; test(cellTypes[ct] == expected[ct], msg.str()); } } } } std::cout << "Entity lookup via reverse classification\n"; smtk::model::EntityRefArray ents; bool entsAreValid = mr->meshes().modelEntities(ents); test(entsAreValid, "Expected valid entity refs."); test(ents.size() == numTetsInModel, "Expected 1 tetrahedron per model."); for (smtk::model::EntityRefArray::iterator eit = ents.begin(); eit != ents.end(); ++eit) { std::cout << " " << eit->name() << " (" << eit->flagSummary(0) << ")\n"; } } void verify_vertex_conversion() { smtk::model::ResourcePtr modelResource = smtk::model::Resource::create(); create_simple_model(modelResource); smtk::io::ModelToMesh convert; smtk::mesh::ResourcePtr mr = convert(modelResource); test(mr->isValid(), "mesh resource should be valid"); test(mr->numberOfMeshes() == numTetsInModel, "mesh resource should have a mesh per tet"); smtk::mesh::PointSet points = mr->points(); test(points.size() == 7, "After merging of identical points we should have 7"); } void verify_cell_have_points() { smtk::model::ResourcePtr modelResource = smtk::model::Resource::create(); create_simple_model(modelResource); smtk::io::ModelToMesh convert; smtk::mesh::ResourcePtr mr = convert(modelResource); smtk::mesh::MeshSet triMeshes = mr->meshes(smtk::mesh::Dims2); CountCells functor; smtk::mesh::for_each(triMeshes.cells(), functor); test( functor.numberOCellsVisited() == static_cast<int>(triMeshes.cells().size()), "Mismatch in number of cells visited."); test( functor.numberOPointsSeen() == static_cast<int>(triMeshes.pointConnectivity().size()), "Mismatch in number of points seen."); //currently no two cells are sharing vertices. test( functor.numberOCellsVisited() == static_cast<int>(numTetsInModel * 10), "Number of cells not proportional to number of tets."); test( functor.numberOPointsSeen() == static_cast<int>(numTetsInModel * 10 * 3), "Number of points not proportional to number of tets."); } } // namespace int UnitTestModelToMesh3D(int /*unused*/, char** const /*unused*/) { verify_empty_model(); verify_model_association(); verify_cell_conversion(); verify_vertex_conversion(); verify_cell_have_points(); return 0; }
35.013441
100
0.653359
[ "mesh", "model" ]
24fc66112695247e83473c48ceb62a5b56f9c24c
7,169
cpp
C++
week-08/clues/src/main.cpp
tehwalris/algolab
489e0f6dd137336fa32b8002fc6eed8a7d35d87a
[ "MIT" ]
1
2021-01-17T08:21:32.000Z
2021-01-17T08:21:32.000Z
week-08/clues/src/main.cpp
tehwalris/algolab
489e0f6dd137336fa32b8002fc6eed8a7d35d87a
[ "MIT" ]
null
null
null
week-08/clues/src/main.cpp
tehwalris/algolab
489e0f6dd137336fa32b8002fc6eed8a7d35d87a
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> #include <vector> #include <deque> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Delaunay_triangulation_2.h> #include <CGAL/Triangulation_data_structure_2.h> #include <CGAL/Triangulation_vertex_base_with_info_2.h> #include <CGAL/Triangulation_face_base_2.h> #include <boost/graph/adjacency_list.hpp> const int debug_level = 0; #define DEBUG(min_level, x) \ if (debug_level >= min_level) \ { \ std::cerr << x << std::endl; \ } typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Triangulation_vertex_base_with_info_2<int, K> TVB; typedef CGAL::Triangulation_face_base_2<K> TFB; typedef CGAL::Triangulation_data_structure_2<TVB, TFB> TriangulationDataStructure; typedef CGAL::Delaunay_triangulation_2<K, TriangulationDataStructure> Triangulation; typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph; K::Point_2 read_point() { int x, y; std::cin >> x >> y; assert(abs(x) < (1 << 24) && abs(y) < (1 << 24)); return K::Point_2(x, y); } inline Triangulation::Vertex_handle vertex_from_edge(Triangulation::Edge &edge, int i) { assert(i == 0 || i == 1); return edge.first->vertex((edge.second + 1 + i) % 3); } inline Triangulation::Vertex_handle other_vertex_from_edge(Triangulation::Edge &edge, Triangulation::Vertex_handle &v) { auto vertex_a = vertex_from_edge(edge, 0); auto vertex_b = vertex_from_edge(edge, 1); if (vertex_a == v) { return vertex_b; } else if (vertex_b == v) { return vertex_a; } assert(false); __builtin_unreachable(); } struct NetworkAnalysis { NetworkAnalysis(int n) : valid(false), component_map(n, -1){}; bool valid; std::vector<int> component_map; }; NetworkAnalysis analyze_network(std::vector<std::pair<K::Point_2, int>> radio_stations, Triangulation &all_stations_triangulation, std::function<bool(double)> is_close_enough) { const int n = radio_stations.size(); NetworkAnalysis network_analysis(n); std::vector<Triangulation::Vertex_handle> all_stations_triangulation_handles(n); for (auto it = all_stations_triangulation.finite_vertices_begin(); it != all_stations_triangulation.finite_vertices_end(); it++) { all_stations_triangulation_handles.at(it->info()) = it; } std::deque<std::pair<int, int>> queue; std::vector<int> color_by_station(n, -1); int next_connected_component = 0; for (int queue_starter = 0; queue_starter < n; queue_starter++) { if (network_analysis.component_map.at(queue_starter) >= 0) { continue; } queue.push_back(std::make_pair(queue_starter, 0)); const int this_connected_component = next_connected_component++; network_analysis.component_map.at(queue_starter) = this_connected_component; while (!queue.empty()) { int prev_index = queue.front().first; int prev_color = queue.front().second; queue.pop_front(); K::Point_2 &prev_point = radio_stations.at(prev_index).first; assert(color_by_station.at(prev_index) == -1); color_by_station.at(prev_index) = prev_color; auto &prev_vertex = all_stations_triangulation_handles.at(prev_index); Triangulation::Edge_circulator c = all_stations_triangulation.incident_edges(prev_vertex); do { if (all_stations_triangulation.is_infinite(c)) { continue; } auto next_vertex = other_vertex_from_edge(*c, prev_vertex); int next_index = next_vertex->info(); K::Point_2 &next_point = next_vertex->point(); int next_color = 1 - prev_color; if (network_analysis.component_map.at(next_index) == -1 && is_close_enough(CGAL::squared_distance(prev_point, next_point))) { network_analysis.component_map.at(next_index) = this_connected_component; queue.push_front(std::make_pair(next_index, next_color)); } } while (++c != all_stations_triangulation.incident_edges(prev_vertex)); } } assert(*std::min_element(network_analysis.component_map.begin(), network_analysis.component_map.end()) >= 0); std::vector<std::vector<K::Point_2>> point_vectors_by_color(2); for (int i = 0; i < n; i++) { int color = color_by_station.at(i); point_vectors_by_color.at(color).push_back(radio_stations.at(i).first); } for (auto &points_this_color : point_vectors_by_color) { Triangulation color_triangulation; color_triangulation.insert(points_this_color.begin(), points_this_color.end()); for (auto it = color_triangulation.finite_edges_begin(); it != color_triangulation.finite_edges_end(); it++) { if (is_close_enough(color_triangulation.segment(it).squared_length())) { return network_analysis; } } } network_analysis.valid = true; return network_analysis; } void testcase() { int n, m, r; std::cin >> n >> m >> r; assert(n >= 1 && n <= 9e4 && m >= 1 && m <= 9e4 && r > 0 && r < (1 << 24)); const double r_squared = pow(double(r), 2); const auto is_close_enough = [r_squared](double sqlen) { return sqlen <= r_squared; }; std::vector<std::pair<K::Point_2, int>> radio_stations; for (int i = 0; i < n; i++) { radio_stations.push_back(std::make_pair(read_point(), i)); } std::vector<std::pair<K::Point_2, K::Point_2>> clues; for (int i = 0; i < m; i++) { auto p1 = read_point(); auto p2 = read_point(); clues.push_back(std::make_pair(p1, p2)); } Triangulation all_stations_triangulation; all_stations_triangulation.insert(radio_stations.begin(), radio_stations.end()); NetworkAnalysis network_analysis = analyze_network(radio_stations, all_stations_triangulation, is_close_enough); DEBUG(2, "network_analysis.valid " << network_analysis.valid); const auto network_component_from_radio_set = [&is_close_enough, &all_stations_triangulation, &network_analysis](K::Point_2 &radio_set) -> int { auto nearest_station = all_stations_triangulation.nearest_vertex(radio_set); double set_station_sq_dist = CGAL::squared_distance(radio_set, nearest_station->point()); if (!is_close_enough(set_station_sq_dist)) { return -1; } return network_analysis.component_map.at(nearest_station->info()); }; std::vector<bool> can_transmit_by_clue(m, false); if (network_analysis.valid) { for (int i = 0; i < m; i++) { DEBUG(3, "clue " << i); auto &clue = clues.at(i); if (is_close_enough(CGAL::squared_distance(clue.first, clue.second))) { can_transmit_by_clue.at(i) = true; } else { int first_component = network_component_from_radio_set(clue.first); if (first_component >= 0 && first_component == network_component_from_radio_set(clue.second)) { can_transmit_by_clue.at(i) = true; } } } } for (bool can_transmit : can_transmit_by_clue) { std::cout << (can_transmit ? "y" : "n"); } std::cout << "\n"; } int main() { std::ios_base::sync_with_stdio(false); int t; std::cin >> t; for (int i = 0; i < t; i++) { testcase(); } return 0; }
31.442982
175
0.68587
[ "vector" ]
700adfbb382e1448850cc50ba01fc7a32dbe2231
1,944
hpp
C++
bahamut/tools/script-encoder.hpp
higan-emu/bahamut-lagoon-translation-kit
6f08de5b92b597c0b9ecebd485cc975b99acfc13
[ "0BSD" ]
2
2021-08-15T04:10:10.000Z
2021-08-15T20:14:13.000Z
bahamut/tools/script-encoder.hpp
higan-emu/bahamut-lagoon-translation-kit
6f08de5b92b597c0b9ecebd485cc975b99acfc13
[ "0BSD" ]
1
2022-02-16T02:46:39.000Z
2022-02-16T04:30:29.000Z
bahamut/tools/script-encoder.hpp
higan-emu/bahamut-lagoon-translation-kit
6f08de5b92b597c0b9ecebd485cc975b99acfc13
[ "0BSD" ]
1
2021-12-25T11:34:57.000Z
2021-12-25T11:34:57.000Z
#pragma once #include "text-encoder.hpp" struct ScriptEncoder : TextEncoder { using TextEncoder::load; auto load() -> void; auto lineWidth(const string& text, u32 index = 0) -> maybe<u32>; }; auto ScriptEncoder::load() -> void { FontEncoder::load("font-large", 8, 11); } //enhanced version of TextEncoder::lineWidth() supporting additional commands. //returns the number of pixels required to render a line of text. //returns nothing if the line width cannot be determined or is ambiguous. auto ScriptEncoder::lineWidth(const string& text, u32 index) -> maybe<u32> { u32 width = 0; TextEncoder::push(); while(true) { auto read = TextEncoder::read(text, index); if(read.isTerminal()) break; if(read.isLineFeed()) break; if(read.isCommand()) { if(read.command == "skip") { width += read.argument.natural(); continue; } if(read.command == "option") { width += 12; continue; } if(read.command == "style") { if(read.argument == "normal") { TextEncoder::setStyle(Style::Normal); continue; } if(read.argument == "italic") { TextEncoder::setStyle(Style::Italic); continue; } } if(read.command == "color") continue; if(read.command == "pause") continue; if(read.command == "wait" ) continue; if(auto index = TextEncoder::name(read.command)) { if(*index <= 9) { //dynamic name; assume the longest possible width width += 66; } else if(auto nameWidth = TextEncoder::lineWidth(read.command)) { //static name; fixed width width += *nameWidth; } continue; } return TextEncoder::pop(), nothing; //other tags cannot be used with {center} } if(read.isCharacter()) { width -= read.kerning; width += read.width; continue; } return TextEncoder::pop(), nothing; } return TextEncoder::pop(), width; }
31.354839
89
0.610597
[ "render" ]
700be3ebb574c0214c2933b1bec22e208b92bf12
620
hpp
C++
source/ashes/renderer/D3D11Renderer/Command/Commands/D3D11ScissorCommand.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
source/ashes/renderer/D3D11Renderer/Command/Commands/D3D11ScissorCommand.hpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
source/ashes/renderer/D3D11Renderer/Command/Commands/D3D11ScissorCommand.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
/* This file belongs to Ashes. See LICENSE file in root folder */ #pragma once #include "renderer/D3D11Renderer/Command/Commands/D3D11CommandBase.hpp" namespace ashes::d3d11 { /** *\brief * Commande d'application d'un scissor. */ class ScissorCommand : public CommandBase { public: /** *\brief * Constructeur. *\param[in] scissor * Le scissor. */ ScissorCommand( VkDevice device , uint32_t first , ArrayView< VkRect2D const > const & scissors ); void apply( Context const & context )const override; CommandPtr clone()const override; private: std::vector< RECT > m_scissors; }; }
17.222222
71
0.695161
[ "vector" ]
700f2355829272cb8f0f83545d983f2b1063d5ce
1,441
cpp
C++
datasets/github_cpp_10/8/52.cpp
yijunyu/demo-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
1
2019-05-03T19:27:45.000Z
2019-05-03T19:27:45.000Z
datasets/github_cpp_10/8/52.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
datasets/github_cpp_10/8/52.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <climits> #include <stdio.h> #include <queue> #include <set> #include <list> #include <cmath> #include <assert.h> #include <bitset> #include <map> #include <unordered_map> #include <unordered_set> #include <iomanip> #define mp make_pair #define pb push_back #define x first #define y second #define print(arr) for (auto it = arr.begin(); it != arr.end(); ++it) cout << *it << " "; cout << "\n"; typedef long long int ll; typedef long double ld; typedef std::pair <int, int> ii; typedef std::vector <int> vi; typedef std::vector <ll> vll; const int INF = int(1e9); const ll INF64 = ll(1e18); const ld EPS = 1e-9, PI = 3.1415926535897932384626433832795; using namespace std; int main() { int N, M, a, b; bitset <20> viz; scanf("%d %d", &N, &M); vector <vi> graph(N+1); vi topo, indegree(N+1, 0); for (int i = 0; i < M; i++) { scanf("%d %d", &a, &b); graph[a].pb(b); indegree[b] += 1; } queue <int> Q; for (int u = 1; u <= N; u++) { if (indegree[u] == 0) { Q.push(u); viz[u] = true; } } while (!Q.empty()) { int u = Q.front(); Q.pop(); topo.pb(u); for (int v : graph[u]) { if (!viz[v]) { indegree[v]--; viz[v] = true; Q.push(v); } } } print(topo); }
21.833333
103
0.523248
[ "vector" ]
70143c90116eb28bdfcfe4b41b297754d3b6db99
40,249
cpp
C++
RenderSystems/Vulkan/src/OgreVulkanQueue.cpp
dawlane/ogre
7bae21738c99b117ef2eab3fcb1412891b8c2025
[ "MIT" ]
1
2019-10-29T23:36:28.000Z
2019-10-29T23:36:28.000Z
RenderSystems/Vulkan/src/OgreVulkanQueue.cpp
dawlane/ogre
7bae21738c99b117ef2eab3fcb1412891b8c2025
[ "MIT" ]
null
null
null
RenderSystems/Vulkan/src/OgreVulkanQueue.cpp
dawlane/ogre
7bae21738c99b117ef2eab3fcb1412891b8c2025
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-present Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreVulkanQueue.h" #include "OgreVulkanDevice.h" #include "OgreVulkanMappings.h" #include "OgreVulkanRenderSystem.h" #include "OgreVulkanTextureGpu.h" #include "OgreVulkanWindow.h" #include "OgreException.h" #include "OgrePixelFormat.h" #include "OgreStringConverter.h" #include "OgreVulkanUtils.h" #include "OgreVulkanDescriptorPool.h" #define TODO_findRealPresentQueue #define TODO_we_assume_has_stencil namespace Ogre { // Mask away read flags from srcAccessMask static const uint32 c_srcValidAccessFlags = 0xFFFFFFFF ^ ( VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_HOST_READ_BIT | VK_ACCESS_MEMORY_READ_BIT ); VulkanQueue::VulkanQueue() : mDevice( 0 ), mFamily( NumQueueFamilies ), mFamilyIdx( 0u ), mQueueIdx( 0u ), mQueue( 0 ), mCurrentCmdBuffer( 0 ), mOwnerDevice( 0 ), mNumFramesInFlight( 3 ), mCurrentFrameIdx( 0 ), mRenderSystem( 0 ), mCurrentFence( 0 ), mEncoderState( EncoderClosed ), mCopyEndReadSrcBufferFlags( 0 ), mCopyEndReadDstBufferFlags( 0 ), mCopyEndReadDstTextureFlags( 0 ), mCopyStartWriteSrcBufferFlags( 0 ) { } //------------------------------------------------------------------------- VulkanQueue::~VulkanQueue() { destroy(); } //------------------------------------------------------------------------- void VulkanQueue::setQueueData( VulkanDevice *owner, QueueFamily family, uint32 familyIdx, uint32 queueIdx ) { mOwnerDevice = owner; mFamily = family; mFamilyIdx = familyIdx; mQueueIdx = queueIdx; } //------------------------------------------------------------------------- void VulkanQueue::init( VkDevice device, VkQueue queue, VulkanRenderSystem *renderSystem ) { mDevice = device; mQueue = queue; mRenderSystem = renderSystem; mPerFrameData.resize( mNumFramesInFlight ); VkCommandPoolCreateInfo cmdPoolCreateInfo = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cmdPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; cmdPoolCreateInfo.queueFamilyIndex = mFamilyIdx; VkCommandBufferAllocateInfo allocateInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocateInfo.commandBufferCount = 1u; VkFenceCreateInfo fenceCi = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; fenceCi.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (auto& fd : mPerFrameData) { OGRE_VK_CHECK(vkCreateCommandPool(mDevice, &cmdPoolCreateInfo, 0, &fd.mCommandPool)); allocateInfo.commandPool = fd.mCommandPool; OGRE_VK_CHECK(vkAllocateCommandBuffers( mDevice, &allocateInfo, &fd.mCommandBuffer )); OGRE_VK_CHECK(vkCreateFence(mDevice, &fenceCi, 0, &fd.mProtectingFence)); } newCommandBuffer(); } void VulkanQueue::destroy() { if( mDevice ) { vkDeviceWaitIdle( mDevice ); for(size_t i = 0; i < mPerFrameData.size(); ++i) { _waitOnFrame(i); } for(auto& fd : mPerFrameData) { vkDestroyFence( mDevice, fd.mProtectingFence, 0 ); vkDestroyCommandPool( mDevice, fd.mCommandPool, 0 ); } mDevice = 0; } } //------------------------------------------------------------------------- void VulkanQueue::newCommandBuffer( void ) { _waitOnFrame(mCurrentFrameIdx); vkResetCommandPool(mDevice, mPerFrameData[mCurrentFrameIdx].mCommandPool, 0); mCurrentCmdBuffer = mPerFrameData[mCurrentFrameIdx].mCommandBuffer; mCurrentFence = mPerFrameData[mCurrentFrameIdx].mProtectingFence; VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer( mCurrentCmdBuffer, &beginInfo ); } //------------------------------------------------------------------------- void VulkanQueue::endCommandBuffer( void ) { if( mCurrentCmdBuffer ) { endAllEncoders(); OGRE_VK_CHECK(vkEndCommandBuffer( mCurrentCmdBuffer )); } } //------------------------------------------------------------------------- void VulkanQueue::getGraphicsEncoder( void ) { if( mEncoderState != EncoderGraphicsOpen ) { endCopyEncoder(); endComputeEncoder(); mEncoderState = EncoderGraphicsOpen; } } //------------------------------------------------------------------------- void VulkanQueue::getComputeEncoder( void ) { if( mEncoderState != EncoderComputeOpen ) { endRenderEncoder(); endCopyEncoder(); mEncoderState = EncoderComputeOpen; } } //------------------------------------------------------------------------- VkPipelineStageFlags VulkanQueue::deriveStageFromBufferAccessFlags( VkAccessFlags accessFlags ) { VkPipelineStageFlags stage = 0; if( accessFlags & VK_ACCESS_INDIRECT_COMMAND_READ_BIT ) stage |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; if( accessFlags & ( VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT ) ) { stage |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT; } if( accessFlags & ( VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if( accessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } return stage; } //------------------------------------------------------------------------- VkPipelineStageFlags VulkanQueue::deriveStageFromTextureAccessFlags( VkAccessFlags accessFlags ) { VkPipelineStageFlags stage = 0; if( accessFlags & ( VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; } if( accessFlags & ( VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; } if( accessFlags & ( VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if( accessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } if( accessFlags & VK_ACCESS_INPUT_ATTACHMENT_READ_BIT ) stage |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; return stage; } //------------------------------------------------------------------------- void VulkanQueue::insertRestoreBarrier( VulkanTextureGpu *vkTexture, const VkImageLayout newTransferLayout ) { const VkImageLayout oldLayout = vkTexture->mCurrLayout; const VkImageLayout otherTransferLayout = newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ? VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; const VkAccessFlags accessFlags = newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_TRANSFER_WRITE_BIT; if( oldLayout == newTransferLayout ) { // Nothing to do. A restore barrier has already been inserted // If the assert fails, then the texture transitioned // to this layout without us knowing OGRE_ASSERT_HIGH( std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), vkTexture ) != mImageMemBarrierPtrs.end() && "Only this class should set VK_IMAGE_LAYOUT_TRANSFER_*_OPTIMAL" ); } else if( oldLayout == otherTransferLayout ) { // A restore barrier has already been inserted, but it needs modification FastArray<TextureGpu *>::iterator itor = std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), vkTexture ); // If the assert fails, then the texture transitioned // to this layout without us knowing OGRE_ASSERT_LOW( itor != mImageMemBarrierPtrs.end() && "Only this class should set VK_IMAGE_LAYOUT_TRANSFER_*_OPTIMAL" ); const size_t idx = ( size_t )( itor - mImageMemBarrierPtrs.begin() ); VkImageMemoryBarrier &imageMemBarrier = *( mImageMemBarriers.begin() + idx ); imageMemBarrier.srcAccessMask = accessFlags & c_srcValidAccessFlags; imageMemBarrier.oldLayout = newTransferLayout; } else { // First time we see this texture VkImageMemoryBarrier imageMemBarrier = vkTexture->getImageMemoryBarrier(); imageMemBarrier.srcAccessMask = accessFlags & c_srcValidAccessFlags; imageMemBarrier.dstAccessMask = VulkanMappings::get( vkTexture ); if( newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ) { // We need to block subsequent stages from writing to this texture // until we're done copying from it (but they can read) imageMemBarrier.dstAccessMask &= (VkAccessFlags)~VK_ACCESS_SHADER_READ_BIT; mCopyEndReadDstTextureFlags |= imageMemBarrier.dstAccessMask; } imageMemBarrier.oldLayout = newTransferLayout; imageMemBarrier.newLayout = vkTexture->mNextLayout; mImageMemBarriers.push_back( imageMemBarrier ); mImageMemBarrierPtrs.push_back( vkTexture ); } } //------------------------------------------------------------------------- void VulkanQueue::prepareForUpload( const BufferPacked *buffer, TextureGpu *texture ) { VkAccessFlags bufferAccessFlags = 0; if( buffer ) { BufferPackedDownloadMap::iterator it = mCopyDownloadBuffers.find( buffer ); if( it == mCopyDownloadBuffers.end() ) ;//bufferAccessFlags = VulkanMappings::get( buffer->getBufferPackedType() ); else { if( !it->second ) { // bufferAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; // We assume consecutive writes means we're writing to non-overlapping areas // Do not wait for previous transfers. bufferAccessFlags = 0; } else bufferAccessFlags = VK_ACCESS_TRANSFER_READ_BIT; } mCopyDownloadBuffers[buffer] = false; mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_WRITE_BIT; } OGRE_ASSERT_HIGH( !texture || dynamic_cast<VulkanTextureGpu *>( texture ) ); VulkanTextureGpu *vkTexture = static_cast<VulkanTextureGpu *>( texture ); VkAccessFlags texAccessFlags = 0; if( texture ) { TextureGpuDownloadMap::iterator it = mCopyDownloadTextures.find( vkTexture ); if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_UNDEFINED ) { // This texture must just have been created texAccessFlags = 0; } else if( it == mCopyDownloadTextures.end() ) { if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) { OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Texture " + vkTexture->getName() + " is already in CopySrc or CopyDst layout, externally set. Perhaps " "you need to call RenderSystem::flushTextureCopyOperations", "VulkanQueue::prepareForUpload" ); } texAccessFlags = VulkanMappings::get( texture ); } else { if( !it->second ) { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); // texAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; // We assume consecutive writes means we're writing to non-overlapping areas // Do not wait for previous transfers. texAccessFlags = 0; } else { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); texAccessFlags = VK_ACCESS_TRANSFER_READ_BIT; } } // We need to block subsequent stages from accessing this texture at all // until we're done copying into it mCopyEndReadDstTextureFlags |= VulkanMappings::get( texture ); mCopyDownloadTextures[vkTexture] = false; } // One buffer barrier is enough for all buffers. // Unless we already issued a transfer to this same buffer const bool bNeedsBufferBarrier = ( bufferAccessFlags && ( mCopyEndReadDstBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) || ( bufferAccessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ); const bool bNeedsTexTransition = vkTexture && vkTexture->mCurrLayout != VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; mCopyEndReadDstBufferFlags |= bufferAccessFlags; // Trigger the barrier if we actually have to wait. // And only if we haven't issued this barrier already if( bNeedsBufferBarrier || bNeedsTexTransition ) { VkPipelineStageFlags srcStage = 0; uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; if( bNeedsBufferBarrier ) { // GPU must stop using this buffer before we can write into it memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage |= deriveStageFromBufferAccessFlags( bufferAccessFlags ); numMemBarriers = 1u; } uint32 numImageMemBarriers = 0u; VkImageMemoryBarrier imageMemBarrier; if( bNeedsTexTransition ) { // GPU must stop using this texture before we can write into it // Also we need to do a transition imageMemBarrier = vkTexture->getImageMemoryBarrier(); imageMemBarrier.srcAccessMask = texAccessFlags & c_srcValidAccessFlags; imageMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; imageMemBarrier.oldLayout = vkTexture->mCurrLayout; imageMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; if( texAccessFlags == 0u ) { if( bufferAccessFlags == 0u ) { // Wait for nothing. We're only issuing a barrier // because of the texture transition srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; } } else { srcStage |= deriveStageFromTextureAccessFlags( texAccessFlags ); } insertRestoreBarrier( vkTexture, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); vkTexture->mCurrLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; numImageMemBarriers = 1u; } // Wait until earlier render, compute and transfers are done so we can copy what // they wrote (unless we're only here for a texture transition) vkCmdPipelineBarrier( mCurrentCmdBuffer, srcStage & mOwnerDevice->mSupportedStages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, numImageMemBarriers, &imageMemBarrier ); } } //------------------------------------------------------------------------- void VulkanQueue::prepareForDownload( const BufferPacked *buffer, VulkanTextureGpu *texture ) { VkAccessFlags bufferAccessFlags = 0; VkPipelineStageFlags srcStage = 0; // Evaluate the stages which blocks us before we can begin our transfer if( buffer ) { BufferPackedDownloadMap::iterator it = mCopyDownloadBuffers.find( buffer ); if( it == mCopyDownloadBuffers.end() ) { if( /*buffer->getBufferPackedType() == BP_TYPE_UAV*/ 0 ) { bufferAccessFlags = VK_ACCESS_SHADER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } // else //{ // If the buffer is not BT_TYPE_UAV, the GPU won't modify these buffers, // we can start downloading right away without waiting //} } else { if( !it->second ) { bufferAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } else bufferAccessFlags = 0; // Consecutive reads don't require waiting } mCopyDownloadBuffers[buffer] = true; mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_READ_BIT; } OGRE_ASSERT_HIGH( !texture || dynamic_cast<VulkanTextureGpu *>( texture ) ); VulkanTextureGpu *vkTexture = static_cast<VulkanTextureGpu *>( texture ); VkAccessFlags texAccessFlags = 0; if( texture ) { TextureGpuDownloadMap::iterator it = mCopyDownloadTextures.find( vkTexture ); if( it == mCopyDownloadTextures.end() ) { if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) { OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Texture " + vkTexture->getName() + " is already in CopySrc or CopyDst layout, externally set. Perhaps " "you need to call RenderSystem::flushTextureCopyOperations", "VulkanQueue::prepareForDownload" ); } if( texture->isUav() ) { texAccessFlags |= VK_ACCESS_SHADER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if( texture->getUsage() & TU_RENDERTARGET ) { texAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; if( !PixelUtil::isDepth( texture->getFormat() ) ) { texAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; } else { texAccessFlags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; } } } else { if( !it->second ) { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); texAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } else { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); texAccessFlags = 0; // Consecutive reads don't require waiting } } mCopyDownloadTextures[vkTexture] = true; } // One buffer barrier is enough for all buffers. // Unless we already issued a transfer to this same buffer const bool bNeedsBufferBarrier = ( bufferAccessFlags && ( mCopyStartWriteSrcBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) || ( bufferAccessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ); mCopyStartWriteSrcBufferFlags |= bufferAccessFlags; const bool bNeedsTexTransition = vkTexture && vkTexture->mCurrLayout != VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; // Trigger the barrier if we actually have to wait. // And only if we haven't issued this barrier already if( bNeedsBufferBarrier || bNeedsTexTransition ) { uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; if( bNeedsBufferBarrier ) { memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; numMemBarriers = 1u; } uint32 numImageMemBarriers = 0u; VkImageMemoryBarrier imageMemBarrier; if( bNeedsTexTransition ) { imageMemBarrier = vkTexture->getImageMemoryBarrier(); imageMemBarrier.srcAccessMask = texAccessFlags & c_srcValidAccessFlags; imageMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; imageMemBarrier.oldLayout = vkTexture->mCurrLayout; imageMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; insertRestoreBarrier( vkTexture, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); vkTexture->mCurrLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; numImageMemBarriers = 1u; if( !srcStage ) { // If we're here the texture is read-only and we only // need the barrier to perform a layout transition srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; } } // Wait until earlier render, compute and transfers are done so we can copy what // they wrote (unless we're only here for a texture transition) vkCmdPipelineBarrier( mCurrentCmdBuffer, srcStage & mOwnerDevice->mSupportedStages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, numImageMemBarriers, &imageMemBarrier ); } } //------------------------------------------------------------------------- void VulkanQueue::getCopyEncoder( const BufferPacked *buffer, VulkanTextureGpu *texture, const bool bDownload ) { OgreAssert(mEncoderState != EncoderGraphicsOpen, "interrupting RenderPass not supported"); if( mEncoderState != EncoderCopyOpen ) { endRenderEncoder(); endComputeEncoder(); mEncoderState = EncoderCopyOpen; // Submission guarantees the host write being complete, as per // khronos.org/registry/vulkan/specs/1.0/html/vkspec.html#synchronization-submission-host-writes // So no need for a barrier before the transfer // // The only exception is when writing from CPU to GPU when a command that uses that region // has already been submitted via vkQueueSubmit (and you're using vkCmdWaitEvents to wait // for the CPU to write the data and give ok to the GPU). // Which Ogre does not do (too complex to get right). } if( bDownload ) prepareForDownload( buffer, texture ); else prepareForUpload( buffer, texture ); } //------------------------------------------------------------------------- void VulkanQueue::getCopyEncoderV1Buffer( const bool bDownload ) { OgreAssert(mEncoderState != EncoderGraphicsOpen, "interrupting RenderPass not supported"); if( mEncoderState != EncoderCopyOpen ) { endRenderEncoder(); endComputeEncoder(); mEncoderState = EncoderCopyOpen; } if( !bDownload ) { // V1 buffers are only used for vertex and index buffers // We assume v1 buffers don't try to write then read (or read then write) in a row const VkAccessFlags bufferAccessFlags = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDEX_READ_BIT; if( ( mCopyEndReadDstBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) { uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; numMemBarriers = 1u; // GPU must stop using this buffer before we can write into it vkCmdPipelineBarrier( mCurrentCmdBuffer, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, 0u, 0 ); } mCopyEndReadDstBufferFlags |= bufferAccessFlags; mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_WRITE_BIT; } else { mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_READ_BIT; } } //------------------------------------------------------------------------- void VulkanQueue::endCopyEncoder( void ) { if( mEncoderState != EncoderCopyOpen ) return; if( mCopyEndReadDstBufferFlags || !mImageMemBarrierPtrs.empty() ) { VkPipelineStageFlags dstStage = 0; uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; if( mCopyEndReadDstBufferFlags ) { memBarrier.srcAccessMask = mCopyEndReadSrcBufferFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = mCopyEndReadDstBufferFlags; // Evaluate the stages we can unblock when our transfers are done dstStage |= deriveStageFromBufferAccessFlags( memBarrier.dstAccessMask ); numMemBarriers = 1u; } dstStage |= deriveStageFromTextureAccessFlags( mCopyEndReadDstTextureFlags ); if( dstStage == 0u ) { // Nothing needs to wait for us. Can happen if all we're // doing is copying from read-only textures (rare) dstStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; #if OGRE_DEBUG_MODE FastArray<TextureGpu *>::const_iterator itor = mImageMemBarrierPtrs.begin(); FastArray<TextureGpu *>::const_iterator endt = mImageMemBarrierPtrs.end(); while( itor != endt ) { OgreAssert( (( *itor )->getUsage() & TU_RENDERTARGET) == 0/*&& !( *itor )->isUav()*/, "endCopyEncoder says nothing will wait on this texture(s) but " "we don't know if a subsequent stage will write to it" ); ++itor; } #endif } // Wait until earlier render, compute and transfers are done // Block render, compute and transfers until we're done vkCmdPipelineBarrier( mCurrentCmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, dstStage & mOwnerDevice->mSupportedStages, 0, numMemBarriers, &memBarrier, 0u, 0, static_cast<uint32_t>( mImageMemBarriers.size() ), mImageMemBarriers.data() ); mImageMemBarriers.clear(); mImageMemBarrierPtrs.clear(); TextureGpuDownloadMap::const_iterator itor = mCopyDownloadTextures.begin(); TextureGpuDownloadMap::const_iterator endt = mCopyDownloadTextures.end(); while( itor != endt ) { itor->first->mCurrLayout = itor->first->mNextLayout; ++itor; } } mCopyEndReadSrcBufferFlags = 0; mCopyEndReadDstBufferFlags = 0; mCopyEndReadDstTextureFlags = 0; mCopyStartWriteSrcBufferFlags = 0; mCopyDownloadTextures.clear(); mCopyDownloadBuffers.clear(); mEncoderState = EncoderClosed; } //------------------------------------------------------------------------- void VulkanQueue::endRenderEncoder( const bool endRenderPassDesc ) { if( mEncoderState != EncoderGraphicsOpen ) return; mRenderSystem->_notifyActiveEncoderEnded(); if( endRenderPassDesc ) mRenderSystem->endRenderPassDescriptor(); mEncoderState = EncoderClosed; } //------------------------------------------------------------------------- void VulkanQueue::endComputeEncoder( void ) { if( mEncoderState != EncoderComputeOpen ) return; mEncoderState = EncoderClosed; mRenderSystem->_notifyActiveComputeEnded(); } //------------------------------------------------------------------------- void VulkanQueue::endAllEncoders( const bool endRenderPassDesc ) { endCopyEncoder(); endRenderEncoder( endRenderPassDesc ); endComputeEncoder(); } //------------------------------------------------------------------------- void VulkanQueue::notifyTextureDestroyed( VulkanTextureGpu *texture ) { if( mEncoderState == EncoderCopyOpen ) { bool needsToFlush = false; TextureGpuDownloadMap::const_iterator itor = mCopyDownloadTextures.find( texture ); if( itor != mCopyDownloadTextures.end() ) needsToFlush = true; else { FastArray<TextureGpu *>::const_iterator it2 = std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), texture ); if( it2 != mImageMemBarrierPtrs.end() ) needsToFlush = true; } if( needsToFlush ) { // If this asserts triggers, then the texture is probably being referenced // by something else doing anything on the texture and was interrupted // midway (since Ogre must ensure the texture ends in TRANSFER_SRC/DST_OPTIMAL // if the copy encoder is holding a reference. OGRE_ASSERT_LOW( texture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || texture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); endCopyEncoder(); } } } //------------------------------------------------------------------------- void VulkanQueue::addWindowToWaitFor( VkSemaphore imageAcquisitionSemaph ) { OGRE_ASSERT_MEDIUM( mFamily == Graphics ); mGpuWaitFlags.push_back( VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT ); mGpuWaitSemaphForCurrCmdBuff.push_back( imageAcquisitionSemaph ); } //------------------------------------------------------------------------- void VulkanQueue::queueForDeletion(VkBuffer buffer, VkDeviceMemory memory) { mPerFrameData[mCurrentFrameIdx].mBufferGraveyard.push_back({buffer, memory}); } void VulkanQueue::queueForDeletion(const std::shared_ptr<VulkanDescriptorPool>& descriptorPool) { mPerFrameData[mCurrentFrameIdx].mDescriptorPoolGraveyard.push_back(descriptorPool); } void VulkanQueue::_waitOnFrame( uint8 frameIdx ) { VkFence fence = mPerFrameData[frameIdx].mProtectingFence; vkWaitForFences( mDevice, 1, &fence, VK_TRUE, UINT64_MAX ); // it is safe to free staging buffers now for(auto bm : mPerFrameData[frameIdx].mBufferGraveyard) { vkDestroyBuffer(mDevice, bm.first, nullptr); vkFreeMemory(mDevice, bm.second, nullptr); } mPerFrameData[frameIdx].mBufferGraveyard.clear(); mPerFrameData[frameIdx].mDescriptorPoolGraveyard.clear(); } //------------------------------------------------------------------------- bool VulkanQueue::_isFrameFinished( uint8 frameIdx ) { VkFence fence = mPerFrameData[frameIdx].mProtectingFence; VkResult ret = vkWaitForFences( mDevice, 1, &fence, VK_TRUE, 0u ); if( ret != VK_TIMEOUT ) { OGRE_VK_CHECK(ret); //recycleFences( fences ); return true; } return false; } //------------------------------------------------------------------------- void VulkanQueue::commitAndNextCommandBuffer( SubmissionType::SubmissionType submissionType ) { endCommandBuffer(); VkSubmitInfo submitInfo = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &mCurrentCmdBuffer; if( !mGpuWaitSemaphForCurrCmdBuff.empty() ) { // We need to wait on these semaphores so that rendering can // only happen start the swapchain is done presenting submitInfo.waitSemaphoreCount = mGpuWaitSemaphForCurrCmdBuff.size(); submitInfo.pWaitSemaphores = mGpuWaitSemaphForCurrCmdBuff.data(); submitInfo.pWaitDstStageMask = mGpuWaitFlags.data(); } if( submissionType >= SubmissionType::NewFrameIdx ) { if( submissionType >= SubmissionType::EndFrameAndSwap ) { // Get semaphores so that presentation can wait for this job to finish rendering // (one for each window that will be swapped) for (auto w : mWindowsPendingSwap) { mGpuSignalSemaphForCurrCmdBuff.push_back(w->getRenderFinishedSemaphore()); w->setImageFence(mCurrentFence); } } if( !mGpuSignalSemaphForCurrCmdBuff.empty() ) { // We need to signal these semaphores so that presentation // can only happen after we're done rendering (presentation may not be the // only thing waiting for us though; thus we must set this with NewFrameIdx // and not just with EndFrameAndSwap) submitInfo.signalSemaphoreCount = mGpuSignalSemaphForCurrCmdBuff.size(); submitInfo.pSignalSemaphores = mGpuSignalSemaphForCurrCmdBuff.data(); } } OGRE_VK_CHECK(vkResetFences(mDevice, 1, &mCurrentFence) ); vkQueueSubmit( mQueue, 1u, &submitInfo, mCurrentFence ); mGpuWaitSemaphForCurrCmdBuff.clear(); mCurrentCmdBuffer = VK_NULL_HANDLE; if( submissionType >= SubmissionType::EndFrameAndSwap ) { for (auto w : mWindowsPendingSwap) w->_swapBuffers(); } if( submissionType >= SubmissionType::NewFrameIdx ) { mCurrentFrameIdx = (mCurrentFrameIdx + 1) % mPerFrameData.size(); } newCommandBuffer(); if( submissionType >= SubmissionType::EndFrameAndSwap ) { // acquireNextImage must be called after newCommandBuffer() for (auto w : mWindowsPendingSwap) w->acquireNextImage(); mWindowsPendingSwap.clear(); mGpuSignalSemaphForCurrCmdBuff.clear(); } } } // namespace Ogre
43.232009
108
0.576362
[ "render", "object" ]
7019795df361a0e7fd463c2c648be1c42cef3b01
7,079
cpp
C++
src/modules/osgUtil/generated_code/DelaunayTriangulator.pypp.cpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
3
2017-04-20T09:11:47.000Z
2021-04-29T19:24:03.000Z
src/modules/osgUtil/generated_code/DelaunayTriangulator.pypp.cpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
null
null
null
src/modules/osgUtil/generated_code/DelaunayTriangulator.pypp.cpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
null
null
null
// This file has been generated by Py++. #include "boost/python.hpp" #include "wrap_osgUtil.h" #include "wrap_referenced.h" #include "DelaunayTriangulator.pypp.hpp" namespace bp = boost::python; void register_DelaunayTriangulator_class(){ { //::osgUtil::DelaunayTriangulator typedef bp::class_< osgUtil::DelaunayTriangulator, bp::bases< ::osg::Referenced >, osg::ref_ptr< ::osgUtil::DelaunayTriangulator >, boost::noncopyable > DelaunayTriangulator_exposer_t; DelaunayTriangulator_exposer_t DelaunayTriangulator_exposer = DelaunayTriangulator_exposer_t( "DelaunayTriangulator", bp::no_init ); bp::scope DelaunayTriangulator_scope( DelaunayTriangulator_exposer ); DelaunayTriangulator_exposer.def( bp::init< >() ); DelaunayTriangulator_exposer.def( bp::init< osg::Vec3Array *, bp::optional< osg::Vec3Array * > >(( bp::arg("points"), bp::arg("normals")=bp::object() )) ); bp::implicitly_convertible< osg::Vec3Array *, osgUtil::DelaunayTriangulator >(); { //::osgUtil::DelaunayTriangulator::addInputConstraint typedef void ( ::osgUtil::DelaunayTriangulator::*addInputConstraint_function_type )( ::osgUtil::DelaunayConstraint * ) ; DelaunayTriangulator_exposer.def( "addInputConstraint" , addInputConstraint_function_type( &::osgUtil::DelaunayTriangulator::addInputConstraint ) , ( bp::arg("dc") ) , "\n Add an input constraint loop.\n the edges of the loop will constrain the triangulation.\n if remove!=0, the internal triangles of the constraint will be removed;\n the user may the replace the constraint line with an equivalent geometry.\n GWM July 2005\n" ); } { //::osgUtil::DelaunayTriangulator::getInputPointArray typedef ::osg::Vec3Array const * ( ::osgUtil::DelaunayTriangulator::*getInputPointArray_function_type )( ) const; DelaunayTriangulator_exposer.def( "getInputPointArray" , getInputPointArray_function_type( &::osgUtil::DelaunayTriangulator::getInputPointArray ) , bp::return_internal_reference< >() , "\n Get the const input point array.\n" ); } { //::osgUtil::DelaunayTriangulator::getInputPointArray typedef ::osg::Vec3Array * ( ::osgUtil::DelaunayTriangulator::*getInputPointArray_function_type )( ) ; DelaunayTriangulator_exposer.def( "getInputPointArray" , getInputPointArray_function_type( &::osgUtil::DelaunayTriangulator::getInputPointArray ) , bp::return_internal_reference< >() , "\n Get the input point array.\n" ); } { //::osgUtil::DelaunayTriangulator::getOutputNormalArray typedef ::osg::Vec3Array const * ( ::osgUtil::DelaunayTriangulator::*getOutputNormalArray_function_type )( ) const; DelaunayTriangulator_exposer.def( "getOutputNormalArray" , getOutputNormalArray_function_type( &::osgUtil::DelaunayTriangulator::getOutputNormalArray ) , bp::return_internal_reference< >() , "\n Get the const output normal array (optional).\n" ); } { //::osgUtil::DelaunayTriangulator::getOutputNormalArray typedef ::osg::Vec3Array * ( ::osgUtil::DelaunayTriangulator::*getOutputNormalArray_function_type )( ) ; DelaunayTriangulator_exposer.def( "getOutputNormalArray" , getOutputNormalArray_function_type( &::osgUtil::DelaunayTriangulator::getOutputNormalArray ) , bp::return_internal_reference< >() , "\n Get the output normal array (optional).\n" ); } { //::osgUtil::DelaunayTriangulator::getTriangles typedef ::osg::DrawElementsUInt const * ( ::osgUtil::DelaunayTriangulator::*getTriangles_function_type )( ) const; DelaunayTriangulator_exposer.def( "getTriangles" , getTriangles_function_type( &::osgUtil::DelaunayTriangulator::getTriangles ) , bp::return_internal_reference< >() , "\n Get the generated primitive (call triangulate() first).\n" ); } { //::osgUtil::DelaunayTriangulator::getTriangles typedef ::osg::DrawElementsUInt * ( ::osgUtil::DelaunayTriangulator::*getTriangles_function_type )( ) ; DelaunayTriangulator_exposer.def( "getTriangles" , getTriangles_function_type( &::osgUtil::DelaunayTriangulator::getTriangles ) , bp::return_internal_reference< >() , "\n Get the generated primitive (call triangulate() first).\n" ); } { //::osgUtil::DelaunayTriangulator::removeInternalTriangles typedef void ( ::osgUtil::DelaunayTriangulator::*removeInternalTriangles_function_type )( ::osgUtil::DelaunayConstraint * ) ; DelaunayTriangulator_exposer.def( "removeInternalTriangles" , removeInternalTriangles_function_type( &::osgUtil::DelaunayTriangulator::removeInternalTriangles ) , ( bp::arg("constraint") ) , "\n remove the triangles internal to the constraint loops.\n (Line strips cannot remove any internal triangles).\n" ); } { //::osgUtil::DelaunayTriangulator::setInputPointArray typedef void ( ::osgUtil::DelaunayTriangulator::*setInputPointArray_function_type )( ::osg::Vec3Array * ) ; DelaunayTriangulator_exposer.def( "setInputPointArray" , setInputPointArray_function_type( &::osgUtil::DelaunayTriangulator::setInputPointArray ) , ( bp::arg("points") ) , "\n Set the input point array.\n" ); } { //::osgUtil::DelaunayTriangulator::setOutputNormalArray typedef void ( ::osgUtil::DelaunayTriangulator::*setOutputNormalArray_function_type )( ::osg::Vec3Array * ) ; DelaunayTriangulator_exposer.def( "setOutputNormalArray" , setOutputNormalArray_function_type( &::osgUtil::DelaunayTriangulator::setOutputNormalArray ) , ( bp::arg("normals") ) , "\n Set the output normal array (optional).\n" ); } { //::osgUtil::DelaunayTriangulator::triangulate typedef bool ( ::osgUtil::DelaunayTriangulator::*triangulate_function_type )( ) ; DelaunayTriangulator_exposer.def( "triangulate" , triangulate_function_type( &::osgUtil::DelaunayTriangulator::triangulate ) , "\n Start triangulation.\n" ); } } }
49.852113
281
0.608702
[ "geometry", "object" ]
70297dc15069aafa3c7747c47731901f5878c563
4,731
cc
C++
tensorflow_serving/core/load_servables_fast.cc
mzhang-code/serving
527c6f2173eba584ebdca4f8b11ae3c0550ab1a9
[ "Apache-2.0" ]
5,791
2016-02-16T17:50:06.000Z
2022-03-31T11:53:10.000Z
tensorflow_serving/core/load_servables_fast.cc
mzhang-code/serving
527c6f2173eba584ebdca4f8b11ae3c0550ab1a9
[ "Apache-2.0" ]
1,618
2016-02-16T18:04:00.000Z
2022-03-30T07:24:28.000Z
tensorflow_serving/core/load_servables_fast.cc
mzhang-code/serving
527c6f2173eba584ebdca4f8b11ae3c0550ab1a9
[ "Apache-2.0" ]
2,501
2016-02-16T19:57:43.000Z
2022-03-27T02:43:49.000Z
/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_serving/core/load_servables_fast.h" #include <map> #include <string> #include <utility> #include "absl/types/optional.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow_serving/core/servable_state.h" #include "tensorflow_serving/core/source.h" #include "tensorflow_serving/core/target.h" namespace tensorflow { namespace serving { namespace internal { uint32 GetManagerNumLoadThreads(AspiredVersionsManager* manager) { return manager->num_load_threads(); } std::function<void(const uint32)> SetManagerNumLoadThreadsNotifier( AspiredVersionsManager* manager) { return manager->set_num_load_threads_observer_->Notifier(); } Status ConnectSourcesWithFastInitialLoad( AspiredVersionsManager* manager, std::vector<Source<std::unique_ptr<Loader>>*> sources, const std::function<Status()>& wait_until_loaded_fn, const uint32 num_threads) { const uint32 prev_num_load_threads = GetManagerNumLoadThreads(manager); std::function<void(const uint32)> set_manager_num_load_threads = SetManagerNumLoadThreadsNotifier(manager); set_manager_num_load_threads(num_threads); for (Source<std::unique_ptr<Loader>>* source : sources) { ConnectSourceToTarget(source, manager); } const Status status = wait_until_loaded_fn(); set_manager_num_load_threads(prev_num_load_threads); return status; } } // namespace internal Status ConnectSourceWithFastInitialLoad( AspiredVersionsManager* manager, Source<std::unique_ptr<Loader>>* source, ServableStateMonitor* servable_state_monitor, const std::vector<ServableRequest>& initial_servables, const uint32 num_threads) { return ConnectSourcesWithFastInitialLoad(manager, {source}, servable_state_monitor, initial_servables, num_threads); } Status ConnectSourcesWithFastInitialLoad( AspiredVersionsManager* manager, std::vector<Source<std::unique_ptr<Loader>>*> sources, ServableStateMonitor* servable_state_monitor, const std::vector<ServableRequest>& initial_servables, const uint32 num_threads) { return internal::ConnectSourcesWithFastInitialLoad( manager, sources, [&]() { std::map<ServableId, ServableState::ManagerState> states_reached; const bool all_servables_available = servable_state_monitor->WaitUntilServablesReachState( initial_servables, ServableState::ManagerState::kAvailable, &states_reached); if (!all_servables_available) { const int num_unavailable_servables = std::count_if( states_reached.begin(), states_reached.end(), [](const std::pair<ServableId, ServableState::ManagerState>& id_and_state) { return id_and_state.second != ServableState::ManagerState::kAvailable; }); string message = strings::StrCat(num_unavailable_servables, " servable(s) did not become available: {"); for (const auto& id_and_state : states_reached) { if (id_and_state.second != ServableState::ManagerState::kAvailable) { absl::optional<ServableState> maybe_state = servable_state_monitor->GetState(id_and_state.first); const string error_msg = maybe_state && !maybe_state.value().health.ok() ? " due to error: " + maybe_state.value().health.ToString() : ""; strings::StrAppend(&message, "{", id_and_state.first.DebugString(), error_msg, "}, "); } } strings::StrAppend(&message, "}"); return errors::Unknown(message); } return Status::OK(); }, num_threads); } } // namespace serving } // namespace tensorflow
38.778689
80
0.661171
[ "vector" ]
7029c66d32fd9f4ecf0867cfc2a1c4f396240cc1
29,406
cpp
C++
ActionReconstructionLib/InverseProblem_Adjoint_YoungsModulus.cpp
shamanDevel/SparseSurfaceConstraints
88357ff847369a45b9f16f9f44159196138f9147
[ "MIT" ]
16
2020-03-08T18:28:27.000Z
2022-02-13T20:32:56.000Z
ActionReconstructionLib/InverseProblem_Adjoint_YoungsModulus.cpp
shamanDevel/SparseSurfaceConstraints
88357ff847369a45b9f16f9f44159196138f9147
[ "MIT" ]
null
null
null
ActionReconstructionLib/InverseProblem_Adjoint_YoungsModulus.cpp
shamanDevel/SparseSurfaceConstraints
88357ff847369a45b9f16f9f44159196138f9147
[ "MIT" ]
3
2020-03-26T01:54:31.000Z
2020-11-18T13:32:46.000Z
#include "InverseProblem_Adjoint_YoungsModulus.h" #include <Eigen/Dense> #include <tinyformat.h> #include <cinder/Log.h> #include <numeric> #include <LBFGS.h> #include <fstream> #include "GradientDescent.h" #include "AdjointUtilities.h" using namespace std; using namespace Eigen; #define DEBUG_SAVE_MATRICES 0 namespace ar { InverseProblem_Adjoint_YoungsModulus::InverseProblem_Adjoint_YoungsModulus() : initialYoungsModulus(50) , youngsModulusPrior(0.1) , numIterations(10) { } InverseProblemOutput InverseProblem_Adjoint_YoungsModulus::solveGrid(int deformedTimestep, BackgroundWorker* worker, IntermediateResultCallback_t callback) { CI_LOG_I("Solve for Young's Modulus at timestep " << deformedTimestep); // Create simulation worker->setStatus("Adjoint - Young's Modulus Grid: create simulation"); SoftBodyGrid2D simulation; simulation.setGridResolution(input->gridResolution_); simulation.setSDF(input->gridReferenceSdf_); simulation.setExplicitDiffusion(true); simulation.setHardDirichletBoundaries(false); simulation.resetBoundaries(); for (const auto& b : input->gridDirichletBoundaries_) simulation.addDirichletBoundary(b.first.first, b.first.second, b.second); for (const auto& b : input->gridNeumannBoundaries_) simulation.addNeumannBoundary(b.first.first, b.first.second, b.second); if (worker->isInterrupted()) return InverseProblemOutput(); // Set parameters with everything that can't be reconstructed here simulation.setGravity(input->settings_.gravity_); simulation.setMass(input->settings_.mass_); simulation.setDamping(input->settings_.dampingAlpha_, input->settings_.dampingBeta_); simulation.setRotationCorrection(SoftBodySimulation::RotationCorrection::None); if (worker->isInterrupted()) return InverseProblemOutput(); //cost function: //F(youngsModulus) = 0.5*|| disp(youngsModulus) - dispRef ||^2 + priorWeight / youngsModulus GridUtils2D::grid_t outputSdf(input->gridResolution_, input->gridResolution_); //TODO: once the gradient is fixed, switch to LBFGS #if 1 //Gradient Descent //define gradient of the cost function real finalCost = 0; const auto gradient = [&simulation, &outputSdf, &finalCost, this, worker, deformedTimestep](const Vector1& youngsModulusV) { real youngsModulus = youngsModulusV.x(); real cost; real gradient = gradientGrid(deformedTimestep, simulation, youngsModulus, outputSdf, cost, worker); finalCost = cost; return Vector1(gradient); }; //Optimize GradientDescent<Vector1> gd(Vector1(initialYoungsModulus), gradient, 1e-10, 10); gd.setMinStepsize(0.0001); gd.setMaxStepsize(0.5); int oi; for (oi = 0; oi < numIterations; ++oi) { worker->setStatus(tfm::format("Adjoint - Young's Modulus Grid: optimization %d/%d", (oi + 1), numIterations)); if (gd.step()) break; { InverseProblemOutput output; output.youngsModulus_ = gd.getCurrentSolution()[0]; output.resultGridSdf_ = outputSdf; output.finalCost_ = finalCost; callback(output); } if (worker->isInterrupted()) return InverseProblemOutput(); } real finalValue = gd.getCurrentSolution()[0]; #else //LBFGS LBFGSpp::LBFGSParam<real> params; params.epsilon = 1e-10; params.max_iterations = numIterations; LBFGSpp::LBFGSSolver<real> lbfgs(params); //define gradient LBFGSpp::LBFGSSolver<real>::ObjectiveFunction_t fun([&simulation, &outputSdf, this, worker, deformedTimestep](const VectorX& x, VectorX& gradient) -> real { real youngsModulus = x[0]; real cost; real grad = gradientGrid(deformedTimestep, simulation, youngsModulus, outputSdf, cost, worker); gradient[0] = grad; return cost; }); LBFGSpp::LBFGSSolver<real>::CallbackFunction_t lbfgsCallback([worker, callback, &outputSdf, this](const VectorX& x, const real& v, int k) -> bool { worker->setStatus(tfm::format("Adjoint - Young's Modulus: optimization %d/%d", k, numIterations)); InverseProblemOutput output; output.youngsModulus_ = x[0]; output.resultGridSdf_ = outputSdf; output.finalCost_ = v; callback(output); return !worker->isInterrupted(); }); //optimize real finalCost = 0; VectorX finalValueV = VectorX::Constant(1, initialYoungsModulus); int oi = lbfgs.minimize(fun, finalValueV, finalCost, lbfgsCallback); if (worker->isInterrupted()) return InverseProblemOutput(); real finalValue = finalValueV[0]; #endif CI_LOG_I("Optimization: final Youngs' Modulus is " << finalValue << " after " << oi << " optimization steps, reference value is " << input->settings_.youngsModulus_); InverseProblemOutput output; output.youngsModulus_ = finalValue; output.resultGridSdf_ = outputSdf; output.finalCost_ = finalCost; return output; } InverseProblemOutput InverseProblem_Adjoint_YoungsModulus::solveMesh(int deformedTimestep, BackgroundWorker* worker, IntermediateResultCallback_t callback) { CI_LOG_I("Solve for Young's Modulus at timestep " << deformedTimestep); // Create simulation worker->setStatus("Adjoint - Young's Modulus: create simulation"); SoftBodyMesh2D simulation; simulation.setMesh(input->meshReferencePositions_, input->meshReferenceIndices_); simulation.resetBoundaries(); for (const auto& b : input->meshDirichletBoundaries_) simulation.addDirichletBoundary(b.first, b.second); for (const auto& b : input->meshNeumannBoundaries_) simulation.addNeumannBoundary(b.first, b.second); simulation.reorderNodes(); if (worker->isInterrupted()) return InverseProblemOutput(); // Set parameters with everything that can't be reconstructed here simulation.setGravity(input->settings_.gravity_); simulation.setMass(input->settings_.mass_); simulation.setDamping(input->settings_.dampingAlpha_, input->settings_.dampingBeta_); simulation.setRotationCorrection(SoftBodySimulation::RotationCorrection::None); if (worker->isInterrupted()) return InverseProblemOutput(); //cost function: //F(youngsModulus) = 0.5*|| disp(youngsModulus) - dispRef ||^2 + priorWeight / youngsModulus VectorX outputU; #if 0 //Gradient Descent //define gradient of the cost function const auto gradient = [&simulation, &outputU, this, worker, deformedTimestep](const Vector1& youngsModulusV) { real youngsModulus = youngsModulusV.x(); real cost; real gradient = gradientMesh(deformedTimestep, simulation, youngsModulus, outputU, cost, worker); return Vector1(gradient); }; //run optimization GradientDescent<Vector1> gd(Vector1(initialYoungsModulus), gradient, 1e-10, 10); int oi; for (oi = 0; oi < numIterations; ++oi) { worker->setStatus(tfm::format("Adjoint - Young's Modulus: optimization %d/%d", (oi + 1), numIterations)); if (gd.step()) break; if (worker->isInterrupted()) return InverseProblemOutput(); } real finalValue = gd.getCurrentSolution()[0]; #else //LBFGS LBFGSpp::LBFGSParam<real> params; params.epsilon = 1e-15; params.max_iterations = numIterations; LBFGSpp::LBFGSSolver<real> lbfgs(params); //define gradient LBFGSpp::LBFGSSolver<real>::ObjectiveFunction_t fun([&simulation, &outputU, this, worker, deformedTimestep](const VectorX& x, VectorX& gradient) -> real { real youngsModulus = x[0]; real cost; real grad = gradientMesh(deformedTimestep, simulation, youngsModulus, outputU, cost, worker); gradient[0] = grad; return cost; }); LBFGSpp::LBFGSSolver<real>::CallbackFunction_t lbfgsCallback([worker, &simulation, &outputU, callback, this](const VectorX& x, const VectorX& g, const real& v, int k) -> bool { worker->setStatus(tfm::format("Adjoint - Young's Modulus: optimization %d/%d", k, numIterations)); InverseProblemOutput output; output.youngsModulus_ = x[0]; output.resultMeshDisp_ = SoftBodyMesh2D::Vector2List(simulation.getNumNodes()); for (int i = 0; i<simulation.getNumNodes(); ++i) { if (simulation.getNodeToFreeMap()[i] < 0) output.resultMeshDisp_->at(i).setZero(); else output.resultMeshDisp_->at(i) = outputU.segment<2>(2 * simulation.getNodeToFreeMap()[i]); } output.finalCost_ = v; callback(output); return !worker->isInterrupted(); }); //optimize real finalCost = 0; VectorX finalValueV = VectorX::Constant(1, initialYoungsModulus); int oi = lbfgs.minimize(fun, finalValueV, finalCost, lbfgsCallback); if (worker->isInterrupted()) return InverseProblemOutput(); real finalValue = finalValueV[0]; #endif CI_LOG_I("Optimization: final Youngs' Modulus is " << finalValue << " after " << oi << " optimization steps, reference value is " << input->settings_.youngsModulus_); InverseProblemOutput output; output.youngsModulus_ = finalValue; output.resultMeshDisp_ = SoftBodyMesh2D::Vector2List(simulation.getNumNodes()); for (int i=0; i<simulation.getNumNodes(); ++i) { if (simulation.getNodeToFreeMap()[i] < 0) output.resultMeshDisp_->at(i).setZero(); else output.resultMeshDisp_->at(i) = outputU.segment<2>(2 * simulation.getNodeToFreeMap()[i]); } output.finalCost_ = finalCost; return output; } real InverseProblem_Adjoint_YoungsModulus::gradientMesh( int deformedTimestep, const SoftBodyMesh2D& simulation, real youngsModulus, VectorX& outputU, real& outputCost, BackgroundWorker* worker) const { real poissonsRatio = input->settings_.poissonsRatio_; //FORWARD MatrixX K = MatrixX::Zero(2 * simulation.getNumFreeNodes(), 2 * simulation.getNumFreeNodes()); VectorX F = VectorX::Zero(2 * simulation.getNumFreeNodes()); //assemble force vector F and stiffness matrix K simulation.assembleForceVector(F); if (worker->isInterrupted()) return 0; real materialMu, materialLambda; SoftBodySimulation::computeMaterialParameters(youngsModulus, poissonsRatio, materialMu, materialLambda); Matrix3 C = SoftBodySimulation::computeMaterialMatrix(materialMu, materialLambda); simulation.assembleStiffnessMatrix(C, K, &F, SoftBodyMesh2D::Vector2List(simulation.getNumNodes(), Vector2::Zero())); if (worker->isInterrupted()) return 0; #if DEBUG_SAVE_MATRICES==1 saveAsCSV(K, tfm::format("AdjointYoung-GradientMesh-K-k%f.csv", youngsModulus)); #endif //assemble derivate of matrix K with respect to the youngsModulus MatrixX KDyoung = MatrixX::Zero(2 * simulation.getNumFreeNodes(), 2 * simulation.getNumFreeNodes()); real muDyoung, lambdaDyoung; AdjointUtilities::computeMaterialParameters_D_YoungsModulus(youngsModulus, poissonsRatio, muDyoung, lambdaDyoung); Matrix3 CDyoung = SoftBodySimulation::computeMaterialMatrix(muDyoung, lambdaDyoung); simulation.assembleStiffnessMatrix(CDyoung, KDyoung, nullptr, SoftBodyMesh2D::Vector2List(simulation.getNumNodes(), Vector2::Zero())); #if DEBUG_SAVE_MATRICES==1 saveAsCSV(KDyoung, tfm::format("AdjointYoung-GradientMesh-KDyoung-k%f.csv", youngsModulus)); #endif //solve for the current displacement PartialPivLU<MatrixX> Klu = K.partialPivLu(); VectorX u = Klu.solve(F); outputU = u; //compute the partial gradient of the operations with respect to Young's Modulus VectorX EDyoung = -KDyoung * u; //VectorX EDyoung = Klu.solve(-KDyoung * u); // BACKWARD //compute derivate of the cost function with respect to the output u (displacement) VectorX costDu(2 * simulation.getNumFreeNodes()); for (int i = 0; i < simulation.getNumNodes(); ++i) { if (simulation.getNodeToFreeMap()[i] < 0) continue; costDu.segment<2>(2 * simulation.getNodeToFreeMap()[i]) = u.segment<2>(2 * simulation.getNodeToFreeMap()[i]) - input->meshResultsDisplacement_[deformedTimestep][i]; } #if DEBUG_SAVE_MATRICES==1 saveAsCSV(costDu, tfm::format("AdjointYoung-GradientMesh-costDu-k%f.csv", youngsModulus)); #endif //solve for the dual //In theory, I have to use K', but because I know that K is symmetric, //I can use K directly and not the transpose. VectorX lambda = Klu.solve(costDu); //compute gradient of the prior term real priorDyoung = -youngsModulusPrior / (youngsModulus*youngsModulus); //evalue the final gradient real gradient = lambda.transpose() * EDyoung + priorDyoung; //For testing: evaluate cost real cost = youngsModulusPrior / youngsModulus; for (int i = 0; i < simulation.getNumNodes(); ++i) { if (simulation.getNodeToFreeMap()[i] < 0) continue; cost += (u.segment<2>(2 * simulation.getNodeToFreeMap()[i]) - input->meshResultsDisplacement_[deformedTimestep][i]).squaredNorm() / 2; } outputCost = cost; CI_LOG_I("Optimization: Youngs Modulus " << youngsModulus << " -> cost " << cost << ", gradient " << gradient); return gradient; } real InverseProblem_Adjoint_YoungsModulus::gradientGrid(int deformedTimestep, const SoftBodyGrid2D& simulation, real youngsModulus, GridUtils2D::grid_t& outputSdf, real& outputCost, BackgroundWorker* worker) const { real poissonsRatio = input->settings_.poissonsRatio_; //FORWARD int resolution = input->gridResolution_; real h = 1.0 / (resolution - 1); Vector2 pos(0, 0); //lower left corner of the grid Vector2 size(h, h); //size of each cell //collect degrees of freedom in the stifness solve const Eigen::MatrixXi& posToIndex = simulation.getPosToIndex(); const SoftBodyGrid2D::indexToPos_t& indexToPos = simulation.getIndexToPos(); const int dof = simulation.getDoF(); MatrixX K = MatrixX::Zero(dof * 2, dof * 2); VectorX f = VectorX::Zero(dof * 2); const VectorX prevU = VectorX::Zero(dof * 2); //previous displacements for rotation correction. Not needed here //assemble force vector F and stiffness matrix K VectorX collisionForces = VectorX::Zero(2 * dof); simulation.assembleForceVector(f, posToIndex, collisionForces); if (worker->isInterrupted()) return 0; real materialMu, materialLambda; SoftBodySimulation::computeMaterialParameters(youngsModulus, poissonsRatio, materialMu, materialLambda); Matrix3 C = SoftBodySimulation::computeMaterialMatrix(materialMu, materialLambda); simulation.assembleStiffnessMatrix(C, materialMu, materialLambda, K, &f, posToIndex, prevU); if (worker->isInterrupted()) return 0; #if DEBUG_SAVE_MATRICES==1 saveAsCSV(K, tfm::format("AdjointYoung-GradientGrid-K-k%f.csv", youngsModulus)); #endif //assemble derivate of matrix K with respect to the youngsModulus MatrixX KDyoung = MatrixX::Zero(dof * 2, dof * 2); real muDyoung, lambdaDyoung; AdjointUtilities::computeMaterialParameters_D_YoungsModulus(youngsModulus, poissonsRatio, muDyoung, lambdaDyoung); Matrix3 CDyoung = SoftBodySimulation::computeMaterialMatrix(muDyoung, lambdaDyoung); simulation.assembleStiffnessMatrix(CDyoung, muDyoung, lambdaDyoung, KDyoung, nullptr, posToIndex, prevU); if (worker->isInterrupted()) return 0; #if DEBUG_SAVE_MATRICES==1 saveAsCSV(KDyoung, tfm::format("AdjointYoung-GradientGrid-KDyoung-k%f.csv", youngsModulus)); #endif //solve for the current displacement PartialPivLU<MatrixX> Klu = K.partialPivLu(); VectorX solution = Klu.solve(f); if (worker->isInterrupted()) return 0; //map back to a grid SoftBodyGrid2D::grid_t uGridX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); SoftBodyGrid2D::grid_t uGridY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); for (int i = 0; i < dof; ++i) { Vector2i p = indexToPos.at(i); uGridX(p.x(), p.y()) = solution[2 * i]; uGridY(p.x(), p.y()) = solution[2 * i + 1]; } if (worker->isInterrupted()) return 0; //perform diffusion step GridUtils2D::bgrid_t validCells = simulation.computeValidCells(uGridX, uGridY, posToIndex); uGridX = GridUtils2D::fillGridDiffusion(uGridX, validCells); uGridY = GridUtils2D::fillGridDiffusion(uGridY, validCells); if (worker->isInterrupted()) return 0; #if 0 //invert displacements SoftBodyGrid2D::grid_t uGridInvX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); SoftBodyGrid2D::grid_t uGridInvY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); GridUtils2D::invertDisplacement(uGridX, uGridY, uGridInvX, uGridInvY, h); if (worker->isInterrupted()) return 0; //advect levelset outputSdf = GridUtils2D::advectGridSemiLagrange(input->gridReferenceSdf_, uGridInvX, uGridInvY, -1 / h); if (worker->isInterrupted()) return 0; #else //advect levelset GridUtils2D::grid_t advectionWeights(resolution, resolution); outputSdf = GridUtils2D::advectGridDirectForward(input->gridReferenceSdf_, uGridX, uGridY, -1 / h, &advectionWeights); if (worker->isInterrupted()) return 0; #endif //compute the partial gradient of the operations with respect to Young's Modulus VectorX EDyoung = -KDyoung * solution; //VectorX EDyoung = Klu.solve(-KDyoung * solution); if (worker->isInterrupted()) return 0; // BACKWARD #if 1 //compute derivate of the cost function with respect to the output u (displacement) //SoftBodyGrid2D::grid_t costDu = outputSdf - input->gridResultsSdf_[deformedTimestep]; SoftBodyGrid2D::grid_t costDu = (2 * ((2 / M_PI)*outputSdf.atan() - (2 / M_PI)*input->gridResultsSdf_[deformedTimestep].atan())) / (M_PI * (1 + outputSdf.square())); #if 0 //Adjoint: advect levelset SoftBodyGrid2D::grid_t adjInputSdf = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); SoftBodyGrid2D::grid_t adjUGridInvX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); SoftBodyGrid2D::grid_t adjUGridInvY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); GridUtils2D::advectGridSemiLagrangeAdjoint( adjInputSdf, adjUGridInvX, adjUGridInvY, -1 / h, costDu, uGridInvX, uGridInvY, input->gridReferenceSdf_); if (worker->isInterrupted()) return 0; //Adjoint: invert levelset SoftBodyGrid2D::grid_t adjUGridX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); SoftBodyGrid2D::grid_t adjUGridY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); GridUtils2D::invertDisplacementDirectShepardAdjoint( adjUGridX, adjUGridY, adjUGridInvX, adjUGridInvY, uGridX, uGridY, uGridInvX, uGridInvY, h); if (worker->isInterrupted()) return 0; #else SoftBodyGrid2D::grid_t adjInputSdf = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); SoftBodyGrid2D::grid_t adjUGridX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); SoftBodyGrid2D::grid_t adjUGridY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); GridUtils2D::advectGridDirectForwardAdjoint(adjInputSdf, adjUGridX, adjUGridY, costDu, uGridX, uGridY, input->gridReferenceSdf_, outputSdf, -1 / h, advectionWeights); if (worker->isInterrupted()) return 0; #endif //Adjoint: perform diffusion step GridUtils2D::fillGridDiffusionAdjoint(adjUGridX, adjUGridX, uGridX, validCells); //note that the adjoint is both input and output GridUtils2D::fillGridDiffusionAdjoint(adjUGridY, adjUGridY, uGridY, validCells); //it is modified in-place if (worker->isInterrupted()) return 0; //Adjoint: map back to a grid VectorX adjSolution(2 * dof); for (int i = 0; i < dof; ++i) { Vector2i p = indexToPos.at(i); adjSolution[2 * i] = adjUGridX(p.x(), p.y()); adjSolution[2 * i + 1] = adjUGridY(p.x(), p.y()); } if (worker->isInterrupted()) return 0; //Adjoint: solve for the current displacement //since K is symmetric, I can use K directly instead of K' as normally required by the Adjoint Method. VectorX lambda = Klu.solve(adjSolution); if (worker->isInterrupted()) return 0; #else //Recompute inverted true solution SoftBodyGrid2D::grid_t gridResultsInvUx = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); SoftBodyGrid2D::grid_t gridResultsInvUy = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); GridUtils2D::invertDisplacementDirectShepard( input->gridResultsUx_[deformedTimestep], input->gridResultsUy_[deformedTimestep], gridResultsInvUx, gridResultsInvUy, h); //Reduced problem only on the levelset SoftBodyGrid2D::grid_t adjUGridInvX = uGridInvX - gridResultsInvUx; SoftBodyGrid2D::grid_t adjUGridInvY = uGridInvY - gridResultsInvUy; //Adjoint: invert levelset SoftBodyGrid2D::grid_t adjUGridX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); SoftBodyGrid2D::grid_t adjUGridY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution); GridUtils2D::invertDisplacementDirectShepardAdjoint( adjUGridX, adjUGridY, adjUGridInvX, adjUGridInvY, uGridX, uGridY, uGridInvX, uGridInvY, h); if (worker->isInterrupted()) return 0; //Adjoint: perform diffusion step GridUtils2D::fillGridDiffusionAdjoint(adjUGridX, adjUGridX, uGridX, validCells); //note that the adjoint is both input and output GridUtils2D::fillGridDiffusionAdjoint(adjUGridY, adjUGridY, uGridY, validCells); //it is modified in-place if (worker->isInterrupted()) return 0; //Adjoint: map back to a grid VectorX adjSolution(2 * dof); for (int i = 0; i < dof; ++i) { Vector2i p = indexToPos[i]; adjSolution[2 * i] = adjUGridX(p.x(), p.y()); adjSolution[2 * i + 1] = adjUGridY(p.x(), p.y()); } if (worker->isInterrupted()) return 0; #if DEBUG_SAVE_MATRICES==1 saveAsCSV(adjSolution, tfm::format("AdjointYoung-GradientGrid-costDu-k%f.csv", youngsModulus)); #endif //Adjoint: solve for the current displacement //since K is symmetric, I can use K directly instead of K' as normally required by the Adjoint Method. VectorX lambda = -Klu.solve(adjSolution); if (worker->isInterrupted()) return 0; #endif //Done with the adjoint computation //Now I can assemble the final gradient //compute gradient of the prior term real priorDyoung = -youngsModulusPrior / (youngsModulus*youngsModulus); //evalue the final gradient real gradient = -lambda.transpose() * EDyoung + priorDyoung; //For testing: evaluate cost #if 1 real cost = youngsModulusPrior / youngsModulus + ((2/M_PI)*outputSdf.atan() - (2/M_PI)*input->gridResultsSdf_[deformedTimestep].atan()).matrix().squaredNorm() / 2; #else //reduced problem real cost = (uGridInvX - gridResultsInvUx).matrix().squaredNorm() / 2 + (uGridInvY - gridResultsInvUy).matrix().squaredNorm() / 2; #endif outputCost = cost; CI_LOG_I("Optimization: Youngs Modulus " << youngsModulus << " -> cost " << cost << ", gradient " << gradient); return gradient; } void InverseProblem_Adjoint_YoungsModulus::setupParams(cinder::params::InterfaceGlRef params, const std::string& group) { params->addParam("InverseProblem_Adjoint_YoungsModulus_InitialYoungsModulus", &initialYoungsModulus) .group(group).label("Initial Young's Modulus").min(0).step(0.01f); params->addParam("InverseProblem_Adjoint_YoungsModulus_YoungsModulusPrior", &youngsModulusPrior) .group(group).label("Prior on Young's Modulus").min(0).step(0.01f); params->addParam("InverseProblem_Adjoint_YoungsModulus_NumIterations", &numIterations) .group(group).label("Iterations").min(1); } void InverseProblem_Adjoint_YoungsModulus::setParamsVisibility(cinder::params::InterfaceGlRef params, bool visible) const { std::string option = visible ? "visible=true" : "visible=false"; params->setOptions("InverseProblem_Adjoint_YoungsModulus_InitialYoungsModulus", option); params->setOptions("InverseProblem_Adjoint_YoungsModulus_YoungsModulusPrior", option); params->setOptions("InverseProblem_Adjoint_YoungsModulus_NumIterations", option); } std::vector<InverseProblem_Adjoint_YoungsModulus::DataPoint> InverseProblem_Adjoint_YoungsModulus::plotEnergy(int deformedTimestep, BackgroundWorker * worker) const { //control points real trueYoung = input->settings_.youngsModulus_; real minYoung = trueYoung / 4; real maxYoung = trueYoung + (trueYoung - minYoung); int steps = 25; // has to be odd std::vector<DataPoint> points(steps); for (int i = 0; i < steps; ++i) points[i].youngsModulus = minYoung + (maxYoung - minYoung) * i / (steps - 1.0); // Create grid simulation worker->setStatus("Test Plot Grid: create simulation"); SoftBodyGrid2D simulationGrid; simulationGrid.setGridResolution(input->gridResolution_); simulationGrid.setSDF(input->gridReferenceSdf_); simulationGrid.setExplicitDiffusion(true); simulationGrid.setHardDirichletBoundaries(false); simulationGrid.resetBoundaries(); for (const auto& b : input->gridDirichletBoundaries_) simulationGrid.addDirichletBoundary(b.first.first, b.first.second, b.second); for (const auto& b : input->gridNeumannBoundaries_) simulationGrid.addNeumannBoundary(b.first.first, b.first.second, b.second); simulationGrid.setGravity(input->settings_.gravity_); simulationGrid.setMass(input->settings_.mass_); simulationGrid.setDamping(input->settings_.dampingAlpha_, input->settings_.dampingBeta_); simulationGrid.setRotationCorrection(input->settings_.rotationCorrection_); //Run grid simulation GridUtils2D::grid_t outputGrid; for (int i = 0; i < steps; ++i) { worker->setStatus(tfm::format("Test Plot Grid: simulation %d/%d",i+1,steps)); real cost; real gradient = gradientGrid(deformedTimestep, simulationGrid, points[i].youngsModulus, outputGrid, cost, worker); if (worker->isInterrupted()) return {}; points[i].costGrid = cost; points[i].gradientGrid = gradient; } //Create mesh simulation worker->setStatus("Test Plot Mesh: create simulation"); SoftBodyMesh2D simulationMesh; simulationMesh.setMesh(input->meshReferencePositions_, input->meshReferenceIndices_); simulationMesh.resetBoundaries(); for (const auto& b : input->meshDirichletBoundaries_) simulationMesh.addDirichletBoundary(b.first, b.second); for (const auto& b : input->meshNeumannBoundaries_) simulationMesh.addNeumannBoundary(b.first, b.second); simulationMesh.reorderNodes(); simulationMesh.setGravity(input->settings_.gravity_); simulationMesh.setMass(input->settings_.mass_); simulationMesh.setDamping(input->settings_.dampingAlpha_, input->settings_.dampingBeta_); simulationMesh.setRotationCorrection(input->settings_.rotationCorrection_); //Run mesh simulation VectorX outputMesh; for (int i = 0; i < steps; ++i) { worker->setStatus(tfm::format("Test Plot Mesh: simulation %d/%d", i + 1, steps)); real cost; real gradient = gradientMesh(deformedTimestep, simulationMesh, points[i].youngsModulus, outputMesh, cost, worker); if (worker->isInterrupted()) return {}; points[i].costMesh = cost; points[i].gradientMesh = gradient; } return points; } void InverseProblem_Adjoint_YoungsModulus::testPlot(int deformedTimestep, BackgroundWorker* worker) { auto points = plotEnergy(deformedTimestep-1, worker); if (worker->isInterrupted()) return; fstream file("../plots/Adjoint-YoungsModulus.csv", fstream::out | fstream::trunc); file << "Youngs Modulus , Cost Mesh , Gradient Mesh , Cost Grid , Gradient Grid" << endl; file << std::fixed; for (auto point : points) { file << point.youngsModulus << " , " << point.costMesh << " , " << point.gradientMesh << " , " << point.costGrid << " , " << point.gradientGrid << endl; } file.close(); } }
46.602219
178
0.678365
[ "mesh", "vector" ]
703042cf3efdc641e6b5f7e0d99a44f1b8a5876e
3,410
cpp
C++
src/dataloader.cpp
CoinCheung/ImageNet-Loader
e3b860c1597f2c1aa30df2479b717989256ce1bd
[ "Apache-2.0" ]
2
2020-04-16T04:05:41.000Z
2020-06-23T00:43:54.000Z
src/dataloader.cpp
CoinCheung/ImageNet-Loader
e3b860c1597f2c1aa30df2479b717989256ce1bd
[ "Apache-2.0" ]
null
null
null
src/dataloader.cpp
CoinCheung/ImageNet-Loader
e3b860c1597f2c1aa30df2479b717989256ce1bd
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <chrono> #include <vector> #include <string> #include <numeric> #include <cmath> #include <array> #include <fstream> #include <sstream> #include <future> #include <thread> #include <glog/logging.h> #include <opencv2/opencv.hpp> #include "pipeline.hpp" #include "random.hpp" #include "dataloader.hpp" #include "blocking_queue.hpp" using std::endl; using std::cout; using std::vector; using std::string; using std::array; using std::ifstream; using std::stringstream; using std::ios; using cv::Mat; // functions of Batch Batch::Batch(vector<float> *dt, vector<int> dsz, vector<int64_t> *lbs, vector<int> lsz): data(dt), dsize(dsz), labels(lbs), lsize(lsz) {} /* * methods for DataLoaderNP * */ Batch DataLoaderNp::_get_batch() { // auto t1 = std::chrono::steady_clock::now(); CHECK (!pos_end()) << "want more samples than n_samples, there can be some logical problem\n"; Batch spl; int n_batch = batchsize; if (pos + batchsize > n_samples) n_batch = n_samples - pos; int single_size = width * height * 3; vector<float> *data = new vector<float>(n_batch * single_size); vector<int64_t> *labels = new vector<int64_t>(n_batch); int bs_thread = n_batch / num_workers + 1; auto thread_func = [&](int thread_idx) { for (int i{0}; i < bs_thread; ++i) { int pos_thread = i * num_workers + thread_idx; if (pos_thread >= n_batch) break; dataset.get_one_by_idx( indices[pos + pos_thread], &((*data)[pos_thread * single_size]), (*labels)[pos_thread] ); } }; // auto t2 = std::chrono::steady_clock::now(); vector<std::future<void>> tpool(num_workers); // vector<std::future<void>> tpool; for (int i{0}; i < num_workers; ++i) { // tpool[i] = std::async(std::launch::async, thread_func, i); tpool[i] = std::move(thread_pool.submit(thread_func, i)); } for (int i{0}; i < num_workers; ++i) { tpool[i].get(); } pos += n_batch; // auto t3 = std::chrono::steady_clock::now(); vector<int> dsize; if (nchw) { dsize = {n_batch, 3, height, width}; } if (!nchw){ dsize = {n_batch, height, width, 3}; } vector<int> lsize{n_batch}; // auto t4 = std::chrono::steady_clock::now(); // // cout << "prepare thread_func and memory: " // << std::chrono::duration<double, std::milli>(t2 - t1).count() << endl; // cout << "processing: " // << std::chrono::duration<double, std::milli>(t3 - t2).count() << endl; spl.data = data; spl.labels = labels; spl.dsize.swap(dsize); spl.lsize.swap(lsize); return spl; } // // int main () { // string imroot("/data/zzy/imagenet/train/"); // string annfile("../grpc/train.txt"); // BaseDataLoader dl(imroot, annfile, 128, {224, 224}, true, 4); // for (int i{0}; i < 10; ++i) { // cout << dl.dataset.img_paths[i] << endl; // } // for (int i{0}; i < 10; ++i) { // cout << dl.indices[i] << endl; // } // // vector<float> *batch; // vector<int> size; // cout << "run get batch: " << endl; // dl._get_batch(batch, size); // cout << "batch size: "; // for (auto& el : size) cout << el << ", "; cout << endl; // cout << batch->size() << endl; // // return 0; // }
27.723577
137
0.570968
[ "vector" ]
7038bd1362f74c7bbfa8a15bf83155daea6b9fae
3,328
cpp
C++
pytorch/cpp/pybind.cpp
AndrejOrsula/O-CNN
e17290a206c3fe23d80873fb21d7243f71e2e9df
[ "MIT" ]
null
null
null
pytorch/cpp/pybind.cpp
AndrejOrsula/O-CNN
e17290a206c3fe23d80873fb21d7243f71e2e9df
[ "MIT" ]
1
2021-07-15T19:02:21.000Z
2021-07-15T19:02:21.000Z
pytorch/cpp/pybind.cpp
AndrejOrsula/O-CNN
e17290a206c3fe23d80873fb21d7243f71e2e9df
[ "MIT" ]
null
null
null
#include "ocnn.h" PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("octree_batch", &octree_batch, "merge a batch of octrees"); m.def("octree_samples", &octree_samples, "octree samples"); m.def("points2octree", &points2octree, "convert points to octree"); m.def("octree2col", &octree2col, "octree2col"); m.def("col2octree", &col2octree, "col2octree"); m.def("octree_conv", &octree_conv, "octree based convolution"); m.def("octree_deconv", &octree_deconv, "octree based deconvolution"); m.def("octree_conv_grad", &octree_conv_grad, "octree based convolution"); m.def("octree_deconv_grad", &octree_deconv_grad, "octree based deconvolution"); m.def("octree_pad", &octree_pad, "octree pad"); m.def("octree_depad", &octree_depad, "octree depad"); m.def("octree_max_pool", &octree_max_pool, "octree max pooling"); m.def("octree_max_unpool", &octree_max_unpool, "octree max unpooling"); m.def("octree_mask_pool", &octree_mask_pool, "octree mask pooling"); m.def("octree_property", &octree_property, "get the octree property", py::arg("octree"), py::arg("property"), py::arg("depth") = 0); m.def("octree_set_property", &octree_set_property, "set the octree property", py::arg("octree"), py::arg("data"), py::arg("depth")); m.def("transform_points", &transform_points, "transform the point cloud"); m.def("clip_points", &clip_points, "clip the points with unit boundingbox"); m.def("normalize_points", &normalize_points, "normalize the point cloud"); m.def("bounding_sphere", &bounding_sphere, "calc the bounding sphere"); m.def("write_octree", &write_octree, "write octree into file"); m.def("octree_encode_key", &octree_encode_key, "encode xyz-id to octree key"); m.def("octree_decode_key", &octree_decode_key, "decode octree key to xyz-id"); m.def("octree_xyz2key", &octree_xyz2key, "convert key from xyz order"); m.def("octree_key2xyz", &octree_key2xyz, "convert key to xyz order"); m.def("octree_search_key", &octree_search_key, "search key from octree", py::arg("key"), py::arg("octree"), py::arg("depth"), py::arg("key_is_xyz") = true, py::arg("nempty") = false); m.def("octree_scan", &octree_scan, "octree scanning", py::arg("octree"), py::arg("axis"), py::arg("scale") = 1.0); m.def("octree_grow", &octree_grow, "octree growing", py::arg("octree"), py::arg("target_depth"), py::arg("full_octree") = false); m.def("octree_update", &octree_update, "update octree via splitting labels", py::arg("octree"), py::arg("label"), py::arg("depth"), py::arg("split") = 1); m.def("octree_new", &octree_new, "create a new octree", py::arg("batch_size") = 1, py::arg("channel") = 4, py::arg("node_dis") = true, py::arg("adaptive_layer") = 0); m.def("octree_align", &octree_align, "align octree data", py::arg("src_data"), py::arg("src_octree"), py::arg("des_octree"), py::arg("depth")); m.def("octree_align_grad", &octree_align_grad, "backward of align-octree-data"); m.def("points_batch_property", &points_batch_property, "get batch of points' property"); m.def("points_property", &points_property, "get the points' property"); m.def("points_set_property", &points_set_property, "set the points' property"); m.def("points_new", &points_new, "create new points with given input"); }
65.254902
90
0.686599
[ "transform" ]
7045fb6910a8133dd8025762b0f0e74eaa6be324
22,357
cpp
C++
TerraEd/TerraEdDoc.cpp
cjburchell/terrafighter
debc9b7563de05263d9159fbff15407a2dcb0fe9
[ "Apache-2.0" ]
null
null
null
TerraEd/TerraEdDoc.cpp
cjburchell/terrafighter
debc9b7563de05263d9159fbff15407a2dcb0fe9
[ "Apache-2.0" ]
null
null
null
TerraEd/TerraEdDoc.cpp
cjburchell/terrafighter
debc9b7563de05263d9159fbff15407a2dcb0fe9
[ "Apache-2.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// TerraEdDoc.cpp /// /// PATH: D:\dev2\TerraEd /// /// CREATED: 03/06/2004 9:07:16 AM by Christiaan Burchell /// /// PURPOSE: implementation of the CTerraEdDoc class /// /// COPYRIGHT NOTICE: Copyright (C) 2004 Redpoint Games /// /// This software is provided 'as-is', without any express or implied /// warranty. In no event will the author be held liable for any damages /// arising from the use of this software. /// /// Permission is granted to anyone to use this software for any purpose, /// excluding commercial applications, and to alter it and redistribute it /// freely, subject to the following restrictions: /// /// 1. The origin of this software must not be misrepresented; you must not /// claim that you wrote the original software. If you use this software /// in a product, an acknowledgment in the product documentation would be /// appreciated but is not required. /// 2. Altered source versions must be plainly marked as such, and must not be /// misrepresented as being the original software. /// 3. This notice may not be removed or altered from any source distribution. /// 4. The author permission is required to use this software in commercial /// applications /// /// LAST CHANGED: $Date$ /// /// REVISION HISTORY: /// $Log$ /// #include "stdafx.h" #include "TerraEd.h" #include "TerraEdDoc.h" #include "XmlHelpers.h" #include "DeleteFileDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif #define LEVEL_FLIE_NAME "Levels.xml" #define OBJECTS_FLIE_NAME "Objects.xml" #define SPRITES_FLIE_NAME "Sprites.xml" #define WEAPONS_FLIE_NAME "Weapons.xml" ///////////////////////////////////////////////////////////////////////////// // CTerraEdDoc IMPLEMENT_DYNCREATE(CTerraEdDoc, CDocument) BEGIN_MESSAGE_MAP(CTerraEdDoc, CDocument) //{{AFX_MSG_MAP(CTerraEdDoc) ON_COMMAND(ID_TOOLS_ADDFILE, OnToolsAddfile) ON_COMMAND(ID_TOOLS_REMOVEFILE, OnToolsRemovefile) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTerraEdDoc construction/destruction ///////////////////////////////////////////////// /// /// NAME: CTerraEdDoc /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Class Constructor /// /// CREATED: 03/06/2004 9:07:23 AM /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// CTerraEdDoc::CTerraEdDoc() { // TODO: add one-time construction code here } ///////////////////////////////////////////////// /// /// NAME: ~CTerraEdDoc /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Class Destructor /// /// CREATED: 03/06/2004 9:07:25 AM /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// CTerraEdDoc::~CTerraEdDoc() { ClearLevelData(); ClearPlanetObjectData(); ClearSpriteData(); for(UINT i=0;i<m_WeaponData.size();i++) { delete m_WeaponData[i]; } m_WeaponData.clear(); m_Zip.Close(); } ///////////////////////////////////////////////// /// /// NAME: OnNewDocument /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Creates a new document /// /// CREATED: 03/06/2004 9:07:37 AM /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: add reinitialization code here // (SDI documents will reuse this document) ClearLevelData(); ClearPlanetObjectData(); ClearSpriteData(); for(UINT i=0;i<m_WeaponData.size();i++) { delete m_WeaponData[i]; } m_WeaponData.clear(); return TRUE; } ///////////////////////////////////////////////// /// /// NAME: ClearLevelData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Clears the level data /// /// CREATED: 03/06/2004 9:07:46 AM /// /// RETURN: void /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// void CTerraEdDoc::ClearLevelData() { for(UINT i=0;i<m_Levels.size();i++) { delete m_Levels[i]; } m_Levels.clear(); } ///////////////////////////////////////////////////////////////////////////// // CTerraEdDoc serialization ///////////////////////////////////////////////// /// /// NAME: Serialize /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Serializes the Object /// /// CREATED: 03/06/2004 9:07:49 AM /// /// PARAMETERS: /// CArchive& ar /// /// RETURN: void /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// void CTerraEdDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } ///////////////////////////////////////////////////////////////////////////// // CTerraEdDoc diagnostics #ifdef _DEBUG ///////////////////////////////////////////////// /// /// NAME: AssertValid /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Debug Function /// /// CREATED: 03/06/2004 9:07:53 AM /// /// RETURN: void /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// void CTerraEdDoc::AssertValid() const { CDocument::AssertValid(); } ///////////////////////////////////////////////// /// /// NAME: Dump /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Debug Function /// /// CREATED: 03/06/2004 9:07:54 AM /// /// PARAMETERS: /// CDumpContext& dc /// /// RETURN: void /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// void CTerraEdDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CTerraEdDoc commands ///////////////////////////////////////////////// /// /// NAME: OnOpenDocument /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Opens a new document /// /// CREATED: 03/06/2004 9:08:02 AM /// /// PARAMETERS: /// LPCTSTR lpszPathName /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::OnOpenDocument(LPCTSTR lpszPathName) { AfxGetApp()->WriteProfileString(_T("Settings"),_T("LastOpenFile"),lpszPathName); //if (!CDocument::OnOpenDocument(lpszPathName)) // return FALSE; //m_Zip.Open("Test2.zip"); //m_Zip.AddNewFile("Test.txt"); //m_Zip.Close(); try { m_Zip.Open(lpszPathName); } catch(...) { CString str; str.Format("Unable To Open File %s",lpszPathName); MessageBox(NULL,str,"ERROR",0); return FALSE; } if(!LoadLevelData()) return FALSE; if(!LoadSpriteData()) return FALSE; if(!LoadPlanetObjectData()) return FALSE; if(!LoadWeaponData()) return FALSE; return TRUE; } ///////////////////////////////////////////////// /// /// NAME: OnSaveDocument /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Saves the doument /// /// CREATED: 03/06/2004 9:08:12 AM /// /// PARAMETERS: /// LPCTSTR lpszPathName /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::OnSaveDocument(LPCTSTR lpszPathName) { AfxGetApp()->WriteProfileString(_T("Settings"),_T("LastOpenFile"),lpszPathName); SaveLevelData(); SavePlanetObjectData(); SaveSpriteData(); m_Zip.Close(); m_Zip.Open(lpszPathName); return TRUE;//CDocument::OnSaveDocument(lpszPathName); } ///////////////////////////////////////////////// /// /// NAME: LoadPlanetObjectData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Loads the planet Object data /// /// CREATED: 03/06/2004 9:10:32 AM /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::LoadPlanetObjectData() { try { MSXML2::IXMLDOMDocumentPtr docPtr; // create the xml document if( FAILED(docPtr.CreateInstance("msxml2.domdocument"))) return FALSE; if(!m_Zip.ExtractFileTo(OBJECTS_FLIE_NAME,"temp.xml")) { AfxMessageBox("Unable to load Objects.xml"); return FALSE; } _variant_t varOut((bool)TRUE); varOut = docPtr->load("temp.xml"); // load the xml document DeleteFile("temp.xml"); if((bool)varOut == TRUE) { int ElementCount; MSXML2::IXMLDOMElementPtr docElementPtr = docPtr->documentElement; MSXML2::IXMLDOMNodeListPtr RowListPtr = docElementPtr->selectNodes("Object"); ElementCount = RowListPtr->length; if(ElementCount > 0) // if there are any rows { ClearPlanetObjectData(); for(int i=0;i<ElementCount;i++) // for each row { // get the row MSXML2::IXMLDOMNodePtr RowItem = RowListPtr->item[i]; CPlanetObjectData Data; Data.Load(RowItem); CPlanetObjectDataEx* pData; switch(Data.m_Type) { case OBJECTTYPE_TREE: pData = new CPlanetObjectTree(); break; case OBJECTTYPE_BUSH: pData = new CPlanetObjectBush(); break; case OBJECTTYPE_MESH: case OBJECTTYPE_POWERUP: case OBJECTTYPE_WAYPOINT: pData = new CPlanetObjectMesh(); break; } pData->Load(RowItem); pData->m_Index = i; m_PlanetObjectData.push_back(pData); } } else return FALSE; } } catch(...) { AfxMessageBox("Exception occurred LoadPlanetObjectData"); return FALSE; } return TRUE; } ///////////////////////////////////////////////// /// /// NAME: LoadSpriteData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Loads the sprite data /// /// CREATED: 03/06/2004 9:10:22 AM /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::LoadSpriteData() { try { MSXML2::IXMLDOMDocumentPtr docPtr; // create the xml document if( FAILED(docPtr.CreateInstance("msxml2.domdocument"))) return FALSE; if(!m_Zip.ExtractFileTo(SPRITES_FLIE_NAME,"temp.xml")) { AfxMessageBox("Unable to load Sprites.xml"); return FALSE; } _variant_t varOut((bool)TRUE); varOut = docPtr->load("temp.xml"); // load the xml document DeleteFile("temp.xml"); if((bool)varOut == TRUE) { int ElementCount; MSXML2::IXMLDOMElementPtr docElementPtr = docPtr->documentElement; MSXML2::IXMLDOMNodeListPtr RowListPtr = docElementPtr->selectNodes("Sprite"); ElementCount = RowListPtr->length; if(ElementCount > 0) // if there are any rows { ClearSpriteData(); for(int i=0;i<ElementCount;i++) // for each row { // get the row MSXML2::IXMLDOMNodePtr RowItem = RowListPtr->item[i]; CSpriteDataEx* pData = new CSpriteDataEx; pData->Load(RowItem); pData->m_Index = i; m_SpriteData.push_back(pData); } } else return FALSE; } } catch(...) { AfxMessageBox("Exception occurred LoadShips"); return FALSE; } return TRUE; } ///////////////////////////////////////////////// /// /// NAME: ClearPlanetObjectData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Clears the planet data /// /// CREATED: 03/06/2004 9:08:27 AM /// /// RETURN: void /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// void CTerraEdDoc::ClearPlanetObjectData() { for(UINT i=0;i<m_PlanetObjectData.size();i++) { delete m_PlanetObjectData[i]; } m_PlanetObjectData.clear(); } ///////////////////////////////////////////////// /// /// NAME: ClearSpriteData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Clears the sprite data /// /// CREATED: 03/06/2004 9:08:36 AM /// /// RETURN: void /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// void CTerraEdDoc::ClearSpriteData() { for(UINT i=0;i<m_SpriteData.size();i++) { delete m_SpriteData[i]; } m_SpriteData.clear(); } ///////////////////////////////////////////////// /// /// NAME: SavePlanetObjectData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Saves the planet data /// /// CREATED: 03/06/2004 9:10:08 AM /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::SavePlanetObjectData() { try { MSXML2::IXMLDOMDocumentPtr l_docPtr; MSXML2::IXMLDOMElementPtr l_Root; l_docPtr.CreateInstance(_T("msxml2.domdocument")); l_Root = l_docPtr->createElement(_T("Objects")); l_docPtr->appendChild(l_Root); for(UINT i=0;i<m_PlanetObjectData.size();i++) { MSXML2::IXMLDOMElementPtr pElement; pElement = l_docPtr->createElement("Object"); l_Root->appendChild(pElement); m_PlanetObjectData[i]->Save(l_docPtr,pElement); } l_docPtr->save(COleVariant(OBJECTS_FLIE_NAME)); int index = m_Zip.FindFile(OBJECTS_FLIE_NAME); if( index != -1) m_Zip.DeleteFile(index); m_Zip.AddNewFile(OBJECTS_FLIE_NAME); DeleteFile(OBJECTS_FLIE_NAME); } catch (...) { sys_msg("Unexpected exception trying to save the XML file in CEMSOIMainFrame::OnFileOisaveworkspace\n"); return FALSE; } return TRUE;//CDocument::OnSaveDocument(lpszPathName); } ///////////////////////////////////////////////// /// /// NAME: SaveSpriteData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Saves the sprite data /// /// CREATED: 03/06/2004 9:09:59 AM /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::SaveSpriteData() { try { MSXML2::IXMLDOMDocumentPtr l_docPtr; MSXML2::IXMLDOMElementPtr l_Root; l_docPtr.CreateInstance(_T("msxml2.domdocument")); l_Root = l_docPtr->createElement(_T("Sprites")); l_docPtr->appendChild(l_Root); for(UINT i=0;i<m_SpriteData.size();i++) { MSXML2::IXMLDOMElementPtr pElement; pElement = l_docPtr->createElement("Sprite"); l_Root->appendChild(pElement); m_SpriteData[i]->Save(l_docPtr,pElement); } l_docPtr->save(COleVariant(SPRITES_FLIE_NAME)); int index = m_Zip.FindFile(SPRITES_FLIE_NAME); if( index != -1) m_Zip.DeleteFile(index); m_Zip.AddNewFile(SPRITES_FLIE_NAME); DeleteFile(SPRITES_FLIE_NAME); } catch (...) { sys_msg("Unexpected exception trying to save the XML file in CEMSOIMainFrame::OnFileOisaveworkspace\n"); return FALSE; } return TRUE;//CDocument::OnSaveDocument(lpszPathName); } ///////////////////////////////////////////////// /// /// NAME: SaveWeaponData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Saves the weapon data /// /// CREATED: 03/06/2004 9:09:49 AM /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::SaveWeaponData() { try { MSXML2::IXMLDOMDocumentPtr l_docPtr; MSXML2::IXMLDOMElementPtr l_Root; l_docPtr.CreateInstance(_T("msxml2.domdocument")); l_Root = l_docPtr->createElement(_T("Weapons")); l_docPtr->appendChild(l_Root); for(UINT i=0;i<m_WeaponData.size();i++) { MSXML2::IXMLDOMElementPtr pElement; pElement = l_docPtr->createElement("Weapon"); l_Root->appendChild(pElement); m_WeaponData[i]->Save(l_docPtr,pElement); } l_docPtr->save(COleVariant(WEAPONS_FLIE_NAME)); int index = m_Zip.FindFile(WEAPONS_FLIE_NAME); if( index != -1) m_Zip.DeleteFile(index); m_Zip.AddNewFile(WEAPONS_FLIE_NAME); DeleteFile(WEAPONS_FLIE_NAME); } catch (...) { sys_msg("Unexpected exception trying to save the XML file in CEMSOIMainFrame::OnFileOisaveworkspace\n"); return FALSE; } return TRUE;//CDocument::OnSaveDocument(lpszPathName); } ///////////////////////////////////////////////// /// /// NAME: LoadWeaponData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Loads the weapon data /// /// CREATED: 03/06/2004 9:09:40 AM /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::LoadWeaponData() { try { MSXML2::IXMLDOMDocumentPtr docPtr; // create the xml document if( FAILED(docPtr.CreateInstance("msxml2.domdocument"))) return FALSE; if(!m_Zip.ExtractFileTo(WEAPONS_FLIE_NAME,"temp.xml")) { AfxMessageBox("Unable to load Weapons.xml"); return FALSE; } _variant_t varOut((bool)TRUE); varOut = docPtr->load("temp.xml"); // load the xml document DeleteFile("temp.xml"); if((bool)varOut == TRUE) { MSXML2::IXMLDOMNodeListPtr RowListPtr = docPtr->documentElement->selectNodes("Weapon"); int ElementCount = RowListPtr->length; if(ElementCount > 0) // if there are any rows { { for(UINT i=0;i<m_WeaponData.size();i++) { delete m_WeaponData[i]; } m_WeaponData.clear(); } for(UINT i=0;i<ElementCount;i++) // for each row { // get the row MSXML2::IXMLDOMNodePtr RowItem = RowListPtr->item[i]; CWeaponData* pWeapon = new CWeaponData; pWeapon->Load(RowItem); m_WeaponData.push_back(pWeapon); } } else return FALSE; } } catch(...) { sys_msg("Exception occurred LoadWeapons"); return FALSE; } return TRUE; } ///////////////////////////////////////////////// /// /// NAME: LoadLevelData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Loads the level data /// /// CREATED: 03/06/2004 9:09:31 AM /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::LoadLevelData() { try { MSXML2::IXMLDOMDocumentPtr docPtr; // create the xml document if( FAILED(docPtr.CreateInstance("msxml2.domdocument"))) return FALSE; if(!m_Zip.ExtractFileTo(LEVEL_FLIE_NAME,"temp.xml")) { AfxMessageBox("Unable to load Levels.xml"); return FALSE; } _variant_t varOut((bool)TRUE); varOut = docPtr->load("temp.xml"); // load the xml document DeleteFile("temp.xml"); if((bool)varOut == TRUE) { int ElementCount; MSXML2::IXMLDOMElementPtr docElementPtr = docPtr->documentElement; MSXML2::IXMLDOMNodeListPtr RowListPtr = docElementPtr->selectNodes("Level"); ElementCount = RowListPtr->length; if(ElementCount > 0) // if there are any rows { ClearLevelData(); for(int i=0;i<ElementCount;i++) // for each row { // get the row MSXML2::IXMLDOMNodePtr RowItem = RowListPtr->item[i]; CLevelData* pLevel = new CLevelData(); pLevel->Load(RowItem); pLevel->SetIndex(m_Levels.size()); m_Levels.push_back(pLevel); } } else return FALSE; } } catch(...) { AfxMessageBox("Exception occurred LoadShips"); return FALSE; } return TRUE; } ///////////////////////////////////////////////// /// /// NAME: SaveLevelData /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Saves the Level data /// /// CREATED: 03/06/2004 9:09:23 AM /// /// RETURN: BOOL /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// BOOL CTerraEdDoc::SaveLevelData() { try { MSXML2::IXMLDOMDocumentPtr l_docPtr; MSXML2::IXMLDOMElementPtr l_Root; l_docPtr.CreateInstance(_T("msxml2.domdocument")); l_Root = l_docPtr->createElement(_T("Levels")); l_docPtr->appendChild(l_Root); for(UINT i=0;i<m_Levels.size();i++) { MSXML2::IXMLDOMElementPtr pElement; pElement = l_docPtr->createElement("Level"); l_Root->appendChild(pElement); m_Levels[i]->Save(l_docPtr,pElement); } l_docPtr->save(COleVariant(LEVEL_FLIE_NAME)); int index = m_Zip.FindFile(LEVEL_FLIE_NAME); if( index != -1) m_Zip.DeleteFile(index); m_Zip.AddNewFile(LEVEL_FLIE_NAME); DeleteFile(LEVEL_FLIE_NAME); } catch (...) { sys_msg("Unexpected exception trying to save the XML file in CEMSOIMainFrame::OnFileOisaveworkspace\n"); return FALSE; } return TRUE; } ///////////////////////////////////////////////// /// /// NAME: OnToolsAddfile /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Adds a file to the arcive /// /// CREATED: 03/06/2004 9:09:13 AM /// /// RETURN: void /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// void CTerraEdDoc::OnToolsAddfile() { static TCHAR BASED_CODE szFilter[] = _T("All Files (*.*)|*.*||"); CString FileName; CFileDialog dlg(TRUE,_T(""),FileName,OFN_HIDEREADONLY |OFN_NOCHANGEDIR,szFilter); if(dlg.DoModal() == IDOK) { BOOL bRemote = CopyFile(dlg.GetPathName(),dlg.GetFileName(),TRUE); int index = m_Zip.FindFile(dlg.GetFileName()); if( index != -1) m_Zip.DeleteFile(index); m_Zip.AddNewFile(dlg.GetFileName()); if(bRemote) DeleteFile(dlg.GetFileName()); } } ///////////////////////////////////////////////// /// /// NAME: OnToolsRemovefile /// /// CLASS: CTerraEdDoc /// /// DESCRIPTION: Removes selected file from arcive /// /// CREATED: 03/06/2004 9:09:03 AM /// /// RETURN: void /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// void CTerraEdDoc::OnToolsRemovefile() { CDeleteFileDlg dlg(&m_Zip); if(dlg.DoModal() == IDOK) { m_Zip.DeleteFiles(dlg.m_DelList); } }
22.245771
110
0.530259
[ "object" ]
704ee503e8fecae82e2c086fca142298112d8b97
547
hpp
C++
source/011/Grid.hpp
TheBuzzSaw/ProjectEuler
0aa472dc7dac3a710b6a99538b2cbaf8b6463abc
[ "Unlicense" ]
1
2015-03-12T19:56:28.000Z
2015-03-12T19:56:28.000Z
source/011/Grid.hpp
TheBuzzSaw/ProjectEuler
0aa472dc7dac3a710b6a99538b2cbaf8b6463abc
[ "Unlicense" ]
null
null
null
source/011/Grid.hpp
TheBuzzSaw/ProjectEuler
0aa472dc7dac3a710b6a99538b2cbaf8b6463abc
[ "Unlicense" ]
null
null
null
#ifndef GridHpp #define GridHpp #include <iostream> #include <vector> #include <cstdint> class Grid { public: Grid(std::istream& stream); ~Grid(); int64_t Get(std::size_t row, std::size_t column) const; std::size_t RowCount() const; std::size_t ColumnCount() const; private: Grid(Grid&&) = delete; Grid(const Grid&) = delete; Grid& operator=(Grid&&) = delete; Grid& operator=(const Grid&) = delete; std::vector<int64_t> _values; std::size_t _columnCount; }; #endif
18.862069
60
0.610603
[ "vector" ]
7050b48dc181905dc3857aeca23c9840000d586c
921
hpp
C++
RainbowNoise/src/Theory/HybridDiffGenerator.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
24
2016-12-13T09:48:17.000Z
2022-01-13T03:24:45.000Z
RainbowNoise/src/Theory/HybridDiffGenerator.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
2
2019-03-29T06:44:41.000Z
2019-11-12T03:14:25.000Z
RainbowNoise/src/Theory/HybridDiffGenerator.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
8
2016-11-09T15:54:19.000Z
2021-04-08T14:04:17.000Z
/* HybridDiffGenerator.hpp hybrid diff generator for needles over white noise Li-Yi Wei 11/04/2008 */ #ifndef _HYBRID_DIFF_GENERATOR_HPP #define _HYBRID_DIFF_GENERATOR_HPP #include "DiffGenerator.hpp" class HybridDiffGenerator : public DiffGenerator { public: // r_value: positive for removing diff < r_value, negative for keep them // r_variance: positive for turning diff < r_value into >, negative for not HybridDiffGenerator(const vector<float> & domain_size, const float r_value, const float r_variance); ~HybridDiffGenerator(void); int Produce(vector<Sample> & differences) const; protected: // return the number of valid entries int UnitProduce(vector<Sample> & results) const; protected: const float _r_value; const float _r_variance; const bool _keep_diff_less_r; const bool _spawn_diff_less_r; mutable Coordinate _coord0, _coord1; }; #endif
21.928571
104
0.744843
[ "vector" ]
705d504e48580cc8f51dad56df1ed7ec6bc69300
6,381
cpp
C++
Code/Editor/TrackView/AssetBlendKeyUIControls.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Editor/TrackView/AssetBlendKeyUIControls.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Editor/TrackView/AssetBlendKeyUIControls.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "EditorDefs.h" // AzCore #include <AzCore/Asset/AssetManagerBus.h> // CryCommon #include <CryCommon/Maestro/Types/AnimNodeType.h> #include <CryCommon/Maestro/Types/AnimValueType.h> #include <CryCommon/Maestro/Bus/SequenceComponentBus.h> #include <CryCommon/Maestro/Types/AssetBlendKey.h> // Editor #include "KeyUIControls.h" #include "TrackViewKeyPropertiesDlg.h" #include "Controls/ReflectedPropertyControl/ReflectedPropertyItem.h" ////////////////////////////////////////////////////////////////////////// void CAssetBlendKeyUIControls::ResetStartEndLimits(float assetBlendKeyDuration) { const float time_zero = .0f; float step = ReflectedPropertyItem::ComputeSliderStep(time_zero, assetBlendKeyDuration); mv_startTime.GetVar()->SetLimits(time_zero, assetBlendKeyDuration, step, true, true); mv_endTime.GetVar()->SetLimits(time_zero, assetBlendKeyDuration, step, true, true); mv_blendInTime.GetVar()->SetLimits(time_zero, assetBlendKeyDuration, step, true, true); mv_blendOutTime.GetVar()->SetLimits(time_zero, assetBlendKeyDuration, step, true, true); } bool CAssetBlendKeyUIControls::OnKeySelectionChange(CTrackViewKeyBundle& selectedKeys) { if (!selectedKeys.AreAllKeysOfSameType()) { return false; } bool bAssigned = false; if (selectedKeys.GetKeyCount() == 1) { const CTrackViewKeyHandle& keyHandle = selectedKeys.GetKey(0); if (keyHandle.GetTrack()->GetValueType() == AnimValueType::AssetBlend) { AZ::IAssetBlendKey assetBlendKey; keyHandle.GetKey(&assetBlendKey); // Find editor object who owns this node. const CTrackViewTrack* pTrack = keyHandle.GetTrack(); if (pTrack && pTrack->GetAnimNode()->GetType() == AnimNodeType::Component) { m_componentId = pTrack->GetAnimNode()->GetComponentId(); // try to get the AZ::EntityId from the component node's parent CTrackViewAnimNode* parentNode = static_cast<CTrackViewAnimNode*>(pTrack->GetAnimNode()->GetParentNode()); if (parentNode) { m_entityId = parentNode->GetAzEntityId(); } } mv_asset->SetUserData(assetBlendKey.m_assetId.m_subId); mv_asset->SetDisplayValue(assetBlendKey.m_assetId.m_guid.ToString<AZStd::string>().c_str()); mv_loop = assetBlendKey.m_bLoop; mv_endTime = assetBlendKey.m_endTime; mv_startTime = assetBlendKey.m_startTime; mv_timeScale = assetBlendKey.m_speed; mv_blendInTime = assetBlendKey.m_blendInTime; mv_blendOutTime = assetBlendKey.m_blendOutTime; bAssigned = true; } } return bAssigned; } // Called when UI variable changes. void CAssetBlendKeyUIControls::OnUIChange(IVariable* pVar, CTrackViewKeyBundle& selectedKeys) { CTrackViewSequence* pSequence = GetIEditor()->GetAnimation()->GetSequence(); if (!pSequence || !selectedKeys.AreAllKeysOfSameType()) { return; } for (unsigned int keyIndex = 0, num = (int)selectedKeys.GetKeyCount(); keyIndex < num; keyIndex++) { CTrackViewKeyHandle keyHandle = selectedKeys.GetKey(keyIndex); CTrackViewTrack* pTrack = keyHandle.GetTrack(); if (keyHandle.GetTrack()->GetValueType() == AnimValueType::AssetBlend) { AZ::IAssetBlendKey assetBlendKey; keyHandle.GetKey(&assetBlendKey); if (mv_asset.GetVar() == pVar) { AZStd::string stringGuid = mv_asset->GetDisplayValue().toLatin1().data(); if (!stringGuid.empty()) { AZ::Uuid guid(stringGuid.c_str(), stringGuid.length()); AZ::u32 subId = mv_asset->GetUserData().value<AZ::u32>(); assetBlendKey.m_assetId = AZ::Data::AssetId(guid, subId); // Lookup Filename by assetId and get the filename part of the description AZStd::string assetPath; EBUS_EVENT_RESULT(assetPath, AZ::Data::AssetCatalogRequestBus, GetAssetPathById, assetBlendKey.m_assetId); assetBlendKey.m_description = ""; if (!assetPath.empty()) { AZStd::string filename; if (AzFramework::StringFunc::Path::GetFileName(assetPath.c_str(), filename)) { assetBlendKey.m_description = filename; } } } // This call is required to make sure that the newly set animation is properly triggered. pTrack->GetSequence()->Reset(false); } SyncValue(mv_loop, assetBlendKey.m_bLoop, false, pVar); SyncValue(mv_startTime, assetBlendKey.m_startTime, false, pVar); SyncValue(mv_endTime, assetBlendKey.m_endTime, false, pVar); SyncValue(mv_timeScale, assetBlendKey.m_speed, false, pVar); SyncValue(mv_blendInTime, assetBlendKey.m_blendInTime, false, pVar); SyncValue(mv_blendOutTime, assetBlendKey.m_blendOutTime, false, pVar); if (assetBlendKey.m_assetId.IsValid()) { // Ask entity id this asset blend is bound to, to // get the duration of this asset in an async way. Maestro::SequenceComponentRequests::AnimatedFloatValue currValue = 0.0f; Maestro::SequenceComponentRequestBus::Event( pSequence->GetSequenceComponentEntityId(), &Maestro::SequenceComponentRequestBus::Events::GetAssetDuration, currValue, m_entityId, m_componentId, assetBlendKey.m_assetId ); assetBlendKey.m_duration = currValue.GetFloatValue(); ResetStartEndLimits(assetBlendKey.m_duration); } keyHandle.SetKey(&assetBlendKey); } } }
39.88125
126
0.616048
[ "object", "3d" ]
7062a83d52d621f55ecdca47cc960196712bc2c5
4,072
hpp
C++
saga/impl/engine/ini/ini.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
saga/impl/engine/ini/ini.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
saga/impl/engine/ini/ini.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
// Copyright (c) 2005-2007 Andre Merzky (andre@merzky.net) // Copyright (c) 2009 João Abecasis // // 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 _SAGA_IMPL_INI_H_ #define _SAGA_IMPL_INI_H_ 1 #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include <boost/noncopyable.hpp> #include <map> #include <vector> #include <iostream> #include <saga/saga/util.hpp> #include <saga/impl/config.hpp> #define SAGA_INI_MAXLEN 256 #define SAGA_INI_ERRLEN SAGA_INI_MAXLEN // suppress warnings about dependent classes not being exported from the dll #if defined(BOOST_MSVC) #pragma warning(push) #pragma warning(disable: 4091 4251 4231 4275 4660) #endif ////////////////////////////////////////// // // C++ interface // /// @cond /** Hide from Doxygen */ namespace saga { namespace impl { namespace ini { class section; typedef section ini; typedef std::map <std::string, std::string> entry_map; typedef std::map <std::string, TR1::shared_ptr<section> > section_map; class section : boost::noncopyable , public TR1::enable_shared_from_this<section> { section *this_() { return this; } protected: entry_map entries; section_map sections; void indent (int ind, std::ostream& strm) const; void saga_ini_line_msg (std::string msg, std::string file, int lnum = 0); std::string name; section * root; public: explicit section (std::string filename = "", section* root = NULL); ~section (void) { }; void read (std::string filename); void parse (std::string sourcename, std::vector <std::string> lines); void merge (std::string second); void merge (TR1::shared_ptr<section> second); void dump (int ind, std::ostream& strm) const; bool has_section (std::string sec_name) const; bool has_section_full (std::string sec_name) const; TR1::shared_ptr<section> get_section (std::string sec_name); void add_entry (std::string key, std::string val); bool has_entry (std::string key) const; std::string get_entry (std::string key) const; std::string get_entry (std::string key, std::string dflt_val) const; template <typename T> std::string get_entry (std::string const & key, T dflt) const { return get_entry (key, boost::lexical_cast <std::string> (dflt)); } std::string expand_entry (std::string in) const; void expand_entry (std::string&, std::string::size_type) const; void expand_bracket (std::string&, std::string::size_type) const; void expand_brace (std::string&, std::string::size_type) const; section * get_root () const { return root; } std::string get_name () const { return name; } section_map & get_sections () { return sections; } entry_map get_entries () const { entry_map result; entry_map::const_iterator end = entries.end(); for (entry_map::const_iterator it = entries.begin(); it != end; ++it) result [(*it).first] = expand_entry ((*it).second); return result; } }; } // namespace ini } // namespace impl } // namespace saga ///@endcond #endif // _SAGA_IMPL_INI_H_
31.565891
87
0.533153
[ "vector" ]
70635ec5ba77bf1949877478d8cb4b5a1c21bbe1
6,348
cpp
C++
flashlight/ext/integrations/halide/HalideInterface.cpp
harveenchadha/flashlight
80978b464c20b8f9b9eb73cb17c000f7613c35b3
[ "BSD-3-Clause" ]
1
2021-04-24T07:53:02.000Z
2021-04-24T07:53:02.000Z
flashlight/ext/integrations/halide/HalideInterface.cpp
harveenchadha/flashlight
80978b464c20b8f9b9eb73cb17c000f7613c35b3
[ "BSD-3-Clause" ]
5
2021-06-20T23:58:27.000Z
2021-07-09T17:45:07.000Z
flashlight/ext/integrations/halide/HalideInterface.cpp
harveenchadha/flashlight
80978b464c20b8f9b9eb73cb17c000f7613c35b3
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "flashlight/ext/integrations/halide/HalideInterface.h" #include "flashlight/fl/common/CudaUtils.h" #include <af/device.h> #include <af/dim4.hpp> #include <cuda.h> // Driver API needed for CUcontext /* * Replace Halide weakly-linked CUDA handles. * * The Halide CUDA runtime API facilitates defining hard links to handles * defined in libHalide by code that calls AOT-generated pipelines. These * include: * - CUDA memory alloc functions (which are linked to the AF memory manager) * - halide_cuda_device_malloc -- https://git.io/JLA8X * - CUDA memory free functions (which are linked to the AF memory manager) * - halide_cuda_device_free -- https://git.io/JLA81 * - Getter for the CUstream (the CUDA Driver analog of cudaStream_t) * - halide_cuda_get_stream -- https://git.io/JLdYv * - Getter for CUcontext * - halide_cuda_acquire_context -- https://git.io/JLdYe * - Getter for the device ID. * - halide_get_gpu_device -- https://git.io/JLdYf * * Defining these hard links ensures we never have memory or synchronization * issues between Halide pipelines that are dropped inside of any AF operations. * * In hard links associated with the CUDA driver CUcontext, CUstream, or CUDA * device ID we assume that there's always a context, stream, and device ID * defined in the calling thread (that ArrayFire has properly-initialized CUDA * such that one is active). ArrayFire functions that change global CUDA state * should take care of these implicitly. * * An alternative way to accomplish this would be to define a UserContext struct * which holds each of these resources, then define the __user_context symbol * before calling into a Halide AOT-generated pipeline; LLVM should properly * grab this symbol off the stack: https://git.io/JLNax * * \code typedef struct UserContext { UserContext(int id, CUcontext* ctx, cudaStream_t* stream) : deviceId(id), cudaContext(ctx), stream(stream) {}; int deviceId; CUcontext* cudaContext; cudaStream_t* stream; } UserContext; * \endcode * * Initializing code: * \code // Setup CUDA -- shield your eyes int deviceId = fl::getDevice(); CUcontext ctx = 0; CUresult res = cuCtxGetCurrent(&ctx); if (res != CUDA_SUCCESS) throw std::runtime_error("cuCtxGetCurrent failed"); cudaStream_t stream = fl::cuda::getActiveStream(); fl::ext::detail::UserContext userCtx(deviceId, &ctx, &stream); // This symbol is searched for by LLVM on the stack before // JMPing to a function pointer void* __user_context = (void*)&userCtx; * \endcode * * I couldn't quite get this to work, but it might work better and not have some * side effects that the current implementation does. Unclear. */ extern "C" { int halide_cuda_device_malloc(void* /* user_context */, halide_buffer_t* buf) { size_t size = buf->size_in_bytes(); // TODO(jacobkahn): replace me with af::allocV2 when using AF >= 3.8 void* ptr = af::alloc(size, af::dtype::u8); buf->device = (uint64_t)ptr; // eh buf->device_interface = halide_cuda_device_interface(); // This doesn't work because the public device interface API returns an // incomplete type. Is it needed? Who knows // buf->device_interface->impl->use_module(); return 0; } int halide_cuda_device_free(void* /* user_context */, halide_buffer_t* buf) { // TODO(jacobkahn): replace me with af::freeV2 when using AF >= 3.8 af::free((void*)buf->device); // See above - we never call use_module(), so don't release it I suppose... // buf->device_interface->impl->release_module(); buf->device_interface = nullptr; buf->device = 0; return 0; } int halide_cuda_acquire_context( void* /* user_context */, CUcontext* ctx, bool create = true) { CUcontext _ctx = 0; CUresult res = cuCtxGetCurrent(&_ctx); if (res != CUDA_SUCCESS) { throw std::runtime_error("Could not get from CUDA context"); }; *ctx = _ctx; return 0; } int halide_cuda_get_stream( void* /* user_context */, CUcontext /* ctx */, CUstream* stream) { *stream = (CUstream)fl::cuda::getActiveStream(); return 0; } int halide_get_gpu_device(void* /* user_context */) { return fl::getDevice(); } } // extern "C" namespace fl { namespace ext { std::vector<int> afToHalideDims(const af::dim4& dims) { const auto ndims = dims.ndims(); std::vector<int> halideDims(ndims); for (int i = 0; i < ndims; ++i) { halideDims[ndims - 1 - i] = static_cast<int>(dims.dims[i]); } return halideDims; } af::dim4 halideToAfDims(const Halide::Buffer<void>& buffer) { const int nDims = buffer.dimensions(); // Fastpaths if (nDims == 0) { return af::dim4(0); } for (size_t i = 0; i < nDims; ++i) { if (buffer.dim(i).extent() == 0) { return af::dim4(0); } } if (nDims > 4) { throw std::invalid_argument( "getDims: Halide buffer has greater than 4 dimensions"); } af::dim4 out(1, 1, 1, 1); // initialize so unfilled dims are 1, not 0 for (size_t i = 0; i < nDims; ++i) { // Halide can have size zero along a dim --> convert to size 1 for AF auto size = static_cast<dim_t>(buffer.dim(i).extent()); out[nDims - 1 - i] = size == 0 ? 1 : size; } return out; } af::dtype halideRuntimeTypeToAfType(halide_type_t type) { halide_type_code_t typeCode = type.code; switch (typeCode) { case halide_type_int: switch (type.bytes()) { case 2: return af::dtype::s16; case 4: return af::dtype::s32; case 8: return af::dtype::s64; } case halide_type_uint: switch (type.bytes()) { case 2: return af::dtype::u16; case 4: return af::dtype::u32; case 8: return af::dtype::u64; } case halide_type_float: switch (type.bytes()) { case 2: return af::dtype::f16; case 4: return af::dtype::f32; case 8: return af::dtype::f64; } default: throw std::invalid_argument( "halideRuntimeTypeToAfType: unsupported or unknown Halide type"); } } } // namespace ext } // namespace fl
30.965854
80
0.665879
[ "vector" ]
7065b5fa80fe0b4ae254a27e4736b9bae88975be
5,961
cc
C++
src/shader_compiler.cc
paulthomson/amber
f0a3613b727c240ae8b98e232e655db71d87217e
[ "Apache-2.0" ]
1
2019-04-25T16:27:11.000Z
2019-04-25T16:27:11.000Z
src/shader_compiler.cc
ConnectionMaster/amber
cea300d8e6b46f7aa329b20214e0b3bafb586734
[ "Apache-2.0" ]
null
null
null
src/shader_compiler.cc
ConnectionMaster/amber
cea300d8e6b46f7aa329b20214e0b3bafb586734
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 The Amber Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 "src/shader_compiler.h" #include <algorithm> #include <cstdlib> #include <iterator> #include <string> #include <utility> #if AMBER_ENABLE_SPIRV_TOOLS #include "spirv-tools/libspirv.hpp" #include "spirv-tools/linker.hpp" #endif // AMBER_ENABLE_SPIRV_TOOLS #if AMBER_ENABLE_SHADERC #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wshadow-uncaptured-local" #pragma clang diagnostic ignored "-Wweak-vtables" #include "third_party/shaderc/libshaderc/include/shaderc/shaderc.hpp" #pragma clang diagnostic pop #endif // AMBER_ENABLE_SHADERC namespace amber { ShaderCompiler::ShaderCompiler() = default; ShaderCompiler::ShaderCompiler(const std::string& env) : spv_env_(env) {} ShaderCompiler::~ShaderCompiler() = default; std::pair<Result, std::vector<uint32_t>> ShaderCompiler::Compile( const Shader* shader, const ShaderMap& shader_map) const { auto it = shader_map.find(shader->GetName()); if (it != shader_map.end()) return {{}, it->second}; #if AMBER_ENABLE_SPIRV_TOOLS std::string spv_errors; spv_target_env target_env = SPV_ENV_UNIVERSAL_1_0; if (!spv_env_.empty()) { if (!spvParseTargetEnv(spv_env_.c_str(), &target_env)) return {Result("Unable to parse SPIR-V target environment"), {}}; } spvtools::SpirvTools tools(target_env); tools.SetMessageConsumer([&spv_errors](spv_message_level_t level, const char*, const spv_position_t& position, const char* message) { switch (level) { case SPV_MSG_FATAL: case SPV_MSG_INTERNAL_ERROR: case SPV_MSG_ERROR: spv_errors += "error: line " + std::to_string(position.index) + ": " + message + "\n"; break; case SPV_MSG_WARNING: spv_errors += "warning: line " + std::to_string(position.index) + ": " + message + "\n"; break; case SPV_MSG_INFO: spv_errors += "info: line " + std::to_string(position.index) + ": " + message + "\n"; break; case SPV_MSG_DEBUG: break; } }); #endif // AMBER_ENABLE_SPIRV_TOOLS std::vector<uint32_t> results; if (shader->GetFormat() == kShaderFormatSpirvHex) { Result r = ParseHex(shader->GetData(), &results); if (!r.IsSuccess()) return {Result("Unable to parse shader hex."), {}}; #if AMBER_ENABLE_SHADERC } else if (shader->GetFormat() == kShaderFormatGlsl) { Result r = CompileGlsl(shader, &results); if (!r.IsSuccess()) return {r, {}}; #endif // AMBER_ENABLE_SHADERC #if AMBER_ENABLE_SPIRV_TOOLS } else if (shader->GetFormat() == kShaderFormatSpirvAsm) { if (!tools.Assemble(shader->GetData(), &results, spvtools::SpirvTools::kDefaultAssembleOption)) { return {Result("Shader assembly failed: " + spv_errors), {}}; } #endif // AMBER_ENABLE_SPIRV_TOOLS } else { return {Result("Invalid shader format"), results}; } #if AMBER_ENABLE_SPIRV_TOOLS spvtools::ValidatorOptions options; if (!tools.Validate(results.data(), results.size(), options)) return {Result("Invalid shader: " + spv_errors), {}}; #endif // AMBER_ENABLE_SPIRV_TOOLS return {{}, results}; } Result ShaderCompiler::ParseHex(const std::string& data, std::vector<uint32_t>* result) const { size_t used = 0; const char* str = data.c_str(); uint8_t converted = 0; uint32_t tmp = 0; while (used < data.length()) { char* new_pos = nullptr; uint64_t v = static_cast<uint64_t>(std::strtol(str, &new_pos, 16)); ++converted; // TODO(dsinclair): Is this actually right? tmp = tmp | (static_cast<uint32_t>(v) << (8 * (converted - 1))); if (converted == 4) { result->push_back(tmp); tmp = 0; converted = 0; } used += static_cast<size_t>(new_pos - str); str = new_pos; } return {}; } #if AMBER_ENABLE_SHADERC Result ShaderCompiler::CompileGlsl(const Shader* shader, std::vector<uint32_t>* result) const { shaderc::Compiler compiler; shaderc::CompileOptions options; shaderc_shader_kind kind; if (shader->GetType() == kShaderTypeCompute) kind = shaderc_compute_shader; else if (shader->GetType() == kShaderTypeFragment) kind = shaderc_fragment_shader; else if (shader->GetType() == kShaderTypeGeometry) kind = shaderc_geometry_shader; else if (shader->GetType() == kShaderTypeVertex) kind = shaderc_vertex_shader; else if (shader->GetType() == kShaderTypeTessellationControl) kind = shaderc_tess_control_shader; else if (shader->GetType() == kShaderTypeTessellationEvaluation) kind = shaderc_tess_evaluation_shader; else return Result("Unknown shader type"); shaderc::SpvCompilationResult module = compiler.CompileGlslToSpv(shader->GetData(), kind, "-", options); if (module.GetCompilationStatus() != shaderc_compilation_status_success) return Result(module.GetErrorMessage()); std::copy(module.cbegin(), module.cend(), std::back_inserter(*result)); return {}; } #else Result ShaderCompiler::CompileGlsl(const Shader*, std::vector<uint32_t>*) const { return {}; } #endif // AMBER_ENABLE_SHADERC } // namespace amber
32.048387
80
0.666331
[ "vector" ]
70677101bf20d81d1ca1357b4c42d7d93e51c4bd
35,127
cpp
C++
osx/devkit/plug-ins/swissArmyManip/swissArmyManip.cpp
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
10
2018-03-30T16:09:02.000Z
2021-12-07T07:29:19.000Z
osx/devkit/plug-ins/swissArmyManip/swissArmyManip.cpp
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
null
null
null
osx/devkit/plug-ins/swissArmyManip/swissArmyManip.cpp
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
9
2018-06-02T09:18:49.000Z
2021-12-20T09:24:35.000Z
//- // ========================================================================== // Copyright 1995,2006,2008 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk // license agreement provided at the time of installation or download, // or which otherwise accompanies this software in either electronic // or hard copy form. // ========================================================================== //+ //////////////////////////////////////////////////////////////////////// // // swissArmyManip.cpp // // This plug-in is an example of a user-defined manipulator, // which is comprised of a variety of the base manipulators: // - MFnCircleSweepManip.h // - MFnDirectionManip.h // - MFnDiscManip.h // - MFnDistanceManip.h // - MFnFreePointTriadManip.h // - MFnStateManip.h // - MFnToggleManip.h // - MFnRotateManip.h // - MFnScaleManip.h // // To use this plug-in: // // mel: loadPlugin "swissArmyManip.so"; // mel: createNode swissArmyLocator; // click on the showManipTool // //////////////////////////////////////////////////////////////////////// #include <math.h> #include <maya/MIOStream.h> #include <maya/MPxNode.h> #include <maya/MPxLocatorNode.h> #include <maya/MString.h> #include <maya/MTypeId.h> #include <maya/MPlug.h> #include <maya/MVector.h> #include <maya/MAngle.h> #include <maya/MDataBlock.h> #include <maya/MDataHandle.h> #include <maya/MColor.h> #include <maya/M3dView.h> #include <maya/MFnPlugin.h> #include <maya/MDistance.h> #include <maya/MFnUnitAttribute.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFn.h> #include <maya/MPxNode.h> #include <maya/MPxManipContainer.h> #include <maya/MFnCircleSweepManip.h> #include <maya/MFnDirectionManip.h> #include <maya/MFnDiscManip.h> #include <maya/MFnDistanceManip.h> #include <maya/MFnFreePointTriadManip.h> #include <maya/MFnStateManip.h> #include <maya/MFnToggleManip.h> #include <maya/MFnRotateManip.h> #include <maya/MFnScaleManip.h> #include <maya/MPxContext.h> #include <maya/MPxSelectionContext.h> #include <maya/MPxDrawOverride.h> #include <maya/MStateManager.h> #include <maya/MDrawRegistry.h> #include <maya/MDrawContext.h> #include <maya/MHWGeometryUtilities.h> #include <maya/MFnNumericData.h> #include <maya/MManipData.h> #define e \ counter++; \ if (MS::kSuccess != s) { \ cerr << "Status Error in method " << method \ << " at checkpoint #" << counter << "." << "\n" \ << " in File: " << __FILE__ \ << ", at Line: " << __LINE__ << endl; \ s.perror("Error"); \ } const double delta1 = 0.01; const double delta2 = 0.02; const double delta3 = 0.03; const double delta4 = 0.04; // Locator Data // static float centre[][3] = { { 0.10f, 0.0f, 0.10f}, { 0.10f, 0.0f, -0.10f }, { -0.10f, 0.0f, -0.10f }, { -0.10f, 0.0f, 0.10f }, { 0.10f, 0.0f, 0.10f } }; static float state1[][3] = { { 1.00f, 0.0f, 1.00f}, { 1.00f, 0.0f, 0.50f }, { 0.50f, 0.0f, 0.50f }, { 0.50f, 0.0f, 1.00f }, { 1.00f, 0.0f, 1.00f } }; static float state2[][3] = { { 1.00f, 0.0f, -1.00f}, { 1.00f, 0.0f, -0.50f }, { 0.50f, 0.0f, -0.50f }, { 0.50f, 0.0f, -1.00f }, { 1.00f, 0.0f, -1.00f } }; static float state3[][3] = { { -1.00f, 0.0f, -1.00f}, { -1.00f, 0.0f, -0.50f }, { -0.50f, 0.0f, -0.50f }, { -0.50f, 0.0f, -1.00f }, { -1.00f, 0.0f, -1.00f } }; static float state4[][3] = { { -1.00f, 0.0f, 1.00f}, { -1.00f, 0.0f, 0.50f }, { -0.50f, 0.0f, 0.50f }, { -0.50f, 0.0f, 1.00f }, { -1.00f, 0.0f, 1.00f } }; static float arrow1[][3] = { { 0.00f, 0.0f, 1.00f}, { 0.10f, 0.0f, 0.20f }, { -0.10f, 0.0f, 0.20f }, { 0.00f, 0.0f, 1.00f } }; static float arrow2[][3] = { { 1.00f, 0.0f, 0.00f}, { 0.20f, 0.0f, 0.10f }, { 0.20f, 0.0f, -0.10f }, { 1.00f, 0.0f, 0.00f } }; static float arrow3[][3] = { { 0.00f, 0.0f, -1.00f}, { 0.10f, 0.0f, -0.20f }, { -0.10f, 0.0f, -0.20f }, { 0.00f, 0.0f, -1.00f } }; static float arrow4[][3] = { { -1.00f, 0.0f, 0.00f}, { -0.20f, 0.0f, 0.10f }, { -0.20f, 0.0f, -0.10f }, { -1.00f, 0.0f, 0.00f } }; static float perimeter[][3] = { { 1.10f, 0.0f, 1.10f}, { 1.10f, 0.0f, -1.10f }, { -1.10f, 0.0f, -1.10f }, { -1.10f, 0.0f, 1.10f }, { 1.10f, 0.0f, 1.10f } }; static int centreCount = 5; static int state1Count = 5; static int state2Count = 5; static int state3Count = 5; static int state4Count = 5; static int arrow1Count = 4; static int arrow2Count = 4; static int arrow3Count = 4; static int arrow4Count = 4; static int perimeterCount = 5; class swissArmyLocatorManip : public MPxManipContainer { public: swissArmyLocatorManip(); virtual ~swissArmyLocatorManip(); static void * creator(); static MStatus initialize(); virtual MStatus createChildren(); virtual MStatus connectToDependNode(const MObject & node); //Viewport 2.0 manipulator draw overrides virtual void preDrawUI( const M3dView &view ); virtual void drawUI( MHWRender::MUIDrawManager& drawManager, const MHWRender::MFrameContext& frameContext) const; virtual void draw(M3dView & view, const MDagPath & path, M3dView::DisplayStyle style, M3dView::DisplayStatus status); MManipData startPointCallback(unsigned index) const; MVector nodeTranslation() const; MDagPath fCircleSweepManip; MDagPath fDirectionManip; MDagPath fDiscManip; MDagPath fDistanceManip; MDagPath fFreePointTriadManip; MDagPath fStateManip; MDagPath fToggleManip; MDagPath fRotateManip; MDagPath fScaleManip; MDagPath fNodePath; //Value prepared for Viewport 2.0 draw MPoint fTextPosition; public: static MTypeId id; }; MManipData swissArmyLocatorManip::startPointCallback(unsigned /*index*/) const { MManipData manipData; MFnNumericData numData; MObject numDataObj = numData.create(MFnNumericData::k3Double); MVector vec = nodeTranslation(); numData.setData(vec.x, vec.y, vec.z); manipData = numDataObj; return manipData; } MVector swissArmyLocatorManip::nodeTranslation() const { MFnDagNode dagFn(fNodePath); MDagPath path; dagFn.getPath(path); path.pop(); // pop from the shape to the transform MFnTransform transformFn(path); return transformFn.translation(MSpace::kWorld); } MTypeId swissArmyLocatorManip::id( 0x8001e ); swissArmyLocatorManip::swissArmyLocatorManip() { // Do not call createChildren from here } swissArmyLocatorManip::~swissArmyLocatorManip() { } void* swissArmyLocatorManip::creator() { return new swissArmyLocatorManip(); } MStatus swissArmyLocatorManip::initialize() { MStatus stat; stat = MPxManipContainer::initialize(); return stat; } MStatus swissArmyLocatorManip::createChildren() { MStatus stat = MStatus::kSuccess; MString method("swissArmyLocatorManip::createChildren"); MStatus s; int counter = 0; // FreePointTriadManip // fFreePointTriadManip = addFreePointTriadManip("freePointTriadManip", "point"); MFnFreePointTriadManip freePointTriadManipFn(fFreePointTriadManip); // DirectionManip // fDirectionManip = addDirectionManip("directionManip", "direction"); MFnDirectionManip directionManipFn(fDirectionManip); // ToggleManip // fToggleManip = addToggleManip("toggleManip", "toggle"); MFnToggleManip toggleManipFn(fToggleManip); // StateManip // fStateManip = addStateManip("stateManip", "state"); MFnStateManip stateManipFn(fStateManip); // DiscManip // fDiscManip = addDiscManip("discManip", "angle"); MFnDiscManip discManipFn(fDiscManip); // CircleSweepManip // fCircleSweepManip = addCircleSweepManip("circleSweepManip", "angle"); MFnCircleSweepManip circleSweepManipFn(fCircleSweepManip, &s); e; circleSweepManipFn.setCenterPoint(MPoint(0, 0, 0)); circleSweepManipFn.setNormal(MVector(0, 1, 0)); circleSweepManipFn.setRadius(2.0); circleSweepManipFn.setDrawAsArc(true); // DistanceManip // MString manipName("distanceManip"); MString distanceName("distance"); MPoint startPoint(0.0, 0.0, 0.0); MVector direction(0.0, 1.0, 0.0); fDistanceManip = addDistanceManip(manipName, distanceName); MFnDistanceManip distanceManipFn(fDistanceManip); distanceManipFn.setStartPoint(startPoint); distanceManipFn.setDirection(direction); // RotateManip // MString RotateManipName("RotateManip"); MString rotateName("rotation"); fRotateManip = addRotateManip(RotateManipName, rotateName); MFnRotateManip rotateManipFn(fRotateManip); // ScaleManip // MString scaleManipName("scaleManip"); MString scaleName("scale"); fScaleManip = addScaleManip(scaleManipName, scaleName); MFnScaleManip scaleManipFn(fScaleManip); return stat; } MStatus swissArmyLocatorManip::connectToDependNode(const MObject &node) { MStatus stat; // Get the DAG path // MFnDagNode dagNodeFn(node); dagNodeFn.getPath(fNodePath); MObject parentNode = dagNodeFn.parent(0); MFnDagNode parentNodeFn(parentNode); // Connect the plugs // MFnDependencyNode nodeFn; nodeFn.setObject(node); // FreePointTriadManip // MFnFreePointTriadManip freePointTriadManipFn(fFreePointTriadManip); MPlug translationPlug = parentNodeFn.findPlug("t", &stat); if (MStatus::kFailure != stat) { freePointTriadManipFn.connectToPointPlug(translationPlug); } // DirectionManip // MFnDirectionManip directionManipFn; directionManipFn.setObject(fDirectionManip); MPlug directionPlug = nodeFn.findPlug("arrow2Direction", &stat); if (MStatus::kFailure != stat) { directionManipFn.connectToDirectionPlug(directionPlug); unsigned startPointIndex = directionManipFn.startPointIndex(); addPlugToManipConversionCallback(startPointIndex, (plugToManipConversionCallback) &swissArmyLocatorManip::startPointCallback); } // DistanceManip // MFnDistanceManip distanceManipFn; distanceManipFn.setObject(fDistanceManip); MPlug sizePlug = nodeFn.findPlug("size", &stat); if (MStatus::kFailure != stat) { distanceManipFn.connectToDistancePlug(sizePlug); unsigned startPointIndex = distanceManipFn.startPointIndex(); addPlugToManipConversionCallback(startPointIndex, (plugToManipConversionCallback) &swissArmyLocatorManip::startPointCallback); } // CircleSweepManip // MFnCircleSweepManip circleSweepManipFn(fCircleSweepManip); MPlug arrow1AnglePlug = nodeFn.findPlug("arrow1Angle", &stat); if (MStatus::kFailure != stat) { circleSweepManipFn.connectToAnglePlug(arrow1AnglePlug); unsigned centerIndex = circleSweepManipFn.centerIndex(); addPlugToManipConversionCallback(centerIndex, (plugToManipConversionCallback) &swissArmyLocatorManip::startPointCallback); } // DiscManip // MFnDiscManip discManipFn(fDiscManip); MPlug arrow3AnglePlug = nodeFn.findPlug("arrow3Angle", &stat); if (MStatus::kFailure != stat) { discManipFn.connectToAnglePlug(arrow3AnglePlug); unsigned centerIndex = discManipFn.centerIndex(); addPlugToManipConversionCallback(centerIndex, (plugToManipConversionCallback) &swissArmyLocatorManip::startPointCallback); } // StateManip // MFnStateManip stateManipFn(fStateManip); MPlug statePlug = nodeFn.findPlug("state", &stat); if (MStatus::kFailure != stat) { stateManipFn.connectToStatePlug(statePlug); unsigned positionIndex = stateManipFn.positionIndex(); addPlugToManipConversionCallback(positionIndex, (plugToManipConversionCallback) &swissArmyLocatorManip::startPointCallback); } // ToggleManip // MFnToggleManip toggleManipFn(fToggleManip); MPlug togglePlug = nodeFn.findPlug("toggle", &stat); if (MStatus::kFailure != stat) { toggleManipFn.connectToTogglePlug(togglePlug); unsigned startPointIndex = toggleManipFn.startPointIndex(); addPlugToManipConversionCallback(startPointIndex, (plugToManipConversionCallback) &swissArmyLocatorManip::startPointCallback); } // Determine the transform node for the locator // MDagPath transformPath(fNodePath); transformPath.pop(); MFnTransform transformNode(transformPath); // RotateManip // MFnRotateManip rotateManipFn(fRotateManip); MPlug rotatePlug = transformNode.findPlug("rotate", &stat); if (MStatus::kFailure != stat) { rotateManipFn.connectToRotationPlug(rotatePlug); rotateManipFn.displayWithNode(node); } // ScaleManip // MFnScaleManip scaleManipFn(fScaleManip); MPlug scalePlug = transformNode.findPlug("scale", &stat); if (MStatus::kFailure != stat) { scaleManipFn.connectToScalePlug(scalePlug); scaleManipFn.displayWithNode(node); } finishAddingManips(); MPxManipContainer::connectToDependNode(node); return stat; } void swissArmyLocatorManip::draw(M3dView & view, const MDagPath &path, M3dView::DisplayStyle style, M3dView::DisplayStatus status) { MPxManipContainer::draw(view, path, style, status); view.beginGL(); MPoint textPos = nodeTranslation(); char str[100]; sprintf(str, "Swiss Army Manipulator"); MString distanceText(str); view.drawText(distanceText, textPos, M3dView::kLeft); view.endGL(); } // Viewport 2.0 manipulator draw overrides void swissArmyLocatorManip::preDrawUI( const M3dView &view ) { // Update text drawing position fTextPosition = nodeTranslation(); } void swissArmyLocatorManip::drawUI( MHWRender::MUIDrawManager& drawManager, const MHWRender::MFrameContext& frameContext) const { drawManager.beginDrawable(); drawManager.setColor( MColor( 0.0f, 1.0f, 0.1f ) ); drawManager.text( fTextPosition, "Swiss Army Manipulator", MHWRender::MUIDrawManager::kLeft ); drawManager.endDrawable(); } class swissArmyLocator : public MPxLocatorNode { public: swissArmyLocator(); virtual ~swissArmyLocator(); virtual MStatus compute(const MPlug& plug, MDataBlock &data); virtual void draw(M3dView &view, const MDagPath &path, M3dView::DisplayStyle style, M3dView::DisplayStatus status); virtual bool isBounded() const; virtual MBoundingBox boundingBox() const; // Access data from node for drawing, reused by VP1 and VP2 implementations struct DrawData { float multiplier; double angle1; double angle2; double angle3; int state; bool toggle; }; void getDrawData(DrawData& data); // Draw helper methods static void drawOutline(const DrawData& data); static void * creator(); static MStatus initialize(); static MObject aSize; // The size of the locator static MObject aPoint; static MObject aPointX; static MObject aPointY; static MObject aPointZ; static MObject aArrow1Angle; static MObject aArrow2Direction; static MObject aArrow2DirectionX; static MObject aArrow2DirectionY; static MObject aArrow2DirectionZ; static MObject aArrow3Angle; static MObject aArrow4Distance; static MObject aState; static MObject aToggle; public: static MTypeId id; static MString classification; static MString registrantId; }; MTypeId swissArmyLocator::id( 0x8001f ); MString swissArmyLocator::classification("drawdb/geometry/swissArmyLocator"); MString swissArmyLocator::registrantId("SwissArmyLocatorNodePlugin"); MObject swissArmyLocator::aSize; MObject swissArmyLocator::aPoint; MObject swissArmyLocator::aPointX; MObject swissArmyLocator::aPointY; MObject swissArmyLocator::aPointZ; MObject swissArmyLocator::aArrow1Angle; MObject swissArmyLocator::aArrow2Direction; MObject swissArmyLocator::aArrow2DirectionX; MObject swissArmyLocator::aArrow2DirectionY; MObject swissArmyLocator::aArrow2DirectionZ; MObject swissArmyLocator::aArrow3Angle; MObject swissArmyLocator::aArrow4Distance; MObject swissArmyLocator::aState; MObject swissArmyLocator::aToggle; swissArmyLocator::swissArmyLocator() {} swissArmyLocator::~swissArmyLocator() {} MStatus swissArmyLocator::compute(const MPlug &/*plug*/, MDataBlock &/*data*/) { return MS::kUnknownParameter; } void swissArmyLocator::getDrawData(DrawData& data) { MObject node = thisMObject(); MPlug plug(node, swissArmyLocator::aSize); MDistance sizeVal; plug.getValue(sizeVal); data.multiplier = (float)sizeVal.asCentimeters(); MPlug arrow1AnglePlug(node, swissArmyLocator::aArrow1Angle); MAngle arrow1Angle; arrow1AnglePlug.getValue(arrow1Angle); data.angle1 = -arrow1Angle.asRadians() - 3.1415927/2.0; MPlug directionXPlug(node, swissArmyLocator::aArrow2DirectionX); MPlug directionZPlug(node, swissArmyLocator::aArrow2DirectionZ); double dirX, dirZ; directionXPlug.getValue(dirX); directionZPlug.getValue(dirZ); data.angle2 = atan2(dirZ,dirX) + 3.1415927; MPlug arrow3AnglePlug(node, swissArmyLocator::aArrow3Angle); MAngle arrow3Angle; arrow3AnglePlug.getValue(arrow3Angle); data.angle3 = arrow3Angle.asRadians(); MPlug statePlug(node, swissArmyLocator::aState); statePlug.getValue(data.state); MPlug togglePlug(node, swissArmyLocator::aToggle); togglePlug.getValue(data.toggle); } void swissArmyLocator::draw(M3dView &view, const MDagPath &/*path*/, M3dView::DisplayStyle style, M3dView::DisplayStatus status) { // Get draw data // DrawData data; getDrawData(data); view.beginGL(); if ((style == M3dView::kFlatShaded) || (style == M3dView::kGouraudShaded)) { // Push the color settings // glPushAttrib(GL_CURRENT_BIT); if (status == M3dView::kActive) { view.setDrawColor(13, M3dView::kActiveColors); } else { view.setDrawColor(13, M3dView::kDormantColors); } int i; int last; if (data.toggle) { if (status == M3dView::kActive) view.setDrawColor(15, M3dView::kActiveColors); else view.setDrawColor(15, M3dView::kDormantColors); glBegin(GL_TRIANGLE_FAN); last = centreCount - 1; for (i = 0; i < last; ++i) { glVertex3f(centre[i][0] * data.multiplier, centre[i][1] * data.multiplier, centre[i][2] * data.multiplier); } glEnd(); } if (data.state == 0) { if (status == M3dView::kActive) view.setDrawColor(19, M3dView::kActiveColors); else view.setDrawColor(19, M3dView::kDormantColors); glBegin(GL_TRIANGLE_FAN); last = state1Count - 1; for (i = 0; i < last; ++i) { glVertex3f(state1[i][0] * data.multiplier, state1[i][1] * data.multiplier, state1[i][2] * data.multiplier); } glEnd(); } if (data.state == 1) { if (status == M3dView::kActive) view.setDrawColor(21, M3dView::kActiveColors); else view.setDrawColor(21, M3dView::kDormantColors); glBegin(GL_TRIANGLE_FAN); last = state2Count - 1; for (i = 0; i < last; ++i) { glVertex3f(state2[i][0] * data.multiplier, state2[i][1] * data.multiplier, state2[i][2] * data.multiplier); } glEnd(); } if (data.state == 2) { if (status == M3dView::kActive) view.setDrawColor(18, M3dView::kActiveColors); else view.setDrawColor(18, M3dView::kDormantColors); glBegin(GL_TRIANGLE_FAN); last = state3Count - 1; for (i = 0; i < last; ++i) { glVertex3f(state3[i][0] * data.multiplier, state3[i][1] * data.multiplier, state3[i][2] * data.multiplier); } glEnd(); } if (data.state == 3) { if (status == M3dView::kActive) view.setDrawColor(17, M3dView::kActiveColors); else view.setDrawColor(17, M3dView::kDormantColors); glBegin(GL_TRIANGLE_FAN); last = state4Count - 1; for (i = 0; i < last; ++i) { glVertex3f(state4[i][0] * data.multiplier, state4[i][1] * data.multiplier, state4[i][2] * data.multiplier); } glEnd(); } if (status == M3dView::kActive) view.setDrawColor(12, M3dView::kActiveColors); else view.setDrawColor(12, M3dView::kDormantColors); glBegin(GL_TRIANGLE_FAN); last = arrow1Count - 1; for (i = 0; i < last; ++i) { glVertex3f( (float) (- arrow1[i][0] * data.multiplier * cos(data.angle1) - arrow1[i][2] * data.multiplier * sin(data.angle1)), (float) (arrow1[i][1] * data.multiplier + delta1), (float) (arrow1[i][2] * data.multiplier * cos(data.angle1) - arrow1[i][0] * data.multiplier * sin(data.angle1))); } glEnd(); if (status == M3dView::kActive) view.setDrawColor(16, M3dView::kActiveColors); else view.setDrawColor(16, M3dView::kDormantColors); glBegin(GL_TRIANGLE_FAN); last = arrow2Count - 1; for (i = 0; i < last; ++i) { glVertex3f( (float) (- arrow2[i][0] * data.multiplier * cos(data.angle2) - arrow2[i][2] * data.multiplier * sin(data.angle2)), (float) (arrow2[i][1] * data.multiplier + delta2), (float) (arrow2[i][2] * data.multiplier * cos(data.angle2) - arrow2[i][0] * data.multiplier * sin(data.angle2))); } glEnd(); if (status == M3dView::kActive) view.setDrawColor(13, M3dView::kActiveColors); else view.setDrawColor(13, M3dView::kDormantColors); glBegin(GL_TRIANGLE_FAN); last = arrow3Count - 1; for (i = 0; i < last; ++i) { glVertex3f( (float) (- arrow3[i][0] * data.multiplier * cos(data.angle3) - arrow3[i][2] * data.multiplier * sin(data.angle3)), (float) (arrow3[i][1] * data.multiplier + delta3), (float) (arrow3[i][2] * data.multiplier * cos(data.angle3) - arrow3[i][0] * data.multiplier * sin(data.angle3))); } glEnd(); if (status == M3dView::kActive) view.setDrawColor(5, M3dView::kActiveColors); else view.setDrawColor(5, M3dView::kDormantColors); glBegin(GL_TRIANGLE_FAN); last = arrow4Count - 1; for (i = 0; i < last; ++i) { glVertex3f((float) (arrow4[i][0] * data.multiplier), (float) (arrow4[i][1] * data.multiplier + delta4), (float) (arrow4[i][2] * data.multiplier)); } glEnd(); glPopAttrib(); } // Draw the outline of the locator // drawOutline(data); view.endGL(); } void swissArmyLocator::drawOutline(const DrawData& data) { glBegin(GL_LINES); int i; int last; if (data.toggle) { last = centreCount - 1; for (i = 0; i < last; ++i) { glVertex3f(centre[i][0] * data.multiplier, centre[i][1] * data.multiplier, centre[i][2] * data.multiplier); glVertex3f(centre[i+1][0] * data.multiplier, centre[i+1][1] * data.multiplier, centre[i+1][2] * data.multiplier); } } if (data.state == 0) { last = state1Count - 1; for (i = 0; i < last; ++i) { glVertex3f(state1[i][0] * data.multiplier, state1[i][1] * data.multiplier, state1[i][2] * data.multiplier); glVertex3f(state1[i+1][0] * data.multiplier, state1[i+1][1] * data.multiplier, state1[i+1][2] * data.multiplier); } } if (data.state == 1) { last = state2Count - 1; for (i = 0; i < last; ++i) { glVertex3f(state2[i][0] * data.multiplier, state2[i][1] * data.multiplier, state2[i][2] * data.multiplier); glVertex3f(state2[i+1][0] * data.multiplier, state2[i+1][1] * data.multiplier, state2[i+1][2] * data.multiplier); } } if (data.state == 2) { last = state3Count - 1; for (i = 0; i < last; ++i) { glVertex3f(state3[i][0] * data.multiplier, state3[i][1] * data.multiplier, state3[i][2] * data.multiplier); glVertex3f(state3[i+1][0] * data.multiplier, state3[i+1][1] * data.multiplier, state3[i+1][2] * data.multiplier); } } if (data.state == 3) { last = state4Count - 1; for (i = 0; i < last; ++i) { glVertex3f(state4[i][0] * data.multiplier, state4[i][1] * data.multiplier, state4[i][2] * data.multiplier); glVertex3f(state4[i+1][0] * data.multiplier, state4[i+1][1] * data.multiplier, state4[i+1][2] * data.multiplier); } } last = arrow1Count - 1; for (i = 0; i < last; ++i) { glVertex3f((float) (- arrow1[i][0] * data.multiplier * cos(data.angle1) - arrow1[i][2] * data.multiplier * sin(data.angle1)), (float) (arrow1[i][1] * data.multiplier + delta1), (float) (arrow1[i][2] * data.multiplier * cos(data.angle1) - arrow1[i][0] * data.multiplier * sin(data.angle1))); glVertex3f((float) (- arrow1[i+1][0] * data.multiplier * cos(data.angle1) - arrow1[i+1][2] * data.multiplier * sin(data.angle1)), (float) (arrow1[i+1][1] * data.multiplier + delta1), (float) (arrow1[i+1][2] * data.multiplier * cos(data.angle1) - arrow1[i+1][0] * data.multiplier * sin(data.angle1))); } last = arrow2Count - 1; for (i = 0; i < last; ++i) { glVertex3f((float) (- arrow2[i][0] * data.multiplier * cos(data.angle2) - arrow2[i][2] * data.multiplier * sin(data.angle2)), (float) (arrow2[i][1] * data.multiplier + delta2), (float) (arrow2[i][2] * data.multiplier * cos(data.angle2) - arrow2[i][0] * data.multiplier * sin(data.angle2))); glVertex3f((float) (- arrow2[i+1][0] * data.multiplier * cos(data.angle2) - arrow2[i+1][2] * data.multiplier * sin(data.angle2)), (float) (arrow2[i+1][1] * data.multiplier + delta2), (float) (arrow2[i+1][2] * data.multiplier * cos(data.angle2) - arrow2[i+1][0] * data.multiplier * sin(data.angle2))); } last = arrow3Count - 1; for (i = 0; i < last; ++i) { glVertex3f((float) (- arrow3[i][0] * data.multiplier * cos(data.angle3) - arrow3[i][2] * data.multiplier * sin(data.angle3)), (float) (arrow3[i][1] * data.multiplier + delta3), (float) (arrow3[i][2] * data.multiplier * cos(data.angle3) - arrow3[i][0] * data.multiplier * sin(data.angle3))); glVertex3f((float) (- arrow3[i+1][0] * data.multiplier * cos(data.angle3) - arrow3[i+1][2] * data.multiplier * sin(data.angle3)), (float) (arrow3[i+1][1] * data.multiplier + delta3), (float) (arrow3[i+1][2] * data.multiplier * cos(data.angle3) - arrow3[i+1][0] * data.multiplier * sin(data.angle3))); } last = arrow4Count - 1; for (i = 0; i < last; ++i) { glVertex3f((float) (arrow4[i][0] * data.multiplier), (float) (arrow4[i][1] * data.multiplier + delta4), (float) (arrow4[i][2] * data.multiplier)); glVertex3f((float) (arrow4[i+1][0] * data.multiplier), (float) (arrow4[i+1][1] * data.multiplier + delta4), (float) (arrow4[i+1][2] * data.multiplier)); } last = perimeterCount - 1; for (i = 0; i < last; ++i) { glVertex3f(perimeter[i][0] * data.multiplier, perimeter[i][1] * data.multiplier, perimeter[i][2] * data.multiplier); glVertex3f(perimeter[i+1][0] * data.multiplier, perimeter[i+1][1] * data.multiplier, perimeter[i+1][2] * data.multiplier); } glEnd(); } bool swissArmyLocator::isBounded() const { return true; } MBoundingBox swissArmyLocator::boundingBox() const { // Get the size // MObject thisNode = thisMObject(); MPlug plug(thisNode, aSize); MDistance sizeVal; plug.getValue(sizeVal); double multiplier = sizeVal.asCentimeters(); MPoint corner1(-1.1, 0.0, -1.1); MPoint corner2(1.1, 0.0, 1.1); corner1 = corner1 * multiplier; corner2 = corner2 * multiplier; return MBoundingBox(corner1, corner2); } void* swissArmyLocator::creator() { return new swissArmyLocator(); } MStatus swissArmyLocator::initialize() { MFnUnitAttribute unitFn; MFnNumericAttribute numericFn; MStatus stat; MString method("swissArmyLocator::initialize"); MStatus s; int counter = 0; // aSize aSize = unitFn.create("size", "sz", MFnUnitAttribute::kDistance, 0.0, &s); e; unitFn.setDefault(10.0); unitFn.setStorable(true); unitFn.setWritable(true); // aPoint aPointX = numericFn.create("pointX", "ptx", MFnNumericData::kDouble, 0.0, &s); e; aPointY = numericFn.create("pointY", "pty", MFnNumericData::kDouble, 0.0, &s); e; aPointZ = numericFn.create("pointZ", "ptz", MFnNumericData::kDouble, 0.0, &s); e; aPoint = numericFn.create("point", "pt", aPointX, aPointY, aPointZ, &s); e; // aArrow1Angle aArrow1Angle = unitFn.create("arrow1Angle", "a1a", MFnUnitAttribute::kAngle, 0.0, &s); e; // aArrow2Direction aArrow2DirectionX = numericFn.create("arrow2DirectionX", "a2x", MFnNumericData::kDouble, 1.0, &s); e; aArrow2DirectionY = numericFn.create("arrow2DirectionY", "a2y", MFnNumericData::kDouble, 0.0, &s); e; aArrow2DirectionZ = numericFn.create("arrow2DirectionZ", "a2z", MFnNumericData::kDouble, 0.0, &s); e; aArrow2Direction = numericFn.create("arrow2Direction", "dir", aArrow2DirectionX, aArrow2DirectionY, aArrow2DirectionZ, &s); e; // aArrow3Angle aArrow3Angle = unitFn.create("arrow3Angle", "a3a", MFnUnitAttribute::kAngle, 0.0, &s); e; // aArrow4Distance aArrow4Distance = unitFn.create("arrow2Distance", "dis", MFnUnitAttribute::kDistance, 0.0, &s); e; // aState; aState = numericFn.create("state", "s", MFnNumericData::kLong, 0, &s); e; // aToggle; aToggle = numericFn.create("toggle", "t", MFnNumericData::kBoolean, false, &s); e; s = addAttribute(aPoint); e; s = addAttribute(aArrow1Angle); e; s = addAttribute(aArrow2Direction); e; s = addAttribute(aArrow3Angle); e; s = addAttribute(aArrow4Distance); e; s = addAttribute(aState); e; s = addAttribute(aToggle); e; stat = addAttribute(aSize); if (!stat) { stat.perror("addAttribute"); return stat; } MPxManipContainer::addToManipConnectTable(id); return MS::kSuccess; } // // Draw override class for drawing manip in VP2.0 // class swissArmyLocatorOverride : public MHWRender::MPxDrawOverride { public: static MHWRender::MPxDrawOverride* Creator(const MObject& obj) { return new swissArmyLocatorOverride(obj); } virtual ~swissArmyLocatorOverride(); virtual MHWRender::DrawAPI supportedDrawAPIs() const; virtual bool isBounded( const MDagPath& objPath, const MDagPath& cameraPath) const; virtual MBoundingBox boundingBox( const MDagPath& objPath, const MDagPath& cameraPath) const; virtual MUserData* prepareForDraw( const MDagPath& objPath, const MDagPath& cameraPath, const MHWRender::MFrameContext& frameContext, MUserData* oldData); static void draw( const MHWRender::MDrawContext& context, const MUserData* data); private: swissArmyLocatorOverride(const MObject& obj); }; class swissArmyLocatorData : public MUserData { public: swissArmyLocatorData() : MUserData(false) {} // don't delete after draw virtual ~swissArmyLocatorData() {} swissArmyLocator::DrawData drawData; float color[4]; }; swissArmyLocatorOverride::swissArmyLocatorOverride(const MObject& obj) : MHWRender::MPxDrawOverride(obj, swissArmyLocatorOverride::draw) { } swissArmyLocatorOverride::~swissArmyLocatorOverride() { } MHWRender::DrawAPI swissArmyLocatorOverride::supportedDrawAPIs() const { return MHWRender::kOpenGL; } bool swissArmyLocatorOverride::isBounded( const MDagPath& objPath, const MDagPath& cameraPath) const { return true; } MBoundingBox swissArmyLocatorOverride::boundingBox( const MDagPath& objPath, const MDagPath& cameraPath) const { MStatus status; MFnDependencyNode node(objPath.node(), &status); if (!status) return MBoundingBox(); swissArmyLocator* swissNode = dynamic_cast<swissArmyLocator*>(node.userNode()); if (!swissNode) return MBoundingBox(); return swissNode->boundingBox(); } MUserData* swissArmyLocatorOverride::prepareForDraw( const MDagPath& objPath, const MDagPath& cameraPath, const MHWRender::MFrameContext& frameContext, MUserData* oldData) { // get the node MStatus status; MFnDependencyNode node(objPath.node(), &status); if (!status) return NULL; swissArmyLocator* swissNode = dynamic_cast<swissArmyLocator*>(node.userNode()); if (!swissNode) return NULL; // access/create user data for draw callback swissArmyLocatorData* data = dynamic_cast<swissArmyLocatorData*>(oldData); if (!data) { data = new swissArmyLocatorData(); } // compute data and cache it swissNode->getDrawData(data->drawData); MColor color = MHWRender::MGeometryUtilities::wireframeColor(objPath); data->color[0] = color.r; data->color[1] = color.g; data->color[2] = color.b; data->color[3] = 1.0f; return data; } void swissArmyLocatorOverride::draw( const MHWRender::MDrawContext& context, const MUserData* data) { // data MStatus status; MHWRender::MStateManager* stateMgr = context.getStateManager(); const swissArmyLocatorData* locatorData = dynamic_cast<const swissArmyLocatorData*>(data); if (!stateMgr || !locatorData) return; // matrices const MMatrix transform = context.getMatrix(MHWRender::MFrameContext::kWorldViewMtx, &status); if (status != MStatus::kSuccess) return; const MMatrix projection = context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status); if (status != MStatus::kSuccess) return; // do drawing of outline only for now glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadMatrixd(transform.matrix[0]); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadMatrixd(projection.matrix[0]); glPushAttrib(GL_CURRENT_BIT); glColor4fv(locatorData->color); swissArmyLocator::drawOutline(locatorData->drawData); glPopAttrib(); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } // // Entry points // MStatus initializePlugin(MObject obj) { MStatus status; MFnPlugin plugin(obj, PLUGIN_COMPANY, "6.0", "Any"); status = plugin.registerNode("swissArmyLocator", swissArmyLocator::id, &swissArmyLocator::creator, &swissArmyLocator::initialize, MPxNode::kLocatorNode, &swissArmyLocator::classification); if (!status) { status.perror("registerNode"); return status; } status = MHWRender::MDrawRegistry::registerDrawOverrideCreator( swissArmyLocator::classification, swissArmyLocator::registrantId, swissArmyLocatorOverride::Creator); if (!status) { status.perror("registerDrawOverrideCreator"); return status; } status = plugin.registerNode("swissArmyLocatorManip", swissArmyLocatorManip::id, &swissArmyLocatorManip::creator, &swissArmyLocatorManip::initialize, MPxNode::kManipContainer); if (!status) { status.perror("registerNode"); return status; } return status; } MStatus uninitializePlugin(MObject obj) { MStatus status; MFnPlugin plugin(obj); status = plugin.deregisterNode(swissArmyLocator::id); if (!status) { status.perror("deregisterNode"); return status; } status = MHWRender::MDrawRegistry::deregisterDrawOverrideCreator( swissArmyLocator::classification, swissArmyLocator::registrantId); if (!status) { status.perror("deregisterDrawOverrideCreator"); return status; } status = plugin.deregisterNode(swissArmyLocatorManip::id); if (!status) { status.perror("deregisterNode"); return status; } return status; }
28.1016
95
0.670624
[ "geometry", "shape", "transform" ]
70677c1fd9214001fe1f3c84f082b5fd0b9f61fc
7,846
cpp
C++
hash.cpp
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
null
null
null
hash.cpp
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
null
null
null
hash.cpp
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2011, Pythia authors (see AUTHORS file). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include <sstream> using std::string; using std::ostringstream; #include "hash.h" #include "exceptions.h" #include "util/static_assert.h" const CtLong ByteHasher::FNV_64_OFFSET = 14695981039346656037ull; /** * Returns the base 2 logarithm of the next higher power of two. */ unsigned int getlogarithm(unsigned int k) { --k; int m = 1 << (sizeof(int)*8-1); for (unsigned int i=0; i<sizeof(int)*8; ++i) { if ((m >> i) & k) return sizeof(int)*8-i; } return 0; } HashFunction::HashFunction(unsigned int buckets) { if (buckets == 0) { throw MissingParameterException("Number of hash buckets cannot be zero."); } _k = getlogarithm(buckets); } /** * Factory method for creating a TupleHasher. * * Takes a configuration node with the following structure: * * <fn-name> = "bytes" | "modulo" | "range" | "exactrange"| "parammodulo" * | "knuth" | "tpchorderkey" | "willis" | "alwayszero" * * <field-spec> = field = <number>; | fieldrange = ( <number>, <number> ); * * hash : * { * <field-spec> * buckets = <number>; * fn = <fn-name>; * (hash-function specific options) * } * * If fn = "alwayszero", the buckets and field-spec options are ignored. * * There are no function-specific options, apart from the following: * * If fn = "range" | fn = "exactrange", the extra options are: * range = (<scalar>, <scalar>) * * If fn = "parammodulo" | fn = "knuth", the extra options are: * offset = <scalar> * skipbits = <scalar> * */ TupleHasher TupleHasher::create(Schema& schema, const libconfig::Setting& node) { HashFunction* hashfn; ostringstream oss; string hashfnname = node["fn"]; // If no hashing is desired, don't bother checking further. // if (hashfnname == "alwayszero") { hashfn = new AlwaysZeroHasher(); return TupleHasher(0, 0, hashfn, "fn=alwayszero"); } int fieldmin, fieldmax; int buckets = node["buckets"]; // Read list with hash fields, either: // * "field", a scalar value, or // * "fieldrange", an aggregate that has exactly two numeric values // if (node.exists("fieldrange")) { libconfig::Setting& field = node["fieldrange"]; dbgassert(field.isAggregate()); dbgassert(field.getLength() == 2); fieldmin = field[0]; fieldmax = field[1]; } else { libconfig::Setting& field = node["field"]; dbgassert(field.isNumber()); fieldmin = field; fieldmax = fieldmin; } // Construct object, and check preconditions. // if (hashfnname == "bytes") { hashfn = new ByteHasher(buckets); oss << "fn=bytes"; } else if (hashfnname == "tpchq1magic") { hashfn = new TpchQ1MagicByteHasher(); oss << "fn=tpchq1magic"; } else { // A ValueHasher has been requested. // Make sure there's a single hash attribute and its type is numeric. // if (fieldmin != fieldmax) { // It's a composite hash. throw IllegalSchemaDeclarationException(); } switch(schema.get(fieldmin).type) { case CT_INTEGER: case CT_LONG: case CT_DATE: static_assert(sizeof(CtDate) == sizeof(CtLong)); break; default: // It's not a numeric type. throw IllegalSchemaDeclarationException(); } // Preconditions okay. Initialize appropriate function. // if (hashfnname == "modulo") { hashfn = new ModuloValueHasher(buckets); oss << "fn=modulo"; } else if (hashfnname == "range") { int min = node["range"][0]; int max = node["range"][1]; hashfn = new RangeValueHasher(min, max, buckets); oss << "fn=range(min=" << min << ", max=" << max << ")"; } else if (hashfnname == "exactrange") { int min = node["range"][0]; int max = node["range"][1]; hashfn = new ExactRangeValueHasher(min, max, buckets); oss << "fn=exactrange(min=" << min << ", max=" << max << ")"; } else if (hashfnname == "parammodulo") { unsigned int skipbits = 0; unsigned int offset = 0; node.lookupValue("skipbits", skipbits); node.lookupValue("offset", offset); hashfn = new ParameterizedModuloValueHasher(offset, buckets, skipbits); oss << "fn=parammodulo(offset=" << offset << ", skipbits=" << skipbits << ")"; } else if (hashfnname == "knuth") { unsigned int skipbits = 0; unsigned int offset = 0; node.lookupValue("skipbits", skipbits); node.lookupValue("offset", offset); hashfn = new KnuthValueHasher(offset, buckets, skipbits); oss << "fn=knuth(offset=" << offset << ", skipbits=" << skipbits << ")"; } else if (hashfnname == "tpchorderkey") { hashfn = new TpchMagicValueHasher(buckets); oss << "fn=tpchorderkey"; } else if (hashfnname == "willis") { hashfn = new WillisValueHasher(buckets); oss << "fn=willis"; } else { throw UnknownHashException(); } oss << ", buckets=" << buckets; } // Calculate offset and size. // // Offset is offset of fieldmin. // Size is size of fields from fieldmin to fieldmax. // unsigned long long lloffset = reinterpret_cast<unsigned long long>(schema.calcOffset(0, fieldmin)); unsigned short offset = static_cast<unsigned short>(lloffset); unsigned short size = 0; for (int i=fieldmin; i<=fieldmax; ++i) { size += schema.get(i).size; } oss << ", offset=" << offset << ", size=" << size; return TupleHasher(offset, size, hashfn, oss.str()); } vector<HashFunction*> ParameterizedModuloValueHasher::generate(unsigned int passes) { vector<HashFunction*> ret; unsigned int totalbitsset = getlogarithm(buckets()-1); unsigned int bitsperpass = totalbitsset / passes; for (unsigned int i=0; i<passes-1; ++i) { ret.push_back(new ParameterizedModuloValueHasher(_min, (1 << bitsperpass), _skipbits + totalbitsset - ((i+1)*bitsperpass))); } bitsperpass = totalbitsset - ((passes-1) * bitsperpass); ret.push_back(new ParameterizedModuloValueHasher(_min, (1 << bitsperpass), _skipbits)); #ifdef DEBUG unsigned int kfinal = dynamic_cast<ParameterizedModuloValueHasher*>(ret[0])->_k; for (unsigned int i=1; i<ret.size(); ++i) { kfinal |= dynamic_cast<ParameterizedModuloValueHasher*>(ret[i])->_k; assert( (dynamic_cast<ParameterizedModuloValueHasher*>(ret[i])->_k & dynamic_cast<ParameterizedModuloValueHasher*>(ret[i-1])->_k) == 0 ); } assert(kfinal==this->_k); #endif return ret; }
27.822695
83
0.674101
[ "object", "vector" ]
0ad30c5773ed27c08a0630765ebcee2f981015ed
3,013
cpp
C++
FaceAlignment/TestDemo.cpp
williamchenwl/FaceAlignmentByShapeRegression
65e84aca36c756491f6554eb55e10b545223ec79
[ "MIT" ]
8
2017-06-01T15:02:52.000Z
2021-11-10T07:19:08.000Z
FaceAlignment/TestDemo.cpp
williamchenwl/FaceAlignmentByShapeRegression
65e84aca36c756491f6554eb55e10b545223ec79
[ "MIT" ]
null
null
null
FaceAlignment/TestDemo.cpp
williamchenwl/FaceAlignmentByShapeRegression
65e84aca36c756491f6554eb55e10b545223ec79
[ "MIT" ]
1
2021-11-10T07:20:20.000Z
2021-11-10T07:20:20.000Z
/* Author: Bi Sai Date: 2014/06/18 This program is a reimplementation of algorithms in "Face Alignment by Explicit Shape Regression" by Cao et al. If you find any bugs, please email me: soundsilencebisai-at-gmail-dot-com Copyright (c) 2014 Bi Sai The MIT License (MIT) 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 "FaceAlignment.h" using namespace std; using namespace cv; int main(){ vector<Mat_<uchar> > test_images; vector<BoundingBox> test_bounding_box; int test_img_num = 507; int initial_number = 20; int landmark_num = 29; ifstream fin; for(int i = 0;i < test_img_num;i++){ string image_name = "./Data/COFW_Dataset/testImages/"; char buff[30]; sprintf(buff,"%d",i + 1); image_name = image_name + buff + ".jpg"; Mat_<uchar> temp = imread(image_name,0); test_images.push_back(temp); } fin.open("./Data/COFW_Dataset/boundingbox_test.txt"); for(int i = 0;i < test_img_num;i++){ BoundingBox temp; fin>>temp.start_x>>temp.start_y>>temp.width>>temp.height; temp.centroid_x = temp.start_x + temp.width/2.0; temp.centroid_y = temp.start_y + temp.height/2.0; test_bounding_box.push_back(temp); } fin.close(); ShapeRegressor regressor; regressor.Load("./data/model.txt"); while(true){ int index = 1; cout<<"Input index:"<<endl; cin>>index; Mat_<double> current_shape = regressor.Predict(test_images[index],test_bounding_box[index],initial_number); Mat test_image_1 = test_images[index].clone(); cout << landmark_num << endl; for(int i = 0;i < landmark_num;i++){ circle(test_image_1,Point2d(current_shape(i,0),current_shape(i,1)),3,Scalar(255,244,244),-1,8,0); cout << current_shape(i,0) << " " << current_shape(i,1) << endl; } circle(test_image_1,Point2d(10,10),3,Scalar(254,122,123),-1,8,0); imshow("result",test_image_1); waitKey(0); } return 0; }
38.139241
115
0.691338
[ "shape", "vector", "model" ]
0ad7c5049f4c62b7805da8acc8a659a11f3352d3
15,216
cpp
C++
SpectatorView/Compositor/UnityCompositorInterface/UnityCompositorInterface.cpp
OrangeLV/HoloLensCompanionKit
c08f631b6dda7689529e4f908cd09f4d12172402
[ "MIT" ]
null
null
null
SpectatorView/Compositor/UnityCompositorInterface/UnityCompositorInterface.cpp
OrangeLV/HoloLensCompanionKit
c08f631b6dda7689529e4f908cd09f4d12172402
[ "MIT" ]
null
null
null
SpectatorView/Compositor/UnityCompositorInterface/UnityCompositorInterface.cpp
OrangeLV/HoloLensCompanionKit
c08f631b6dda7689529e4f908cd09f4d12172402
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #include "stdafx.h" #include "CompositorShared.h" #include <Windows.h> #include <ppltasks.h> #include "DirectXHelper.h" #include "CompositorInterface.h" #include "HologramQueue.h" #include "PluginAPI\IUnityInterface.h" #include "PluginAPI\IUnityGraphics.h" #include "PluginAPI\IUnityGraphicsD3D11.h" #define UNITYDLL EXTERN_C __declspec(dllexport) static CompositorInterface* ci = NULL; static bool isRecording = false; static bool videoInitialized = false; static BYTE* colorBytes = new BYTE[FRAME_BUFSIZE]; static BYTE* holoBytes = new BYTE[FRAME_BUFSIZE]; #if USE_CANON_SDK static BYTE* hiResHoloBytes = new BYTE[HOLOGRAM_BUFSIZE_HIRES]; #endif #if HARDWARE_ENCODE_VIDEO byte* videoBytes = new byte[(int)(1.5f * FRAME_WIDTH * FRAME_HEIGHT)]; #else byte* videoBytes = new byte[FRAME_BUFSIZE]; #endif static ID3D11Texture2D* g_holoRenderTexture = nullptr; #if USE_CANON_SDK static ID3D11Texture2D* g_hiResHoloRenderTexture = nullptr; #endif static ID3D11Texture2D* g_colorTexture = nullptr; static ID3D11Texture2D* g_holoTexture = nullptr; static ID3D11Texture2D* g_videoTexture = nullptr; static ID3D11Texture2D* g_outputTexture = nullptr; static ID3D11ShaderResourceView* g_UnityColorSRV = nullptr; static ID3D11ShaderResourceView* g_UnityHoloSRV = nullptr; static ID3D11Device* g_pD3D11Device = NULL; static LONGLONG prevFrameDelta = 0; static LONGLONG prevFrameDeltaNoModification = 0; static LONGLONG lastColorTime = INVALID_TIMESTAMP; static LONGLONG lastHoloTime = INVALID_TIMESTAMP; static LONGLONG prevColorTime = INVALID_TIMESTAMP; // Flag to indicate to Unity that a new color frame is ready. static bool newColorFrameExternal = false; static float _frameOffset = INITIAL_FRAME_OFFSET; static LONGLONG _networkLatency = 0; static bool takePicture = false; static bool takeHiResPicture = false; static CRITICAL_SECTION lock; static IUnityInterfaces *s_UnityInterfaces = nullptr; static IUnityGraphics *s_Graphics = nullptr; static void UNITY_INTERFACE_API OnGraphicsDeviceEvent(UnityGfxDeviceEventType eventType) { switch (eventType) { case kUnityGfxDeviceEventInitialize: { IUnityGraphicsD3D11* d3d11 = s_UnityInterfaces->Get<IUnityGraphicsD3D11>(); if (d3d11 != nullptr) { g_pD3D11Device = d3d11->GetDevice(); } } break; case kUnityGfxDeviceEventShutdown: g_pD3D11Device = NULL; break; } } void UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces *unityInterfaces) { InitializeCriticalSection(&lock); s_UnityInterfaces = unityInterfaces; s_Graphics = s_UnityInterfaces->Get<IUnityGraphics>(); s_Graphics->RegisterDeviceEventCallback(OnGraphicsDeviceEvent); OnGraphicsDeviceEvent(kUnityGfxDeviceEventInitialize); } void UNITY_INTERFACE_API UnityPluginUnload() { s_Graphics->UnregisterDeviceEventCallback(OnGraphicsDeviceEvent); OnGraphicsDeviceEvent(kUnityGfxDeviceEventShutdown); DeleteCriticalSection(&lock); } UNITYDLL void UpdateCompositor() { if (ci == NULL) { return; } ci->Update(); prevColorTime = lastColorTime; lastColorTime = ci->GetColorTime(); // These flags are only queried from Unity's update loop, so a lock is not needed. if (prevColorTime != lastColorTime) { newColorFrameExternal = true; } } UNITYDLL void SetHoloTime() { LARGE_INTEGER time; QueryPerformanceCounter(&time); time.QuadPart; lastHoloTime = time.QuadPart; } UNITYDLL void SetExplicitHoloTime(LONGLONG holoTime) { lastHoloTime = holoTime; } // Expose queue state so Unity can determine whether to render the spectator view's render texture or the queued hologram texture. UNITYDLL bool QueueingHoloFrames() { return QUEUE_FRAMES; } // Plugin function to handle a specific rendering event static void __stdcall OnRenderEvent(int eventID) { if (ci == nullptr) { return; } #if QUEUE_FRAMES // Get the time of the current render event. LARGE_INTEGER time; QueryPerformanceCounter(&time); // Update Hologram Queue if (ci != nullptr && g_holoRenderTexture != nullptr && g_holoTexture != nullptr && g_pD3D11Device != nullptr) { LONGLONG frameDuration = ci->GetColorDuration(); auto timestamp = (time.QuadPart) + (LONGLONG)(_frameOffset * (float)frameDuration); const auto hologramFrame = ci->GetNextHologramFrame(timestamp); if (hologramFrame != nullptr) { DirectXHelper::CopyTexture(g_pD3D11Device, hologramFrame->holoTexture, g_holoRenderTexture); const auto closestHologramFrame = ci->FindClosestHologramFrame(ci->GetColorTime(), prevFrameDeltaNoModification); if (closestHologramFrame != nullptr) { if (closestHologramFrame->GetId() != hologramFrame->GetId()) { DirectXHelper::CopyTexture(g_pD3D11Device, g_holoTexture, closestHologramFrame->holoTexture); } else { DirectXHelper::CopyTexture(g_pD3D11Device, g_holoTexture, g_holoRenderTexture); } } } } #endif EnterCriticalSection(&lock); if (g_pD3D11Device != nullptr) { ci->UpdateFrameProvider(); if (!videoInitialized && ci != nullptr) { videoInitialized = ci->InitializeVideoEncoder(g_pD3D11Device); } // Update hi res holo bytes #if USE_CANON_SDK if (g_hiResHoloRenderTexture != nullptr) { if (ci != nullptr && takeHiResPicture) { takeHiResPicture = false; DirectXHelper::GetBytesFromTexture(g_pD3D11Device, g_hiResHoloRenderTexture, FRAME_BPP, hiResHoloBytes); DirectXHelper::FlipHorizontally(hiResHoloBytes, HOLOGRAM_HEIGHT_HIRES, HOLOGRAM_WIDTH_HIRES * FRAME_BPP); ci->TakeCanonPicture(g_pD3D11Device, hiResHoloBytes); } } #endif if (takePicture && g_colorTexture != nullptr) { takePicture = false; BYTE* colorBytes = new BYTE[FRAME_BUFSIZE]; BYTE* holoBytes = new BYTE[FRAME_BUFSIZE]; BYTE* mergedBytes = new BYTE[FRAME_BUFSIZE]; BYTE* colorBytesRaw = new BYTE[FRAME_BUFSIZE_RAW]; DirectXHelper::GetBytesFromTexture(g_pD3D11Device, g_colorTexture, FRAME_BPP, colorBytes); if (ci->OutputYUV()) { memcpy(colorBytesRaw, colorBytes, FRAME_BUFSIZE_RAW); DirectXHelper::ConvertYUVtoBGRA(colorBytesRaw, colorBytes, FRAME_WIDTH, FRAME_HEIGHT, true); } else { DirectXHelper::ConvertBGRAtoRGBA(colorBytes, FRAME_WIDTH, FRAME_HEIGHT, true); } DirectXHelper::GetBytesFromTexture(g_pD3D11Device, g_holoRenderTexture, FRAME_BPP, holoBytes); DirectXHelper::FlipHorizontally(holoBytes, FRAME_HEIGHT, FRAME_WIDTH * FRAME_BPP); memcpy(mergedBytes, colorBytes, FRAME_BUFSIZE); DirectXHelper::AlphaBlend(mergedBytes, holoBytes, FRAME_BUFSIZE, ci->GetAlpha()); ci->TakePicture(g_pD3D11Device, FRAME_WIDTH, FRAME_HEIGHT, FRAME_BPP, mergedBytes, colorBytes, holoBytes); delete[] colorBytes; delete[] colorBytesRaw; delete[] holoBytes; delete[] mergedBytes; } LONGLONG cachedFrameTime = ci->GetColorTime(); if (isRecording && g_videoTexture != nullptr && cachedFrameTime != INVALID_TIMESTAMP && ci->IsVideoFrameReady()) { #if HARDWARE_ENCODE_VIDEO DirectXHelper::GetBytesFromTexture(g_pD3D11Device, g_videoTexture, 1.5f, videoBytes); #else DirectXHelper::GetBytesFromTexture(g_pD3D11Device, g_videoTexture, FRAME_BPP, videoBytes); #endif ci->RecordFrameAsync(videoBytes, cachedFrameTime); } } LeaveCriticalSection(&lock); } UNITYDLL void SetNetworkLatency(LONGLONG networkLatency) { _networkLatency = networkLatency; } UNITYDLL int GetFrameDelta() { if (ci == nullptr) { return 0; } if (lastColorTime == INVALID_TIMESTAMP) { return 0; } LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); LONGLONG frameDuration = ci->GetColorDuration(); LONGLONG frameDelta = (lastHoloTime - lastColorTime); if (frameDelta > 0) { frameDelta *= -1; } frameDelta -= (LONGLONG)(_frameOffset * (float)frameDuration); prevFrameDeltaNoModification = frameDelta; frameDelta -= (LONGLONG)(_networkLatency / 2.0f); frameDelta *= QPC_MULTIPLIER; frameDelta /= frequency.QuadPart; prevFrameDelta = frameDelta; return (int)frameDelta; } UNITYDLL LONGLONG GetColorDuration() { if (ci != nullptr) { return ci->GetColorDuration(); } return (LONGLONG)((1.0f / 30.0f) * QPC_MULTIPLIER); } UNITYDLL bool NewColorFrame() { bool ret = newColorFrameExternal; if (newColorFrameExternal) { newColorFrameExternal = false; } return ret; } // Function to pass a callback to plugin-specific scripts EXTERN_C UnityRenderingEvent __declspec(dllexport) __stdcall GetRenderEventFunc() { return OnRenderEvent; } UNITYDLL int GetFrameWidth() { return HOLOGRAM_WIDTH; } UNITYDLL int GetFrameHeight() { return HOLOGRAM_HEIGHT; } UNITYDLL int GetFrameWidthHiRes() { return HOLOGRAM_WIDTH_HIRES; } UNITYDLL int GetFrameHeightHiRes() { return HOLOGRAM_HEIGHT_HIRES; } UNITYDLL bool CaptureHiResHolograms() { return USE_CANON_SDK; } UNITYDLL bool InitializeFrameProvider() { if (g_outputTexture == nullptr || g_UnityColorSRV == nullptr || g_pD3D11Device == nullptr) { return false; } if (ci == nullptr) { ci = new CompositorInterface(); } bool setColorSRV = false; if (ci != nullptr) { setColorSRV = ci->Initialize(g_pD3D11Device, g_UnityColorSRV, g_outputTexture); } return ci != nullptr && setColorSRV; } UNITYDLL void StopFrameProvider() { if (ci != NULL) { ci->StopFrameProvider(); } } UNITYDLL void SetAudioData(BYTE* audioData) { if (!isRecording) { return; } #if ENCODE_AUDIO // Get the time for the audio frame. LARGE_INTEGER time; QueryPerformanceCounter(&time); if (ci != nullptr) { ci->RecordAudioFrameAsync(audioData, time.QuadPart); } #endif } UNITYDLL void TakePicture() { takePicture = true; } UNITYDLL void TakeCanonPicture() { #if USE_CANON_SDK takeHiResPicture = true; #endif } UNITYDLL void StartRecording() { if (videoInitialized && ci != nullptr) { ci->StartRecording(); isRecording = true; } } UNITYDLL void StopRecording() { if (videoInitialized && ci != nullptr) { ci->StopRecording(); isRecording = false; } } UNITYDLL bool IsRecording() { return isRecording; } UNITYDLL void SetFrameOffset(float frameOffset) { _frameOffset = frameOffset; } UNITYDLL float GetFrameOffset() { return _frameOffset; } UNITYDLL void SetAlpha(float alpha) { if (ci != NULL) { ci->SetAlpha(alpha); } } UNITYDLL float GetAlpha() { if (ci != NULL) { return ci->GetAlpha(); } return 0; } UNITYDLL void Reset() { EnterCriticalSection(&lock); g_colorTexture = nullptr; g_holoTexture = nullptr; g_videoTexture = nullptr; g_outputTexture = nullptr; g_holoRenderTexture = nullptr; #if USE_CANON_SDK g_hiResHoloRenderTexture = nullptr; #endif g_UnityColorSRV = nullptr; g_UnityHoloSRV = nullptr; LeaveCriticalSection(&lock); } UNITYDLL bool OutputYUV() { if (ci == nullptr) { return false; } return ci->OutputYUV(); } UNITYDLL LONGLONG GetCurrentUnityTime() { LARGE_INTEGER time; QueryPerformanceCounter(&time); return time.QuadPart; } UNITYDLL bool HardwareEncodeVideo() { return HARDWARE_ENCODE_VIDEO; } #pragma region CreateExternalTextures UNITYDLL bool SetHoloTexture(ID3D11Texture2D* holoTexture) { // We have already set a texture ptr. if (g_holoRenderTexture != nullptr) { return true; } if (g_holoRenderTexture == nullptr) { g_holoRenderTexture = holoTexture; } return g_holoRenderTexture != nullptr; } UNITYDLL bool SetHoloTextureHiRes(ID3D11Texture2D* holoTexture) { #if USE_CANON_SDK // We have already set a texture ptr. if (g_hiResHoloRenderTexture != nullptr) { return true; } if (g_hiResHoloRenderTexture == nullptr) { g_hiResHoloRenderTexture = holoTexture; } return g_hiResHoloRenderTexture != nullptr; #else return true; #endif } UNITYDLL bool SetVideoRenderTexture(ID3D11Texture2D* tex) { if (g_videoTexture == nullptr) { g_videoTexture = tex; } return g_videoTexture != nullptr; } UNITYDLL bool SetOutputRenderTexture(ID3D11Texture2D* tex) { if (g_outputTexture == nullptr) { g_outputTexture = tex; } return g_outputTexture != nullptr; } UNITYDLL bool CreateUnityColorTexture(ID3D11ShaderResourceView*& srv) { if (g_UnityColorSRV == nullptr && g_pD3D11Device != nullptr) { g_colorTexture = DirectXHelper::CreateTexture(g_pD3D11Device, colorBytes, FRAME_WIDTH, FRAME_HEIGHT, FRAME_BPP); if (g_colorTexture == nullptr) { return false; } g_UnityColorSRV = DirectXHelper::CreateShaderResourceView(g_pD3D11Device, g_colorTexture); if (g_UnityColorSRV == nullptr) { return false; } } srv = g_UnityColorSRV; return true; } UNITYDLL bool CreateUnityHoloTexture(ID3D11ShaderResourceView*& srv) { if (g_UnityHoloSRV == nullptr && g_pD3D11Device != nullptr) { g_holoTexture = DirectXHelper::CreateTexture(g_pD3D11Device, holoBytes, FRAME_WIDTH, FRAME_HEIGHT, FRAME_BPP); if (g_holoTexture == nullptr) { return false; } g_UnityHoloSRV = DirectXHelper::CreateShaderResourceView(g_pD3D11Device, g_holoTexture); if (g_UnityHoloSRV == nullptr) { return false; } } srv = g_UnityHoloSRV; return true; } #pragma endregion CreateExternalTextures
24.822186
131
0.648725
[ "render" ]